@didit-protocol/sdk-react-native

中文文档
4.14.7发布于 2026/11/11MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 7.8万

React Native wrapper for Didit Identity Verification SDK

原始使用文档
文档目录43 节
  1. Requirements
  2. Platform Requirements
  3. Permissions
  4. iOS
  5. Android
  6. Bank and Location verification steps
  7. Bank
  8. Location on iOS
  9. Location on Android
  10. Native SDK Variants
  11. Installation
  12. Expo
  13. React Native CLI
  14. Quick Start
  15. Option A: Start verification with a session token
  16. Option B: Start verification with a workflow ID
  17. Configuration
  18. Configuration Options
  19. languageCode
  20. showLanguageSelector
  21. fontFamily
  22. loggingEnabled
  23. Camera Settings
  24. Language Settings
  25. Advanced Session Parameters
  26. Full Workflow Example
  27. Verification Results
  28. Result Types
  29. SessionData
  30. VerificationError
  31. Error Types
  32. Handling Results
  33. Complete Example
  34. API Reference
  35. startVerification(token, config?)
  36. startVerificationWithWorkflow(workflowId, options?)
  37. submitTransaction(transactionToken, transaction, options?)
  38. getTransaction(transactionToken, transactionId, options?)
  39. Exported Types
  40. Running the Example App
  41. iOS
  42. Android
  43. License

DiditSDK for React Native

A React Native wrapper for the Didit Identity Verification SDK. Supports both iOS and Android with a unified TypeScript API built on React Native's New Architecture (TurboModules).

Authentication is being prepared as the separate @didit-protocol/auth-react-native package. It is private and unavailable until the native DiditAuth integration is ready.

Requirements

  • React Native 0.76+ (New Architecture / TurboModules)
  • Node.js 20+
  • TypeScript 5+

Platform Requirements

PlatformMinimum VersionNotes
iOS13.0+NFC passport reading requires iOS 15.0+
AndroidAPI 24+ (7.0)Kotlin 2.1.10+, Android Gradle Plugin 8.6.0+, Gradle 8.7+, JDK 17

Permissions

The SDK uses the camera, optionally NFC, and location only for the Location verification step (see Bank and Location verification steps). Native permissions are declared by the underlying native SDKs and merged automatically where the platform supports it.

iOS

Add the following keys to your app's Info.plist:

<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>

Missing required iOS privacy keys will cause iOS to terminate the app as soon as the SDK accesses that protected resource.

NFC Configuration (for passport/ID chip reading)

  1. Add NFC Capability in Xcode:

    • Select your target > Signing & Capabilities > + Capability > Near Field Communication Tag Reading
  2. Add ISO7816 Identifiers to Info.plist:

    <key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
    <array>
        <string>D23300000045737445494420763335</string>
        <string>A0000002471001</string>
        <string>A0000002472001</string>
        <string>00000000000000</string>
    </array>
    
  3. Add an entitlements file with NFC tag reading enabled:

    <key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        <string>TAG</string>
    </array>
    

Make sure the app's provisioning profile includes the NFC Tag Reading capability. This NFC configuration is not needed when NFC is disabled.

Android

The following permissions are declared in the native SDK's AndroidManifest.xml and merged automatically:

PermissionDescription
INTERNETNetwork access for API communication
ACCESS_NETWORK_STATEDetect network availability
CAMERADocument scanning and face verification
NFCRead NFC chips in passports/ID cards

Camera and NFC hardware features are declared as optional (android:required="false"), so your app can be installed on devices without these features.

Runtime Permissions

The SDK handles Android runtime permission requests automatically. When the user reaches a step that requires camera access:

  1. The SDK prompts for camera permission if not already granted
  2. If the user denies the permission, an error message is displayed with a "Try Again" button
  3. If the user grants the permission, the verification flow continues

You do not need to request camera permission in your app code before calling startVerification() — the SDK manages this internally.

Bank and Location verification steps

