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

# React Native KYC SDK：移动端身份验证

> Didit 提供 React Native 与 Expo KYC SDK，支持 TypeScript、原生 iOS 和 Android，以及 NFC 电子护照验证。单次完整 KYC 检查起价 $0.33，每月 $10 免费额度，无需合同。



React Native SDK 集成提示词
        将提示词复制到剪贴板



      
      

\<pre>

\`Integrate Didit identity verification into my React Native app using the native SDK.

\## Requirements
\- React Native 0.76+ (New Architecture / TurboModules)
\- Node.js 20+, TypeScript 5+
\- iOS 13.0+ (NFC requires iOS 15+)
\- Android API 24+ (Android 7.0), Kotlin 1.9+, Java 17+
\- New Architecture (TurboModules) only - package is published as @didit-protocol/sdk-react-native v4.x (latest 4.13.2)

\## Installation

\### Expo (recommended)
npx expo install @didit-protocol/sdk-react-native

Add to app.json (NFC is enabled by default):
\{
"expo": {
"plugins": ["@didit-protocol/sdk-react-native"]
}
}

To opt out of NFC dependencies:
\{
"expo": {
"plugins": [["@didit-protocol/sdk-react-native", { "iosNfcEnabled": false, "androidNfcEnabled": false }]]
}
}

The config plugin automatically adds the Didit Maven repo (Android), the DiditSDK podspec (iOS),
and BouncyCastle packaging rules for Android. This SDK requires a development build — it does not work in Expo Go.
The plugin does not edit Info.plist: add the iOS permission keys and, for NFC, the ISO7816 select identifiers
(including D392F000260100000001 for the Japan My Number Card) under expo.ios.infoPlist in app.json.

\### React Native CLI
npm install @didit-protocol/sdk-react-native

iOS — add this block to ios/Podfile inside the app target (NFC-aware; pins to iOS 15 when NFC is on):
didit_sdk_ios_nfc_enabled = ENV.fetch('DIDIT_SDK_IOS_NFC_ENABLED', 'true').downcase != 'false'
didit_sdk_ios_pod = didit_sdk_ios_nfc_enabled ? 'DiditSDK' : 'DiditSDK/Core'
pod didit_sdk_ios_pod, :podspec => 'https://raw.githubusercontent.com/didit-protocol/sdk-ios/4.13.2/DiditSDK.podspec'
The tag in that URL must equal diditNativeSdkVersions.ios in the package (4.13.2); do not use 'main', because the package requires that exact version and every pod install fails when the URL resolves to a different one.
Then: cd ios && bundle exec pod install

Android — add to settings.gradle (dependencyResolutionManagement.repositories):
maven { url "https://raw.githubusercontent.com/didit-protocol/sdk-android/main/repository" }
To disable NFC, add diditSdkAndroidNfcEnabled=false to android/gradle.properties.

\## Backend: Create Session (your server)
POST https://verification.didit.me/v3/session/
Headers: { "x-api-key": DIDIT_API_KEY, "Content-Type": "application/json" }
Body: { "workflow_id": DIDIT_WORKFLOW_ID, "vendor_data": "user-id" }
Response: { "session_id": "uuid", "session_token": "short-token", "url": "https://verify.didit.me/session/short-token", "status": "Not Started" }
Send session_token to the React Native app (never expose DIDIT_API_KEY to the device).

\## Integration
import { startVerification, VerificationStatus } from '@didit-protocol/sdk-react-native';

// Option A: With session token from your backend (recommended)
const result = await startVerification('session-token-from-backend');

// Option B: With workflow ID (SDK creates session internally)
const result = await startVerificationWithWorkflow('your-workflow-id', {
vendorData: 'user-123',
});

// Handle result
switch (result.type) {
case 'completed':
if (result.session.status === VerificationStatus.Approved) { /* grant access */ }
break;
case 'cancelled':
// User dismissed the verification flow
break;
case 'failed':
// SDK error — show result.error.message
break;
}

\## Result Statuses (VerificationStatus enum)
\- VerificationStatus.Approved — user identity verified, grant access
\- VerificationStatus.Declined — verification failed, show retry or contact support
\- VerificationStatus.Pending  — needs manual review by your compliance team

\## Full Verification Results
The SDK only returns the status. Full decision data (document fields, face match scores, AML hits, etc.) arrives via webhook to your backend.
Set up webhooks: https://docs.didit.me/integration/webhooks

\## Rate Limits (session creation)
\- 600 session-create requests / minute per x-api-key (see https://docs.didit.me/integration/rate-limiting)
\- On 429, retry honouring Retry-After / X-RateLimit-* headers

\## Environment Variables (backend only — never expose in the app)
\- DIDIT_API_KEY — from Didit Console > API & Webhooks
\- DIDIT_WORKFLOW_ID — from Didit Console > Workflows

\## Docs
\- React Native SDK: https://docs.didit.me/integration/native-sdks/react-native-sdk
\- GitHub: https://github.com/didit-protocol/sdk-react-native
\- npm: https://www.npmjs.com/package/@didit-protocol/sdk-react-native
\- Webhooks: https://docs.didit.me/integration/webhooks
\- API Reference: https://docs.didit.me/api-reference/overview`

