> ## Documentation Index
> Fetch the complete documentation index at: https://docs.air3.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Issue a KYC credential

> Wire a KYC webhook to AIR direct issuance so signed, encrypted verifiable credentials land in users' AIR Accounts with no active session required.

This recipe shows how to issue a verifiable KYC credential the moment your identity provider confirms a user, using [direct issuance](https://docs.air3.com/products/identity/issuing-credentials#direct-issuance). The user does not need an active session.

## What you'll build

1. A webhook handler that fires when your KYC provider confirms a user.
2. A Partner JWT signed with the `issue` scope. The JWT for `initialize-user` also carries the recipient's email.
3. A call to `initialize-user` to resolve the recipient's DID, encryption public key, and signing public key.
4. Issuance: build the VC bound to the holder's signing key, sign it with issuer keys, encrypt it to the holder, and store it in DStorage.

## Prerequisites

* A published issuance program with a schema that includes KYC fields (e.g. `kycVerified`, `kycLevel`, `verifiedAt`)
* [Partner JWT](https://docs.air3.com/get-started/authentication/sdk-auth.md) signing configured (RS256 or ES256)
* Issuer signing keys available to your backend

## Step 1: Handle the KYC webhook

When your KYC provider (Sumsub, Onfido, Jumio, etc.) sends a verification-complete callback, extract the user email and verification result.

```js theme={null}
const express = require("express");
const app = express();
app.use(express.json());

app.post("/webhooks/kyc-complete", async (req, res) => {
  const { userEmail, kycLevel, verifiedAt } = req.body;

  if (!userEmail) return res.status(400).json({ error: "Missing userEmail" });

  try {
    const result = await issueKycCredential(userEmail, { kycLevel, verifiedAt });
    res.json({ success: true, storagePath: result.storagePath });
  } catch (err) {
    console.error("Issuance failed:", err.message);
    res.status(500).json({ error: err.message });
  }
});
```

## Step 2: Sign a Partner JWT

Generate a short-lived JWT with `scope: "issue"`. For the `initialize-user` call, add the recipient's `email` claim; the JWT for `dstorage/vcs` does not carry one.

> [!WARNING]
>
> The recipient's email (the `email` claim sent to `initialize-user`) is the routing key that determines which AIR Account the credential lands in. Resolve it from the triggering event, and never reuse a partner, service, admin, or static email across recipients — every credential issued against that email lands in the same account.

```js theme={null}
const jwt = require("jsonwebtoken");
const fs = require("fs");

const privateKey = fs.readFileSync("path/to/private.key");

function getPartnerJwt(claims = {}) {
  const now = Math.floor(Date.now() / 1000);
  return jwt.sign(
    {
      ...claims, // { email } for initialize-user only
      partnerId: process.env.PARTNER_ID,
      scope: "issue",
      iat: now,
      exp: now + 5 * 60,
    },
    privateKey,
    {
      algorithm: "RS256",
      header: { kid: process.env.KEY_ID, typ: "JWT" },
    }
  );
}
```

## Step 3: Resolve the user and issue

Resolve the recipient's AIR Account with `initialize-user`, then build, sign, encrypt, and store the credential. `buildVc`, `signVc`, and `encryptToHolder` are issuer-controlled helpers backed by your signing keys.

```js theme={null}
const { buildVc, signVc, encryptToHolder } = require("./lib/credential");

const isProduction = process.env.NODE_ENV === "production";
const AIR_API_ORIGIN = isProduction
  ? "https://air.api.air3.com"
  : "https://air.api.sandbox.air3.com";
const BASE_URL = isProduction
  ? "https://mocachain-mainnet.api.air3.com/v1"
  : "https://api.sandbox.mocachain.org/v1";

async function issueKycCredential(recipientEmail, kycData) {
  // 1. Resolve or create the recipient's AIR Account
  const initRes = await fetch(`${AIR_API_ORIGIN}/v2/auth/initialize-user`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-partner-id": process.env.PARTNER_ID },
    body: JSON.stringify({ partnerJwt: getPartnerJwt({ email: recipientEmail }) }),
  });
  if (!initRes.ok) throw new Error(`initialize-user failed: ${initRes.status}`);
  const { did, publicKey, signingKey } = await initRes.json();
  if (!did || !publicKey) throw new Error("initialize-user did not resolve the recipient");

  // 2. Build, sign, and encrypt the credential (issuer-controlled)
  const schemaId = process.env.CREDENTIAL_ID;
  const vc = buildVc({
    holderDid: did,
    cnf: signingKey, // binds the credential to the holder's signing key
    schemaId,
    credentialSubject: {
      kycVerified: true,
      kycLevel: kycData.kycLevel,
      verifiedAt: kycData.verifiedAt || new Date().toISOString(),
    },
  });
  const signed = signVc(vc); // SD-JWT VC, issuer-controlled key
  const encrypted = encryptToHolder(signed, publicKey);

  // 3. Store the encrypted envelope in DStorage
  const storeRes = await fetch(`${BASE_URL}/dstorage/vcs`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-partner-auth": getPartnerJwt() },
    body: JSON.stringify({
      holderDid: did,
      proofType: "SD_JWT_VC",
      schemaId,
      expiresAt: vc.expirationDate,
      data: encrypted.encryptedData,
      iv: encrypted.iv,
      authTag: encrypted.authTag,
      encryptedKey: encrypted.dataEncPublicKey,
      externalId: vc.id,
    }),
  });
  if (!storeRes.ok) throw new Error(`dstorage/vcs failed: ${storeRes.status}`);
  return storeRes.json(); // { storagePath }
}
```

Issuance typically completes in \~1–4 seconds. Record the returned `storagePath` as your issuance result; the credential is immediately available for the holder to present to any AIR verifier.

## Next steps

* [Reusable KYC demo](https://demo.air3.com/demo/reusable-kyc) to see the issued credential reused by a partner

* [Issuance API Reference](https://docs.air3.com/api-reference/issuance-api.md) for full endpoint details

* [Registering credential types](https://docs.air3.com/products/identity/schema-creation.md) to register your KYC credential type

* [Credential Verification](https://docs.air3.com/products/identity/verify) to let verifiers check the credential


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.