# @basis-theory/web-threeds 中文文档

规范地址：https://npmcn.com/package/%40basis-theory/web-threeds/

版本：2\.2\.2
npm 元数据更新时间：2026-11-02T18:33:40.835Z
中文译文更新时间：2026-11-07T18:01:40.568Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40basis-theory/web-threeds
原文对照：https://npmcn.com/package/%40basis-theory/web-threeds/?lang=original
项目主页：https://github.com/Basis-Theory/web-threeds#readme
源码仓库：https://github.com/Basis-Theory/web-threeds

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：138 kB，25 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.x
- 运行依赖：0 个
- 首次发布：2025-02-03T16:28:35.966Z
- 最新版本发布：2026-09-14T16:06:57.318Z
- 近 30 天下载量：79791（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：19（近 12 个月 5 个）

## 中文简介

网络三德软件包是一个JavaScript/TypeScript库,旨在简化网络应用程序中3DS(3D Security)认证程序的实施. 它提供了一个精简的界面,既处理会话的创建,又处理挑战

## 安装

```sh
npm install @basis-theory/web-threeds
```

也可以使用：`pnpm add @basis-theory/web-threeds`、`yarn add @basis-theory/web-threeds`、`bun add @basis-theory/web-threeds`

## README

# `web-threeds`

## 概览

网络三德软件包是一个JavaScript/TypeScript库,旨在简化网络应用程序中3DS(3D Security)认证程序的实施. 它为处理3DS进程的会话创建和质疑步骤提供了简化的界面.

网络三德软件包揭露出两种主要方法: `createSession` 财务报告和审定财务报表 `startChallenge`这些方法有助于启动和处理3DS会议和挑战.

## 方法

### `createSession`

```typescript
createSession({ pan }: Create3dsSessionRequest): Promise<Create3dsSessionResponse>
```

这种方法启动一个3DS会话,用提供的 PAN(Prime Account Number)向服务器提出请求. 它返回一个解析 Creat3dsSessionResponse 对象的保证,其中包含会话细节 .

### `startChallenge`

```typescript
startChallenge(options: ThreeDSChallengeRequest): Promise<void>
```

这种方法通过向ACS(Access Control Server)提出附带必要参数的请求开始3DS挑战. 它处理挑战过程并回报一个承诺.

## 用法实例

### 创建 3DS 会话

```typescript
import { BasisTheory3ds } from '3ds-web';

const apiKey = 'your_api_key';
const { createSession } = BasisTheory3ds(apiKey);

const session = await createSession({
  pan: '<BASIS_THEORY_TOKEN_ID>',
});
```

### 开始挑战

```typescript
import { BasisTheory3ds } from '3ds-web';

const apiKey = 'your_api_key';
const { startChallenge } = BasisTheory3ds(apiKey);

await startChallenge({
  sessionId: 'session_id',
  acsTransactionId: 'acs_transaction_id',
  acsChallengeUrl: 'acs_challenge_url',
  threeDSVersion: '2.2.0',
  windowSize: '05', // Optional, defaults to 'THREE'
});
```

## 处理错误

两者 `createSession` 财务报告和审定财务报表 `startChallenge` 可能会出错,包括出错的细节.

-   **API 错误** (从) `createSession`)作为有包含3DS服务的全部错误细节的额外属性的出错对象返回
-   **挑战错误** (从) `startChallenge`)作为标准错误对象和描述性信件返回

### 错误结构

```typescript
try {
  const session = await createSession({ tokenId: 'token_id' });
} catch (error) {
  // Error object properties:
  console.log(error.message); // Human-readable error message
  console.log(error.title); // Error title (e.g., "3DS Service Error")
  console.log(error.status); // HTTP status code (e.g., 424)
  console.log(error.detail); // Detailed description

  // Nested error object with additional context (normalized to camelCase):
  if (error.error) {
    console.log(error.error.serviceStatus); // HTTP status from 3DS service (e.g., "403")
    console.log(error.error.sessionId); // Session ID for debugging
    console.log(error.error.errorSource); // Which service failed (e.g., "3DS Server", "ACS")
    console.log(error.error.message); // Detailed error message
    console.log(error.error.detail); // Additional error context
  }
}
```

### 常见错误设想