Workflows can include a Bank step (the person links a bank account) and a Location step (the device position is read once, with the person's consent). Both screens are drawn by the native SDKs, so this package needs no new API: they run inside startVerification() / startVerificationWithWorkflow(), and the outcome comes back as the same VerificationResult.

Bank

No setup. The native SDKs open the bank's page (or a page Didit hosts) in the system browser, so there is no permission, URL scheme or deep link to register.

Location on iOS

Location ships in the native SDK as complete Location variants, not as an add-on: Core-Location, NFC-Location and All-Location for CocoaPods, DiditSDKCoreLocation, DiditSDKNFCLocation and DiditSDKLocation (all with Location) for SwiftPM. Exactly one DiditSDK variant may be declared, so this package picks it for you from your variant: all maps to All-Location, core and autodetection map to Core-Location, nfc maps to NFC-Location.

Set $DiditSdkIosLocationEnabled = true before use_native_modules! (or DIDIT_SDK_IOS_LOCATION_ENABLED=true) and keep a single pod didit_sdk_subspec line as shown in React Native CLI, with the Location mapping. With SwiftPM linkage the same flag selects the Location product and needs no pod line. Expo users set iosLocationEnabled: true in this package's plugin options and run prebuild. Without Location enabled, or without NSLocationWhenInUseUsageDescription, the step shows no prompt, reports that the device cannot place the person, and the workflow's own rules decide.

Add the purpose strings to Info.plist. NSLocationTemporaryUsageDescriptionDictionary is optional: it lets the step ask once for precise location when the person granted only an approximate one (iOS 14+), and its key must be exactly DiditLocationVerification.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Your location is used to confirm where you are for this verification.</string>
<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
    <key>DiditLocationVerification</key>
    <string>This verification needs your precise location once.</string>
</dict>

iOS picks these strings by the device language, not by the SDK's languageCode, so translate them in each <lang>.lproj/InfoPlist.strings. The precise-location string is translated under its purpose key. For example es.lproj/InfoPlist.strings:

"NSLocationWhenInUseUsageDescription" = "Tu ubicación se usa para confirmar dónde estás en esta verificación.";
"DiditLocationVerification" = "Esta verificación necesita tu ubicación precisa una vez.";

With Expo, set the same keys in app.json and translate them with locales:

{
  "expo": {
    "plugins": [
      ["@didit-protocol/sdk-react-native", { "iosLocationEnabled": true }]
    ],
    "ios": {
      "infoPlist": {
        "NSLocationWhenInUseUsageDescription": "Your location is used to confirm where you are for this verification.",
        "NSLocationTemporaryUsageDescriptionDictionary": {
          "DiditLocationVerification": "This verification needs your precise location once."
        }
      }
    },
    "locales": {
      "es": "./locales/es.json"
    }
  }
}

where locales/es.json is:

{
  "ios": {
    "NSLocationWhenInUseUsageDescription": "Tu ubicación se usa para confirmar dónde estás en esta verificación.",
    "DiditLocationVerification": "Esta verificación necesita tu ubicación precisa una vez."
  }
}

Both example apps in this repository declare these strings in English and Spanish.

Once your app links the module, declare Precise Location and Coarse Location in App Store Connect under App Functionality, linked to the user and not used for tracking. The SDK reads one position per attempt, only while the step is on screen, and never in the background.

Location on Android

The native SDK declares ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION, plus the location hardware features as optional (android:required="false"), and they merge into your app automatically. It asks for them at runtime only when a workflow reaches the step, after a screen that explains why, and the person can grant precise or approximate location. If your app never runs the step, you can remove them from the merged manifest (the <manifest> element needs xmlns:tools="http://schemas.android.com/tools"):

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove" />

A session that still reaches the step then reports the location as unavailable, without a prompt. If you keep them, declare Approximate location and Precise location as collected data in your Google Play Data safety form.

Native SDK Variants

NFC is enabled by default on both platforms. Automatic capture is available in every variant.

The React Native plugin can install the same native SDK variants exposed by the iOS and Android SDKs:

VariantNFC passport readingUse when
allYesYou want the complete SDK (default)
coreNoYou do not need NFC passport reading
nfcYesYou want the NFC variant
autodetectionNoDeprecated: identical to core

When NFC is disabled, you do not need iOS NFC capabilities, NFC entitlements, Android NFC packaging rules, or NFC-related provisioning setup.

Installation

Expo

npx expo install @didit-protocol/sdk-react-native

Then add the config plugin to your app.json (or app.config.js). The default native variant is all:

{
  "expo": {
    "plugins": ["@didit-protocol/sdk-react-native"]
  }
}

To choose a smaller native variant:

{
  "expo": {
    "plugins": [
      [
        "@didit-protocol/sdk-react-native",
        {
          "iosVariant": "core",
          "androidVariant": "core"
        }
      ]
    ]
  }
}

That's it. The plugin automatically configures both platforms:

  • Android: Adds the Didit Maven repository to Gradle and writes diditSdkAndroidVariant
  • iOS: Adds the DiditSDK podspec to the Podfile and sets $DiditSdkIosVariant

Supported iosVariant / androidVariant values are all, core, autodetection, and nfc. The legacy booleans (iosNfcEnabled, iosAutoDetectionEnabled, androidNfcEnabled) still work, but iosVariant / androidVariant are preferred for new integrations.

Pass "iosLinkage": "spm" to resolve the native iOS SDK through Swift Package Manager instead of CocoaPods - the plugin then writes no pod 'DiditSDK' line at all. See Swift Package Manager for the caveats. The default is cocoapods.

The iOS podspec URL is derived from the native SDK version this package pins (diditNativeSdkVersions.ios in its package.json), so it always matches the DiditSDK version the podspec depends on. To point CocoaPods at a fork, mirror, or prerelease tag instead, pass iosPodspecUrl:

[
  "@didit-protocol/sdk-react-native",
  {
    "iosPodspecUrl": "https://raw.githubusercontent.com/didit-protocol/sdk-ios/4.14.7/DiditSDK.podspec"
  }
]

Note: This SDK uses native modules (camera, NFC) that are not available in Expo Go. You must use a development build or run npx expo prebuild to generate the native projects.

React Native CLI

npm install @didit-protocol/sdk-react-native
# or
yarn add @didit-protocol/sdk-react-native

iOS

Add the DiditSDK pod to your Podfile (it's not on CocoaPods trunk). The default native variant is all:

# Pick one: 'all', 'core', 'nfc' ('autodetection' is deprecated and identical to 'core')
$DiditSdkIosVariant = 'all'

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

didit_sdk_ios_deployment_target = ['all', 'nfc'].include?($DiditSdkIosVariant) ? max_ios_version(min_ios_version_supported, '15.0') : min_ios_version_supported
platform :ios, didit_sdk_ios_deployment_target

# Inside your app target:
# Location ships as complete variants (All-Location, Core-Location, NFC-Location)
$DiditSdkIosLocationEnabled = false # true to enable the Location step
didit_sdk_location_suffix = $DiditSdkIosLocationEnabled ? '-Location' : ''
didit_sdk_subspec = case $DiditSdkIosVariant
                    when 'all'           then "DiditSDK/All#{didit_sdk_location_suffix}"
                    when 'core', 'autodetection' then "DiditSDK/Core#{didit_sdk_location_suffix}"
                    when 'nfc'           then "DiditSDK/NFC#{didit_sdk_location_suffix}"
                    else
                      raise "Invalid $DiditSdkIosVariant '#{$DiditSdkIosVariant}'. Supported values: all, core, autodetection, nfc."
                    end
pod didit_sdk_subspec, :podspec => 'https://raw.githubusercontent.com/didit-protocol/sdk-ios/4.14.7/DiditSDK.podspec'
Swift Package Manager (optional)

On React Native 0.75+ you can skip the pod declaration entirely and let SwiftPM resolve the native SDK straight from the sdk-ios repo. Set the linkage instead of declaring the pod:

# Pick one: 'all', 'core', 'autodetection', 'nfc'
$DiditSdkIosVariant = 'all'
$DiditSdkIosLinkage = 'spm'

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

didit_sdk_ios_deployment_target = ['all', 'nfc'].include?($DiditSdkIosVariant) ? max_ios_version(min_ios_version_supported, '15.0') : min_ios_version_supported
platform :ios, didit_sdk_ios_deployment_target

# No `pod 'DiditSDK'` line needed - SdkReactNative.podspec declares it as a
# SwiftPM dependency on the matching sdk-ios tag.

DIDIT_SDK_IOS_LINKAGE=spm works too, and Expo users can pass "iosLinkage": "spm" to the config plugin. cocoapods remains the default.

If you switch an existing project to spm, remove the pod didit_sdk_subspec, :podspec => ... line - leaving both in place links the same framework twice. React Native warns that SwiftPM packages combined with statically linked pods can produce linker errors; if you hit those, build with USE_FRAMEWORKS=dynamic (details).

Then install dependencies:

cd ios
bundle exec pod install

To switch variants, clean CocoaPods first so the previous variant is not reused:

cd ios
rm -rf Pods Podfile.lock

# Edit $DiditSdkIosVariant in your Podfile, then:
bundle exec pod install

Android

Add the Didit Maven repository to your project-level settings.gradle:

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven {
            url "https://raw.githubusercontent.com/didit-protocol/sdk-android/main/repository"
            // Scope to Didit's group: unfiltered, Gradle probes this host for
            // every dependency and a 429 disables the repo mid-build (issue #40).
            content { includeGroup "me.didit" }
        }
        maven { url "https://jitpack.io" }
    }
}

