@basis-theory/react-agentic

中文文档
2.1.0发布于 2026/09/12MITTypeScriptESM + CJS零依赖近 30 天下载 10.6万

Basis Theory AI React Library

原始使用文档
文档目录13 节
  1. Installation
  2. Setup
  3. BtAiProvider Props
  4. SDK Ready State
  5. Hooks
  6. useAgentic() / useBtAi()
  7. useEnrollmentVerification()
  8. useInstructionVerification()
  9. Enrollment Verification
  10. Instruction Verification
  11. Utilities
  12. collectDeviceContext()
  13. License

@basis-theory/react-agentic

[!IMPORTANT] HTTPS is required. The card network SDKs used for verification (Visa and Mastercard) require your application to be served over HTTPS, even in development. Verification will fail on plain HTTP.

For local development, we recommend Cloudflare Quick Tunnels to expose your local server over HTTPS with zero configuration:

# Install cloudflared
brew install cloudflared

# Start a quick tunnel pointing to your local dev server
cloudflared tunnel --url http://localhost:3000

This gives you a temporary https://*.trycloudflare.com URL you can use for testing.

Installation

npm install @basis-theory/react-agentic

Setup

Wrap your app with BtAiProvider:

import { BtAiProvider } from '@basis-theory/react-agentic';

function App() {
  return (
    <BtAiProvider
      apiKey="your-public-api-key"
      environment="production"
      passkeyTimeoutMs={120000}        // optional: 2 min passkey timeout
      sessionReadyTimeoutMs={15000}    // optional: 15s session ready timeout
    >
      <YourComponent />
    </BtAiProvider>
  );
}

BtAiProvider Props

PropTypeRequiredDescription
apiKeystringYesA Basis Theory AI public API key
environment'production' | 'test'NoEnvironment to use (default: production)
agenticApiUrlstringNoOverride the agentic commerce API base URL
passkeyTimeoutMsnumberNoTimeout in ms for Visa passkey authentication (default: 60000)
sessionReadyTimeoutMsnumberNoTimeout in ms for Visa session readiness after refresh (default: 10000)
onNewDevice'decline' | 'reenroll'NoBehavior when instruction verification detects a different device (default: reenroll)

SDK Ready State

The useAgentic hook exposes a ready boolean that indicates when the underlying card network SDKs (Visa and Mastercard) have finished initializing. Use this to prevent calling verification methods before the SDK is ready.

import { useAgentic } from '@basis-theory/react-agentic';

function VerifyButton() {
  const { ready, verifyEnrollment } = useAgentic();

  return (
    <button onClick={() => verifyEnrollment('enrollment-id')} disabled={!ready}>
      {ready ? 'Verify' : 'Initializing...'}
    </button>
  );
}
  • false initially and during SDK initialization
  • true once at least one card network SDK (Visa or Mastercard) is ready
  • Resets to false if the provider unmounts or the environment changes

All verify methods (verifyEnrollment, verifyInstruction) automatically wait for ready before executing, so it is safe to call them before initialization completes — they will queue until the SDK is ready.

For granular per-network status, use getStatus() which returns { visa: boolean, mastercard: boolean }.

Hooks

useAgentic() / useBtAi()

The primary hook for interacting with the SDK. Returns verification methods and SDK state.

import { useAgentic } from '@basis-theory/react-agentic';

function MyComponent() {
  const {
    ready,              // boolean - whether the SDK is ready
    apiKey,             // string - current API key
    environment,        // string - current environment
    updateApiKey,       // (newKey: string) => void
    getStatus,          // () => { visa: boolean, mastercard: boolean }
    verifyEnrollment,   // (enrollmentId: string) => Promise
    verifyInstruction,  // (agentId: string, instructionId: string) => Promise
  } = useAgentic();
}

Both useAgentic() and useBtAi() return the same interface — use whichever you prefer.

useEnrollmentVerification()

Action-based hook for building a custom enrollment verification UI. Render your UI based on status and call the corresponding action to advance the flow.

This hook handles the complete orchestration for both card networks:

  • Visa: OTP method selection → OTP input → passkey creation → completion
  • Mastercard: popup-based authentication → completion

Statuses

StatusDescriptionAvailable Actions
idleNot startedstart()
loadingAsync operation in progress—
otp_requiredShow OTP method picker (otpMethods available)selectOtpMethod(methodId)
otp_sentShow OTP code inputsubmitOtp(code)
passkey_requiredVisa passkey creation neededconfirmPasskey()
popup_requiredMastercard popup neededconfirmPasskey(), retry()
verifiedVerification complete—
errorSomething went wrong (error has message)retry(), start()

Example

import { useEnrollmentVerification } from '@basis-theory/react-agentic';

function CustomEnrollmentUI({ enrollmentId }) {
  const {
    status,           // current status (see table above)
    error,            // string | null — error message when status is 'error'
    otpMethods,       // available OTP methods when status is 'otp_required'
    start,            // () => Promise — begin or restart verification
    selectOtpMethod,  // (methodId: string) => Promise — select an OTP delivery method
    submitOtp,        // (code: string) => Promise — submit the OTP code
    confirmPasskey,   // () => Promise — trigger passkey creation (Visa) or popup (Mastercard)
    retry,            // () => Promise — retry the current step (or restart if needed)
    cancel,           // () => void — cancel and reset to idle
  } = useEnrollmentVerification({ enrollmentId });

  // Render your own UI based on status
}