\</pre>



      
      

粘贴到

一个跨平台的 React Native SDK，封装了原生 iOS 和 Android SDK，并提供统一的 TypeScript API 用于身份验证。> [card] [GitHub 仓库](https://github.com/didit-protocol/sdk-react-native)
>
> 在 GitHub 上查看源代码和示例> [card] [npm 包](https://www.npmjs.com/package/@didit-protocol/sdk-react-native)
>
> @didit-protocol/sdk-react-native> [!NOTE]
>
> ### **原生 SDK**: 这是 React Native 和 Expo 应用推荐的集成方式。该 SDK 封装了原生 iOS 和 Android SDK，可提供最佳用户体验、经过优化的相机处理，并完整支持 NFC。***## 环境要求| 要求 | 最低版本 |
| - | - |
| React Native | 0.76+（新架构 / TurboModules） |
| Node.js | 20+ |
| TypeScript | 5+ |### 平台要求| 平台 | 最低版本 | 说明 |
| - | - | - |
| iOS | 13.0+ | 读取 NFC 护照需要 iOS 15.0+ |
| Android | API 24+（7.0） | Kotlin 1.9+，Java 17+ |> [!NOTE]
>
> **生物识别同意需要原生 4.10.0 或更高版本。** 对于受 Illinois、Texas 或 Colorado 州法律覆盖的用户，Didit 可以在首次人脸采集之前请求明确的[生物识别同意](https://docs.didit.me/zh/getting-started/biometric-consent.md)。固定使用原生 iOS 和 Android 4.10.0 或更高版本的 React Native SDK 版本会显示该步骤。较早的版本无法显示该步骤：其会话照常运行，但决策结果会将同意报告为未收集（`biometric_consent.reason: "BIOMETRIC_CONSENT_UNSUPPORTED_SDK"`）。如果您在这些州验证用户，请升级。***## 安装### Expo (推荐)```bash theme={null}
npx expo install @didit-protocol/sdk-react-native
```然后将配置插件添加到 `app.json`（或 `app.config.js`）中。默认启用 NFC：```json theme={null}
{
  "expo": {
    "plugins": ["@didit-protocol/sdk-react-native"]
  }
}
```该插件会自动配置两个平台：- **Android：** 将 Didit Maven 仓库添加到 Gradle，设置 `diditSdkAndroidNfcEnabled` Gradle 属性，并应用 BouncyCastle 依赖与打包规则
- **iOS：** 将 DiditSDK podspec 添加到 Podfile 中（启用 NFC 时固定为 iOS 15）该插件不会修改 `Info.plist`。请添加 [iOS 权限键](#ios)，如需 NFC，还要在同一文件的 `ios.infoPlist` 下添加 ISO7816 选择标识符。`D392F000260100000001` 可让 SDK 通过 [JPKI](https://docs.didit.me/zh/core-technology/nfc-verification/overview.md#日本个人编号卡（jpki）) 读取日本 My Number Card：```json theme={null}
{
  "expo": {
    "ios": {
      "infoPlist": {
        "NFCReaderUsageDescription": "NFC is used to read passport chip data for identity verification.",
        "com.apple.developer.nfc.readersession.iso7816.select-identifiers": [
          "D23300000045737445494420763335",
          "A0000002471001",
          "A0000002472001",
          "00000000000000",
          "D392F000260100000001"
        ]
      }
    }
  }
}
```#### 禁用 NFC 依赖项如需在不支持 NFC 的情况下构建（二进制文件更小，且无需 NFC 能力），请传入插件选项：```json theme={null}
{
  "expo": {
    "plugins": [
      [
        "@didit-protocol/sdk-react-native",
        { "iosNfcEnabled": false, "androidNfcEnabled": false }
      ]
    ]
  }
}
```禁用 NFC 时，您无需配置 iOS NFC 能力、NFC 权限配置（entitlements），也无需进行与 NFC 相关的描述文件（provisioning）设置。> [!WARNING]
>
> 此 SDK 使用的原生模块（相机、NFC）在 **Expo Go 中不可用**。您必须使用[开发构建](https://docs.expo.dev/develop/development-builds/introduction/)，或运行 `npx expo prebuild` 以生成原生项目。### React Native CLI```bash theme={null}
npm install @didit-protocol/sdk-react-native
# or
yarn add @didit-protocol/sdk-react-native
```#### iOS 设置将 DiditSDK pod 添加到您的 `Podfile` 中（它不在 CocoaPods trunk 上）。下面的代码块会读取 `DIDIT_SDK_IOS_NFC_ENABLED` 环境变量，以便您在安装时切换是否使用不含 NFC 的子规格（`DiditSDK/Core`）：```ruby theme={null}
# In your ios/Podfile — at the top, before the target block:
didit_sdk_ios_nfc_enabled = ENV.fetch('DIDIT_SDK_IOS_NFC_ENABLED', 'true').downcase != 'false'

def max_ios_version(*versions)
  versions.map(&:to_s).max_by { |version| Gem::Version.new(version) }
end

platform :ios, didit_sdk_ios_nfc_enabled ? max_ios_version(min_ios_version_supported, '15.0') : min_ios_version_supported

# Inside your app target:
didit_sdk_ios_pod = didit_sdk_ios_nfc_enabled ? 'DiditSDK' : 'DiditSDK/Core'
pod didit_sdk_ios_pod, :podspec => 'https://raw.githubusercontent.com/didit-protocol/sdk-ios/4.13.2/DiditSDK.podspec'
```> [!WARNING]
>
> podspec URL 中的标签必须与已安装包版本中的 `diditNativeSdkVersions.ios` 一致。React Native `4.13.2` 固定了原生 iOS `4.13.2` 和原生 Android `4.13.2`。请勿将 podspec 指向 `main`：该包依赖于这个确切的原生 iOS 版本，因此一旦 `main` 向前推进，CocoaPods 就会看到 `DiditSDK` 的两个互不兼容的要求，每次 `pod install` 都会失败。Expo 配置插件会为您推导此 URL；只有不使用 Expo 的 React Native CLI 方式才需要手动写出。然后安装依赖项：```bash theme={null}
cd ios
bundle exec pod install
```如需在不含 NFC 依赖的情况下重新构建，请清理 CocoaPods，并在设置环境变量后重新运行：```bash theme={null}
cd ios
rm -rf Pods Podfile.lock
DIDIT_SDK_IOS_NFC_ENABLED=false bundle exec pod install
```#### Android 设置将 Didit Maven 仓库添加到项目级 `settings.gradle` 中：```groovy theme={null}
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url "https://raw.githubusercontent.com/didit-protocol/sdk-android/main/repository" }
    }
}
```在应用的 `android/app/build.gradle` 中（位于 `android { ... }` 代码块内）添加以下内容，以解决 BouncyCastle 重复类冲突，以及 DiditSDK 传递依赖可能引发的 OSGI `MANIFEST.MF` 重复问题：```groovy theme={null}
android {
    configurations.configureEach {
        exclude group: 'org.bouncycastle', module: 'bcprov-jdk15to18'
        exclude group: 'org.bouncycastle', module: 'bcutil-jdk15to18'
        exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15to18'
        exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on'
    }
    packaging {
        resources {
            pickFirsts += ['org/bouncycastle/**']
            excludes += 'META-INF/versions/9/OSGI-INF/MANIFEST.MF'
        }
    }
}
```如需在不含 Android NFC 依赖的情况下构建（使用 `me.didit:didit-sdk-core` 构件，而非 `me.didit:didit-sdk`），请将以下内容添加到 `android/gradle.properties` 中：```properties theme={null}
diditSdkAndroidNfcEnabled=false
```删除该属性，或将其设置为 `true`，即可使用包含 NFC 的完整 Android SDK。***## 权限### iOS将以下键添加到应用的 `Info.plist` 中。缺少必需的 iOS 隐私键会导致 iOS 在 SDK 访问受保护资源时立即终止应用。| 权限 | Info.plist 键 | 说明 | 必需 |
| - | - | - | - |
| 相机 | `NSCameraUsageDescription` | 证件扫描与人脸验证 | 是 |
| 麦克风 | `NSMicrophoneUsageDescription` | 活体视频录制 | 是 |
| 相册 | `NSPhotoLibraryUsageDescription` | 上传证件图片 | 是 |
| 位置信息 | `NSLocationWhenInUseUsageDescription` | 用于防欺诈的地理位置 | 是 |
| NFC | `NFCReaderUsageDescription` | 读取护照/身份证件中的 NFC 芯片 | 使用 NFC 时 |```xml theme={null}
<key>NSCameraUsageDescription</key>
<string>Camera access is required to scan your identity documents for verification.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is required to record video for liveness verification.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Photo library access is required to upload document images.</string>
<key>NFCReaderUsageDescription</key>
<string>NFC is used to read passport chip data for identity verification.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location access is used to detect your country for identity verification.</string>
```#### NFC 配置要启用对带芯片的护照和身份证的 NFC 读取：1) 在 Xcode 中**添加 NFC 功能**：
   * 选择你的 Target > **Signing & Capabilities** > **+ Capability** > **Near Field Communication Tag Reading**

2) 将 ISO7816 标识符**添加到 `Info.plist`**：```xml theme={null}
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
    <string>D23300000045737445494420763335</string>
    <string>A0000002471001</string>
    <string>A0000002472001</string>
    <string>00000000000000</string>
    <string>D392F000260100000001</string>