By default, the React Native plugin depends on the full Android SDK (all). To choose another variant, add this to android/gradle.properties:

diditSdkAndroidVariant=core

Supported values are all, core, autodetection, and nfc. The legacy diditSdkAndroidNfcEnabled=false property still maps to core for backwards compatibility, but diditSdkAndroidVariant is preferred for new integrations.

The native SDK dependencies for both platforms are declared in the library and resolved automatically.

Quick Start

Option A: Start verification with a session token

If your backend creates the verification session and returns a token:

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

const result = await startVerification('your-session-token');

switch (result.type) {
  case 'completed':
    console.log('Status:', result.session.status);
    console.log('Session ID:', result.session.sessionId);
    break;
  case 'cancelled':
    console.log('User cancelled');
    break;
  case 'failed':
    console.log('Error:', result.error.type, result.error.message);
    break;
}

Option B: Start verification with a workflow ID

If you want the SDK to create the session using a workflow ID:

import { startVerificationWithWorkflow } from '@didit-protocol/sdk-react-native';

const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  config: { loggingEnabled: true },
});

Configuration

Both startVerification and startVerificationWithWorkflow accept a DiditConfig object to customize the SDK behavior. For startVerification, pass it as the second argument. For startVerificationWithWorkflow, pass it inside the options.config field.