How to Build Your Own UI

  • Call start() to kick off the enrollment verification flow
  • Switch on status to render the appropriate UI for each step:
    • loading — show a spinner or loading indicator
    • otp_required — render a list/buttons from otpMethods and call selectOtpMethod(methodId) on selection
    • otp_sent — render a code input field and call submitOtp(code) on submit
    • passkey_required — show a prompt/button explaining passkey creation and call confirmPasskey()
    • popup_required — show a prompt/button explaining Mastercard popup auth and call confirmPasskey()
    • verified — show a success message and proceed with your app flow
    • error — display error message with a button to retry() or start() again
  • Use cancel() to let the user abort and reset to idle at any point
  • The hook manages all card-network orchestration internally — you only need to render UI and call actions

useInstructionVerification()

Action-based hook for building a custom instruction verification UI. Handles passkey authentication for both card networks:

  • Visa: passkey authentication → completion
  • Mastercard: popup-based authentication → completion

Statuses

StatusDescriptionAvailable Actions
idleNot startedstart()
loadingAsync operation in progress—
passkey_requiredVisa passkey auth neededconfirmPasskey()
popup_requiredMastercard popup neededconfirmPasskey(), retry()
verifiedVerification complete—
errorSomething went wrong (error has message)retry(), start()

Example

import { useInstructionVerification } from '@basis-theory/react-agentic';

function CustomInstructionUI({ agentId, instructionId }) {
  const {
    status,           // current status (see table above)
    error,            // string | null — error message when status is 'error'
    start,            // () => Promise — begin or restart verification
    confirmPasskey,   // () => Promise — trigger passkey auth (Visa) or popup (Mastercard)
    retry,            // () => Promise — retry the current step (or restart if needed)
    cancel,           // () => void — cancel and reset to idle
  } = useInstructionVerification({ agentId, instructionId });

  // Render your own UI based on status
}

How to Build Your Own UI

  • Call start() to kick off the instruction verification flow
  • Switch on status to render the appropriate UI for each step:
    • loading — show a spinner or loading indicator
    • passkey_required — show a prompt/button explaining Visa passkey authentication and call confirmPasskey()
    • popup_required — show a prompt/button explaining Mastercard popup auth and call confirmPasskey()
    • verified — show a success message and proceed with your app flow
    • error — display error message with a button to retry() or start() again
  • Use cancel() to let the user abort and reset to idle at any point
  • The hook manages all card-network orchestration internally — you only need to render UI and call actions

Enrollment Verification

Opens a modal that guides the user through enrollment verification. Automatically handles both Visa (OTP + passkey creation) and Mastercard (popup authentication) flows.

import { useAgentic } from '@basis-theory/react-agentic';

function EnrollmentExample() {
  const { verifyEnrollment } = useAgentic();

  const handleVerify = async () => {
    try {
      const result = await verifyEnrollment('enrollment-id');
      console.log('Verified:', result);
    } catch (err) {
      console.error('Verification failed:', err.message);
    }
  };

  return <button onClick={handleVerify}>Verify Enrollment</button>;
}

Instruction Verification

Opens a modal that guides the user through instruction verification (passkey authentication). Supports both Visa and Mastercard cards.

import { useAgentic } from '@basis-theory/react-agentic';

function InstructionExample() {
  const { verifyInstruction } = useAgentic();

  const handleVerify = async () => {
    try {
      const result = await verifyInstruction('agent-id', 'instruction-id');
      console.log('Verified:', result);
    } catch (err) {
      console.error('Verification failed:', err.message);
    }
  };

  return <button onClick={handleVerify}>Verify Instruction</button>;
}

Utilities

collectDeviceContext()

Collects browser and device fingerprint data sent with verification requests. Useful if you're building a fully custom integration.

import { collectDeviceContext } from '@basis-theory/react-agentic';

const context = collectDeviceContext();
// { userAgent, language, platform, screenResolution, ... }

License

MIT

版本与发布记录

@basis-theory/react-agentic 共发布 18 个版本,首次发布于 2026/03/13;过去 12 个月发布了 18 个版本。

版本发布日期距今
2.1.0latest2026/09/121 个月前
2.0.12026/05/215 个月前
2.0.02026/05/096 个月前
1.8.1-beta.0beta2026/05/016 个月前
1.8.02026/04/037 个月前
1.7.02026/04/017 个月前

关于 @basis-theory/react-agentic 的常见问题

@basis-theory/react-agentic 是什么?

Basis Theory AI React Library

如何安装 @basis-theory/react-agentic?

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

@basis-theory/react-agentic 支持 TypeScript 吗?

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

@basis-theory/react-agentic 支持 ESM 还是 CommonJS?

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

@basis-theory/react-agentic 可以商用吗?

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

@basis-theory/react-agentic 的下载量有多少?

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

@basis-theory/react-agentic 还在维护吗?

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