</array>
````D392F000260100000001` 使 SDK 能够通过 [JPKI](https://docs.didit.me/zh/core-technology/nfc-verification/overview.md#日本个人编号卡（jpki）) 读取日本 My Number Card：若没有它，iOS 不会将该卡报告给 SDK。My Number Card 读取功能尚未在生产环境中启用，且该标识符对其他证件没有任何影响，因此你现在即可添加。3) **添加一个启用 NFC 标签读取的授权文件**：```xml theme={null}
<key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>TAG</string>
</array>
```请确保应用的描述文件包含 NFC Tag Reading 功能。禁用 NFC 时无需此 NFC 配置。### Android以下权限在 SDK 的 `AndroidManifest.xml` 中声明，并会自动合并：| 权限 | 说明 | 必需 |
| - | - | - |
| `INTERNET` | 用于 API 通信的网络访问 | 是 |
| `ACCESS_NETWORK_STATE` | 检测网络可用性 | 是 |
| `CAMERA` | 证件扫描与人脸验证 | 是 |
| `NFC` | 读取护照/身份证件中的 NFC 芯片 | 使用 NFC 时 |相机和 NFC 硬件功能被声明为可选（`android:required="false"`），因此你的应用可以安装在不具备这些功能的设备上。***## 快速开始```tsx theme={null}
import { startVerification, VerificationStatus } from '@didit-protocol/sdk-react-native';