import { startVerification } from '@didit-protocol/sdk-react-native';

// With startVerification — config is the second argument
const result = await startVerification('your-session-token', {
  languageCode: 'es',
  showLanguageSelector: true,
  fontFamily: 'Avenir',
  loggingEnabled: true,
  showCloseButton: true,
  showExitConfirmation: true,
  closeOnComplete: false,
});

// With startVerificationWithWorkflow — config is inside options
const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  config: {
    languageCode: 'es',
    showLanguageSelector: true,
    loggingEnabled: true,
    showCloseButton: true,
    showExitConfirmation: true,
  },
});

Configuration Options

OptionTypeDefaultDescription
languageCodestringDevice localeISO 639-1 language code (e.g. "en", "fr", "ar")
showLanguageSelectorbooleanfalseShow the web-style language selector on the welcome screen
fontFamilystringSystem fontCustom font family name
loggingEnabledbooleanfalseEnable SDK debug logging
showCloseButtonbooleantrueShow close (X) button on verification step screens
showExitConfirmationbooleantrueShow confirmation dialog when user attempts to exit
closeOnCompletebooleanfalseAutomatically dismiss verification UI when complete
defaultDocumentCameraCameraLensNative default (back)Lens used when first entering the document capture screen
defaultLivenessCameraCameraLensNative default (front)Lens used when first entering the liveness (passive face) capture screen
showDocumentCameraSwitchButtonbooleantrueShow the in-capture camera switcher on the document screen
showLivenessCameraSwitchButtonbooleantrueShow the in-capture camera switcher on the liveness screen