#### 1\. 3DS服务出错(现状424)

当3DS服务或发卡器返回出错时,这些出错发生:

```typescript
try {
  const session = await createSession({ tokenId: 'token_id' });
} catch (error) {
  if (error.status === 424) {
    // Handle 3DS service errors
    switch (error.error?.serviceStatus) {
      case '403':
        // Access denied by issuer
        console.log('Merchant configuration issue:', error.error.detail);
        break;
      case '401':
        // Authentication failed
        console.log('Authentication failed:', error.error.message);
        break;
      default:
        console.log('3DS service error:', error.message);
    }
  }
}
```

#### 2\. 验证错误(现状400)

这些错误发生在请求参数无效时 :

```typescript
try {
  const session = await createSession({ tokenId: 'invalid_token' });
} catch (error) {
  if (error.status === 400) {
    console.log('Validation error:', error.message);
  }
}
```

### 示例:综合错误处理

```typescript
import { BasisTheory3ds } from '@basis-theory/web-threeds';

const bt3ds = BasisTheory3ds('your_api_key');

try {
  const session = await bt3ds.createSession({ tokenId: 'token_id' });

  // Continue with challenge if needed
  try {
    await bt3ds.startChallenge({
      sessionId: session.id,
      acsTransactionId: 'acs_transaction_id',
      acsChallengeUrl: 'acs_challenge_url',
      threeDSVersion: '2.2.0',
    });
  } catch (challengeError) {
    // Handle challenge-specific errors
    console.error('Challenge error:', challengeError.message);
    if (challengeError.message.includes('Timed out')) {
      showErrorToUser('Challenge timed out. Please try again.');
    } else if (challengeError.message.includes('Invalid challenge request')) {
      showErrorToUser('Invalid challenge configuration.');
    } else {
      showErrorToUser('Challenge failed. Please try again.');
    }
    throw challengeError; // Re-throw to outer catch
  }
} catch (error) {
  // Log full error details for debugging
  console.error('3DS Error:', {
    message: error.message,
    title: error.title,
    status: error.status,
    detail: error.detail,
    error: error.error,
  });

  // Determine action based on error type
  if (error.status === 424 && error.error?.errorSource === '3DS Server') {
    // Merchant configuration issue - contact support
    showErrorToUser(
      'Payment authentication unavailable. Please try a different card.'
    );
  } else if (error.status === 424 && error.error?.errorSource === 'ACS') {
    // Issuer authentication issue
    showErrorToUser('Card authentication failed. Please contact your bank.');
  } else if (error.status === 400) {
    // Validation error
    showErrorToUser('Invalid card information. Please check and try again.');
  } else {
    // Generic error (could be challenge error or session error)
    showErrorToUser('An error occurred. Please try again later.');
  }
}
```

## 配置选项

### 挑战请求

`challengeContainerOptions` 允许您自定义 `id` 3DS 挑战容器的属性,这样您就可以使用 CSS 设定目标并应用样式。 它可以使3DS挑战界面在您的应用的布局中精确定位.

```typescript
const { startChallenge } = BasisTheory3ds(apiKey, {
  challengeConfigurationOptions: {
    id: 'customId',
  },
});
```

## 常见问题

### @basis-theory/web-threeds 是什么？

网络三德软件包是一个JavaScript/TypeScript库,旨在简化网络应用程序中3DS\(3D Security\)认证程序的实施\. 它提供了一个精简的界面,既处理会话的创建,又处理挑战

### 如何安装 @basis-theory/web-threeds？

在项目目录运行 npm install @basis-theory/web-threeds，或使用 pnpm add / yarn add / bun add。

### @basis-theory/web-threeds 支持 TypeScript 吗？

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

### @basis-theory/web-threeds 支持 ESM 还是 CommonJS？

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

### @basis-theory/web-threeds 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.x。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @basis-theory/web-threeds 可以商用吗？

@basis-theory/web-threeds 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @basis-theory/web-threeds 的下载量有多少？

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

### @basis-theory/web-threeds 还在维护吗？

最新版本 2\.2\.2 发布于 2026/09/15（1 个月前）；至今共发布 19 个版本，其中过去 12 个月发布了 5 个；首次发布于 2025/02/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