// Start verification with a session token from your backend
const result = await startVerification('your-session-token');

switch (result.type) {
  case 'completed':
    if (result.session.status === VerificationStatus.Approved) {
      console.log('Identity verified!');
    }
    break;
  case 'cancelled':
    console.log('User cancelled');
    break;
  case 'failed':
    console.log('Error:', result.error.message);
    break;
}
```***## 集成方式SDK 支持两种集成方式：### 方式 1: 会话 token (推荐用于生产环境)使用[创建验证会话 API](https://docs.didit.me/zh/sessions-api/create-session.md)在你的后端创建会话，然后将 token 传递给 SDK：```tsx theme={null}
import { startVerification } from '@didit-protocol/sdk-react-native';

// Your backend creates a session and returns the token
const sessionToken = await yourBackend.createVerificationSession(userId);

// Pass the token to the SDK
const result = await startVerification(sessionToken);
```此方式可让你完全控制以下内容：- 将会话与你的用户关联（`vendor_data`）
- 设置自定义元数据
- 按会话配置回调### 方式 2: 工作流 ID (更简单的集成)对于更简单的集成，SDK 可以直接使用你的工作流 ID 创建会话：```tsx theme={null}
import { startVerificationWithWorkflow } from '@didit-protocol/sdk-react-native';