All fields are optional. If no config is provided, the SDK uses sensible defaults.

languageCode

Sets the language for the entire verification UI. Pass an ISO 639-1 code (e.g. "en", "fr", "es", "ar"). If not set, the SDK automatically detects the device locale and falls back to English.

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

// Use device locale (default — no config needed)
await startVerification(token);

showLanguageSelector

Set this to true to let users change the verification language from the welcome screen. The selector is hidden by default.

await startVerification(token, { showLanguageSelector: true });

fontFamily

Overrides the font used throughout the SDK UI. The font must be registered in your app's native configuration:

  • iOS: Add the font file to your Xcode project and list it in Info.plist under UIAppFonts.
  • Android: Place the font file in android/app/src/main/res/font/.
await startVerification(token, { fontFamily: 'Avenir' });

If not set, the SDK uses the platform's default system font.

loggingEnabled

Enables verbose debug logging from the native SDK. Useful during development to inspect the SDK's internal state, API calls, and error details. Should be disabled in production.

// Enable logging for debugging
await startVerification(token, { loggingEnabled: true });

Camera Settings

Control which camera lens opens by default on the document and liveness capture screens, and whether the in-capture camera switcher is shown to the user.

import { CameraLens, startVerification } from '@didit-protocol/sdk-react-native';

await startVerification(token, {
  defaultDocumentCamera: CameraLens.Back, // back is the native default
  defaultLivenessCamera: CameraLens.Front, // front is the native default
  showDocumentCameraSwitchButton: true, // false to lock to the chosen lens
  showLivenessCameraSwitchButton: true,
});

If the requested lens is not present on the device, the native SDK falls back to the first available camera so capture still works. The switcher is also automatically hidden on single-camera devices regardless of the show…SwitchButton flag.

Language Settings

The SDK supports 54 languages. If no language is specified, the SDK uses the device locale with English as fallback.

// Use device locale (default)
await startVerification(token);

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

Supported Languages

LanguageCodeLanguageCode
AlbaniansqKazakhkk
ArabicarKoreanko
ArmenianhyKyrgyzky
BengalibnLatvianlv
BosnianbsLithuanianlt
BulgarianbgMacedonianmk
CatalancaMalayms
ChinesezhMontenegrincnr
Chinese (Simplified)zh-CNNorwegianno
Chinese (Traditional)zh-TWPersianfa
CroatianhrPolishpl
CzechcsPortuguesept
DanishdaPortuguese (Brazil)pt-BR
DutchnlRomanianro
EnglishenRussianru
EstonianetSerbiansr
FinnishfiSlovaksk
FrenchfrSloveniansl
GeorgiankaSomaliso
GermandeSpanishes
GreekelSwedishsv
HebrewheThaith
HindihiTurkishtr
HungarianhuUkrainianuk
IndonesianidUzbekuz
ItalianitVietnamesevi
JapanesejaMongolianmn

Advanced Session Parameters

For advanced session parameters such as contact_details, expected_details, metadata, and callback, use the Backend Session method. Your backend calls POST /v3/session/ with full parameters, then passes the session_token to the SDK:

// Your backend creates the session with advanced parameters:
// POST /v3/session/ with contact_details, expected_details, metadata, etc.
// Then passes the session_token to the SDK:
const result = await startVerification(sessionTokenFromBackend);

Note: The startVerificationWithWorkflow method only supports vendorData. For any other session parameters, use the Backend Session method.

Full Workflow Example

const result = await startVerificationWithWorkflow('your-workflow-id', {
  vendorData: 'user-123',
  config: {
    languageCode: 'en',
    loggingEnabled: true,
    showCloseButton: true,
    showExitConfirmation: true,
  },
});

Verification Results

Both startVerification and startVerificationWithWorkflow return a Promise<VerificationResult>. The result is a discriminated union — use the type field to determine the outcome.

Result Types

TypeDescriptionFields
completedVerification flow completedsession (always present)
cancelledUser cancelled the flowsession (optional)
failedAn error occurrederror (always present), session (optional)

SessionData

PropertyTypeDescription
sessionIdstringThe unique session identifier
statusVerificationStatusApproved, Pending, or Declined

VerificationError

PropertyTypeDescription
typeVerificationErrorTypeError category (see table below)
messagestringHuman-readable error description

Error Types

Error TypeDescription
sessionExpiredThe session has expired
networkErrorNetwork connectivity issue
cameraAccessDeniedCamera permission not granted
notInitializedSDK not initialized (Android only)
apiErrorAPI request failed
retryBlockedA previous verification was not approved and the maximum number of retries was reached
unknownOther error with message

Handling Results

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('Identity verified!');
          break;
        case VerificationStatus.Pending:
          console.log('Verification under review.');
          break;
        case VerificationStatus.Declined:
          console.log('Verification declined.');
          break;
      }
      console.log('Session ID:', result.session.sessionId);
      break;

    case 'cancelled':
      console.log('User cancelled the verification.');
      if (result.session) {
        console.log('Session ID:', result.session.sessionId);
      }
      break;

    case 'failed':
      console.log(`Error [${result.error.type}]: ${result.error.message}`);
      break;
  }
}

Complete Example

import { useState, useCallback } from 'react';
import {
  Text,
  View,
  TextInput,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
  SafeAreaView,
} from 'react-native';
import {
  startVerification,
  startVerificationWithWorkflow,
  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,
      });
      showResult(result);
    } catch (error) {
      Alert.alert('Error', `Unexpected error: ${error}`);
    } finally {
      setLoading(false);
    }
  }, [token]);

  const showResult = (result: VerificationResult) => {
    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;
    }
  };

  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',
        }}
      >
        {loading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <Text style={{ color: '#fff', fontWeight: '600' }}>
            Start Verification
          </Text>
        )}
      </TouchableOpacity>
    </SafeAreaView>
  );
}

API Reference

startVerification(token, config?)

Start verification with an existing session token.

ParameterTypeRequiredDescription
tokenstringYesSession token from the Didit API
configDiditConfigNoSDK configuration options

Returns: Promise<VerificationResult>

startVerificationWithWorkflow(workflowId, options?)

Start verification by creating a new session with a workflow ID.

ParameterTypeRequiredDescription
workflowIdstringYesWorkflow ID that defines verification steps
optionsWorkflowOptionsNoWorkflow options (see below)

Returns: Promise<VerificationResult>

WorkflowOptions

FieldTypeDescription
vendorDatastringYour user identifier or reference
configDiditConfigSDK configuration options

Note: For advanced session parameters (contactDetails, expectedDetails, metadata), use the Backend Session method (startVerification with a token created via POST /v3/session/).

submitTransaction(transactionToken, transaction, options?)

Submit a transaction directly from the device. Requires a transaction SDK token minted by your backend via POST /v3/transactions/sdk-token/. Device intelligence is attached automatically. autoLaunchAction (default true) auto-launches only a wallet_ownership action natively, invoking options.onTransactionUpdated once it completes; a verification_session action is never auto-launched and is always returned on result.actionRequired for your app to launch with its own Didit verification integration. Full guide: SDK Transaction Submission.

ParameterTypeRequiredDescription
transactionTokenstringYesTransaction SDK token (sent as X-Transaction-Token)
transactionDiditTransactionYesTransaction payload (txnId required; info, subject, counterparty, travelRule, ...)
optionsDiditTransactionOptionsNobaseUrl, autoLaunchAction (default true), onTransactionUpdated callback

Returns: Promise<DiditTransactionResult> with transactionId, status, travelRuleStatus?, and actionRequired?.

Throws: DiditTransactionError with code set to invalid_token, expired_token, validation (see fieldErrors), or network.