const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  contactDetails: { email: 'user@example.com' },
  config: { loggingEnabled: true },
});
```***## 配置通过传递 `DiditConfig` 对象来自定义 SDK 行为：```tsx theme={null}
const result = await startVerification('your-session-token', {
  languageCode: 'es',           // Force Spanish language
  showLanguageSelector: true,   // Let the user change language
  fontFamily: 'Avenir',         // Custom font (must be registered natively)
  loggingEnabled: true,         // Enable debug logging
  showCloseButton: true,        // Show close (X) button on step screens
  showExitConfirmation: true,   // Confirm before exit
  closeOnComplete: false,       // Auto-dismiss UI on completion
});
```对于 `startVerificationWithWorkflow`，请在 `options.config` 中传递配置：```tsx theme={null}
const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  config: {
    languageCode: 'es',
    showLanguageSelector: true,
    loggingEnabled: true,
    showCloseButton: true,
    showExitConfirmation: true,
  },
});
```### 配置选项| 属性 | 类型 | 默认值 | 说明 |
| - | - | - | - |
| `languageCode` | `string` | 设备语言区域 | ISO 639-1 语言代码（例如 `"en"`、`"fr"`、`"ar"`） |
| `showLanguageSelector` | `boolean` | `false` | 在欢迎页面显示网页风格的语言选择器 |
| `fontFamily` | `string` | 系统字体 | 自定义字体族名称（必须在原生端注册） |
| `loggingEnabled` | `boolean` | `false` | 启用 SDK 调试日志 |
| `showCloseButton` | `boolean` | `true` | 在验证步骤页面显示关闭（X）按钮 |
| `showExitConfirmation` | `boolean` | `true` | 用户尝试退出时显示确认对话框 |
| `closeOnComplete` | `boolean` | `false` | 完成后自动关闭验证界面 |
| `defaultDocumentCamera` | `CameraLens?` | 原生默认值（`CameraLens.Back`） | 证件拍摄页面打开时使用的镜头 |
| `defaultLivenessCamera` | `CameraLens?` | 原生默认值（`CameraLens.Front`） | 人脸（活体）拍摄页面打开时使用的镜头 |
| `showDocumentCameraSwitchButton` | `boolean` | `true` | 在证件拍摄页面显示拍摄时的相机切换按钮 |
| `showLivenessCameraSwitchButton` | `boolean` | `true` | 在人脸拍摄页面显示拍摄时的相机切换按钮 |### 相机选项相机选项与[Web SDK 相机选项](https://docs.didit.me/zh/integration/web-sdks/javascript-sdk.md#摄像头选项)一致。
每个镜头为 `CameraLens.Front` 或 `CameraLens.Back`。
如果设备没有所请求的镜头，SDK 将使用其第一个可用相机。
在仅有一个相机的设备上，相机切换按钮也会被隐藏。
将切换选项设为 `false`，可将用户锁定在该步骤的默认镜头上。```tsx theme={null}
import { startVerification, CameraLens } from '@didit-protocol/sdk-react-native';

await startVerification('your-session-token', {
  defaultLivenessCamera: CameraLens.Back,
  showLivenessCameraSwitchButton: false,
});
```> [!NOTE]
>
> **主题与颜色**：颜色、背景和引导页设置通过 Didit Console 中的[白标设置](https://business.didit.me)进行配置，而不是在 SDK 配置中设置。这可确保各平台的品牌形象保持一致。***## 语言支持SDK 支持 **54 种语言**。如果未指定语言，SDK 将使用设备语言区域，并以英语作为后备。```tsx theme={null}
// Use device locale (default)
await startVerification(token);

// Force specific language
await startVerification(token, { languageCode: 'fr' });

// Let the user change language on the welcome screen
await startVerification(token, { showLanguageSelector: true });
```**[查看所有支持的语言 →](https://docs.didit.me/zh/integration/supported-languages.md)*****## 高级选项这些选项仅可与 `startVerificationWithWorkflow` 一起使用，此时由 SDK 代你创建会话。### 联系方式 (预填与通知)提供联系方式以预填充验证表单并启用邮件通知：```tsx theme={null}
const result = await startVerificationWithWorkflow('your-workflow-id', {
  contactDetails: {
    email: 'user@example.com',
    sendNotificationEmails: true,  // Send status update emails
    emailLang: 'en',               // Email language (ISO 639-1)
    phone: '+14155552671',         // E.164 format
  },
});
```### 预期用户信息 (交叉验证)提供预期的用户信息，以便与提取的证件数据进行自动交叉验证：```tsx theme={null}
const result = await startVerificationWithWorkflow('your-workflow-id', {
  expectedDetails: {
    firstName: 'John',
    lastName: 'Doe',
    dateOfBirth: '1990-05-15',     // YYYY-MM-DD format
    gender: 'M',
    nationality: 'USA',            // ISO 3166-1 alpha-3
    country: 'USA',
    address: '1 Market St, San Francisco, CA',
    identificationNumber: 'A1234567',
    ipAddress: '203.0.113.42',
    portraitImage: 'https://...',  // URL or base64 reference image
  },
});
````ExpectedDetails` 的所有字段均为可选。完整类型定义请参见 [`src/types.ts`](https://github.com/didit-protocol/sdk-react-native/blob/main/src/types.ts)。### 自定义元数据在会话中存储自定义 JSON 元数据（不向用户显示）：```tsx theme={null}
const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  metadata: '{"internalId": "abc123", "source": "mobile-app"}',
});
```***## 处理结果`startVerification` 和 `startVerificationWithWorkflow` 均返回 `Promise<VerificationResult>`。该结果是判别联合类型，请使用 `type` 字段判断验证结果。### 结果类型| 类型 | 说明 |
| - | - |
| `completed` | 验证流程已完成（请通过 `session.status` 查看结果） |
| `cancelled` | 用户取消了验证流程 |
| `failed` | 验证过程中发生错误 |### SessionData 属性| 属性 | 类型 | 说明 |
| - | - | - |
| `sessionId` | `string` | 会话的唯一标识符 |
| `status` | `VerificationStatus` | `Approved`、`Pending` 或 `Declined` |### 错误类型| 错误 | 说明 |
| - | - |
| `sessionExpired` | 会话已过期 |
| `networkError` | 网络连接问题 |
| `cameraAccessDenied` | 未授予摄像头权限 |
| `notInitialized` | SDK 未初始化（仅限 Android） |
| `apiError` | API 请求失败 |
| `unknown` | 其他错误，附带错误信息 |### 连接中断如果设备在验证过程中断开网络连接，SDK 会用“无网络连接”页面覆盖当前流程，而不会让某个步骤一直处于加载状态。
SDK 会在后台持续检测，一旦可以连通 Didit，便会自动关闭该页面，用户从中断时所在的步骤继续操作。
该页面提供 **Try Again** 按钮，若 `showCloseButton` 为 `true`（默认值），还会显示 **Exit Verification** 按钮。
点击退出会以 `failed` 结果结束验证，错误为 `networkError`，这样您的应用就能知道用户是因网络连接问题而离开。### 完整结果处理示例```tsx theme={null}
import {
  startVerification,
  VerificationStatus,
  type VerificationResult,
} from '@didit-protocol/sdk-react-native';

async function verify(token: string) {
  const result: VerificationResult = await startVerification(token);

  switch (result.type) {
    case 'completed':
      switch (result.session.status) {
        case VerificationStatus.Approved:
          console.log('Approved! Session:', result.session.sessionId);
          // User is verified — grant access
          break;
        case VerificationStatus.Pending:
          console.log('Under review. Session:', result.session.sessionId);
          // Show "verification in progress" UI
          break;
        case VerificationStatus.Declined:
          console.log('Declined. Session:', result.session.sessionId);
          // Handle declined verification
          break;
      }
      break;

    case 'cancelled':
      console.log('User cancelled the verification.');
      // Maybe show retry option
      break;

    case 'failed':
      console.log(`Error [${result.error.type}]: ${result.error.message}`);
      // Handle error — show retry or contact support
      break;
  }
}
```***## 端到端示例 (后端会话 → React Native SDK → Webhook)这是可用于生产环境的集成方案：您的后端创建会话，您的 RN 应用接收 `session_token`，SDK 运行验证流程。最终决策通过 Webhook 发送到您的后端，切勿仅依赖客户端的结果。### 1. 后端：创建会话```ts theme={null}
// Node.js / Express example. Run on your server. NEVER ship DIDIT_API_KEY to the device.
import express from "express";

const app = express();
app.use(express.json());