import { submitTransaction, DiditTransactionError } from '@didit-protocol/sdk-react-native';

try {
  const result = await submitTransaction(sdkToken, {
    txnId: 'order-123',
    type: 'crypto',
    info: { direction: 'outbound', amount: 0.25, currency: 'ETH' },
    travelRule: { required: true },
  }, {
    onTransactionUpdated: (updated) => console.log('Refreshed:', updated.status),
  });
  console.log(result.transactionId, result.actionRequired?.type);
} catch (error) {
  if (error instanceof DiditTransactionError) {
    console.log(error.code, error.fieldErrors);
  }
}

A verification_session action is returned, not auto-launched - launch it yourself with startVerification:

import { submitTransaction, startVerification } from '@didit-protocol/sdk-react-native';

const result = await submitTransaction(sdkToken, transaction);

if (result.actionRequired?.type === 'verification_session') {
  const { sessionToken } = result.actionRequired;
  const verification = await startVerification(sessionToken!);
  console.log('Verification result:', verification.type);
}

getTransaction(transactionToken, transactionId, options?)

Fetch the current state of a transaction previously submitted with the same token.

ParameterTypeRequiredDescription
transactionTokenstringYesTransaction SDK token
transactionIdstringYestransactionId returned by submitTransaction
optionsDiditTransactionOptionsNobaseUrl override

Returns: Promise<DiditTransactionResult>

Exported Types

import {
  // Functions
  startVerification,
  startVerificationWithWorkflow,
  submitTransaction,
  getTransaction,

  // Enum
  VerificationStatus,

  // Classes
  DiditTransactionError,

  // Types
  type VerificationResult,
  type VerificationCompleted,
  type VerificationCancelled,
  type VerificationFailed,
  type VerificationError,
  type VerificationErrorType,
  type SessionData,
  type DiditConfig,
  type ContactDetails,
  type ExpectedDetails,
  type WorkflowOptions,
  type DiditTransaction,
  type DiditTransactionInfo,
  type DiditTransactionParticipant,
  type DiditTransactionPaymentMethod,
  type DiditTravelRule,
  type DiditTransactionActionRequired,
  type DiditTransactionResult,
  type DiditTransactionOptions,
  type DiditTransactionErrorCode,
} from '@didit-protocol/sdk-react-native';

Running the Example App

The repository includes a fully functional example app.

iOS

yarn install
cd example/ios && bundle exec pod install && cd ../..
yarn run:ios

To run on a real device, open example/ios/SdkReactNativeExample.xcworkspace in Xcode, configure your signing team, and select your device.

Android

yarn install
yarn run:android

License

Copyright (c) 2026 Didit. All rights reserved.

版本与发布记录

@didit-protocol/sdk-react-native 共发布 66 个版本,首次发布于 2026/02/17;过去 12 个月发布了 66 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.14.7latest2026/11/11今天
4.14.62026/11/11今天
4.14.52026/11/111 天前
4.14.42026/11/111 天前
4.14.32026/11/101 天前
4.14.22026/11/101 天前

关于 @didit-protocol/sdk-react-native 的常见问题

@didit-protocol/sdk-react-native 是什么?

React Native wrapper for Didit Identity Verification SDK

如何安装 @didit-protocol/sdk-react-native?

在项目目录运行 npm install @didit-protocol/sdk-react-native,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(*)、react-native(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@didit-protocol/sdk-react-native 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@didit-protocol/sdk-react-native 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@didit-protocol/sdk-react-native 可以商用吗?

@didit-protocol/sdk-react-native 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@didit-protocol/sdk-react-native 的下载量有多少?

根据 npm 官方下载统计,@didit-protocol/sdk-react-native 在 2026/10/12 – 2026/11/10 这 30 天内被下载 77,890 次,日均约 2,596 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@didit-protocol/sdk-react-native 还在维护吗?

最新版本 4.14.7 发布于 2026/11/11(今天);至今共发布 66 个版本,其中过去 12 个月发布了 66 个;首次发布于 2026/02/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。