app.post("/api/verification/start", async (req, res) => {
  const response = await fetch("https://verification.didit.me/v3/session/", {
    method: "POST",
    headers: {
      "x-api-key": process.env.DIDIT_API_KEY!,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      workflow_id: process.env.DIDIT_WORKFLOW_ID,
      vendor_data: req.body.userId, // your stable user id
    }),
  });

  if (!response.ok) {
    return res.status(500).json({ error: `Didit ${response.status}` });
  }

  const { session_id, session_token } = await response.json();
  // Persist session_id <-> userId so you can match the webhook later.
  res.json({ session_id, session_token });
});
```### 2. React Native：交换令牌并启动 SDK```tsx theme={null}
import { useCallback, useState } from 'react';
import { Button, View } from 'react-native';
import {
  startVerification,
  VerificationStatus,
  type VerificationResult,
} from '@didit-protocol/sdk-react-native';

export function VerifyButton({ userId }: { userId: string }) {
  const [loading, setLoading] = useState(false);

  const onPress = useCallback(async () => {
    setLoading(true);
    try {
      const r = await fetch('https://your-backend.example.com/api/verification/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId }),
      });
      const { session_token } = await r.json();

      const result: VerificationResult = await startVerification(session_token);

      switch (result.type) {
        case 'completed':
          if (result.session.status === VerificationStatus.Approved) {
            // Optimistic UI; rely on the webhook delivered to your backend as the source of truth.
          }
          break;
        case 'cancelled':
          // User dismissed the flow
          break;
        case 'failed':
          // Show retry — result.error.type / result.error.message
          break;
      }
    } finally {
      setLoading(false);
    }
  }, [userId]);

  return (
    <View>
      <Button title={loading ? 'Starting...' : 'Verify identity'} onPress={onPress} disabled={loading} />
    </View>
  );
}
```### 3. 后端：通过 Webhook 接收最终决策```ts theme={null}
app.post("/api/webhooks/didit", express.raw({ type: "application/json" }), (req, res) => {
  // 1. Verify the X-Signature header (see Webhooks docs)
  // 2. Parse the body
  const event = JSON.parse(req.body.toString());
  if (event.webhook_type === "status.updated") {
    // event.session_id, event.status ("Approved" | "Declined" | "In Review" | ...)
    // Look up the user by session_id and update their verification state.
  }
  res.sendStatus(200);
});
```有关 HMAC 签名验证的详细信息，请参阅 [Webhooks 指南](https://docs.didit.me/zh/integration/webhooks.md)。***## 完整示例```tsx theme={null}
import { useState, useCallback } from 'react';
import {
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
  SafeAreaView,
} from 'react-native';
import {
  startVerification,
  VerificationStatus,
  type VerificationResult,
} from '@didit-protocol/sdk-react-native';

export default function App() {
  const [token, setToken] = useState('');
  const [loading, setLoading] = useState(false);

  const handleVerify = useCallback(async () => {
    if (!token.trim()) {
      Alert.alert('Error', 'Please enter a session token.');
      return;
    }

    setLoading(true);
    try {
      const result = await startVerification(token.trim(), {
        loggingEnabled: true,
      });

      switch (result.type) {
        case 'completed':
          Alert.alert(
            'Verification Complete',
            `Status: ${result.session.status}\nSession: ${result.session.sessionId}`
          );
          break;
        case 'cancelled':
          Alert.alert('Cancelled', 'The user cancelled the verification.');
          break;
        case 'failed':
          Alert.alert('Failed', `${result.error.type}: ${result.error.message}`);
          break;
      }
    } catch (error) {
      Alert.alert('Error', `Unexpected error: ${error}`);
    } finally {
      setLoading(false);
    }
  }, [token]);

  return (
    <SafeAreaView style={{ flex: 1, padding: 24, justifyContent: 'center' }}>
      <TextInput
        placeholder="Enter session token..."
        value={token}
        onChangeText={setToken}
        autoCapitalize="none"
        style={{
          borderWidth: 1,
          borderColor: '#ccc',
          borderRadius: 8,
          padding: 12,
          marginBottom: 16,
        }}
      />
      <TouchableOpacity
        onPress={handleVerify}
        disabled={loading}
        style={{
          backgroundColor: '#1a1a1a',
          borderRadius: 8,
          padding: 16,
          alignItems: 'center',
          opacity: loading ? 0.6 : 1,
        }}
      >
        {loading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <Text style={{ color: '#fff', fontWeight: '600' }}>
            Start Verification
          </Text>
        )}
      </TouchableOpacity>
    </SafeAreaView>
  );
}
```***


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