@basis-theory/web-elements

中文文档
3.5.0发布于 2026/11/05Apache-2.0TypeScriptESM + CJS零依赖近 30 天下载 36.1万

Secure, PCI-compliant elements for creating payment input forms

原始使用文档
文档目录24 节
  1. Installation
  2. npm
  3. yarn
  4. CDN
  5. Quick Start
  6. CDN Usage
  7. Element Types
  8. Shared Options
  9. Text Element Options
  10. CVV Element Options
  11. Element Methods
  12. Events
  13. change Event Payload
  14. error Event Codes
  15. SDK Options
  16. Services
  17. tokens
  18. tokenize
  19. tokenIntents
  20. sessions
  21. Theming
  22. TypeScript
  23. Documentation
  24. License

@basis-theory/web-elements

Secure, PCI-compliant iframe elements for collecting sensitive data in web applications. Card data never touches your servers.

Installation

npm

npm install @basis-theory/web-elements@beta

yarn

yarn add @basis-theory/web-elements@beta

CDN

<script src="https://js.basistheory.com/3.0.0-beta.2/web-elements/basis-theory.js"></script>

Quick Start

import BasisTheory from '@basis-theory/web-elements';

// Initialize (synchronous -- returns immediately)
const bt = BasisTheory('pk_test_...');

// Create elements
const cardNumberEl = bt.createElement('cardNumber', {
  placeholder: '4242 4242 4242 4242',
});
const expiryEl = bt.createElement('expiry', {
  placeholder: 'MM/YY',
});
const cvvEl = bt.createElement('cvv', {
  placeholder: '123',
});

// Mount to DOM (async -- creates secure iframes)
await Promise.all([
  cardNumberEl.mount('#card-number'),
  expiryEl.mount('#expiry'),
  cvvEl.mount('#cvv'),
]);

// Listen for validation changes
cardNumberEl.on('change', (event) => {
  console.log('Valid:', event.detail.isValid);
  console.log('Brand:', event.detail.cardBrand);
});

// Tokenize on form submission
const token = await bt.tokens.create({
  type: 'card',
  data: {
    number: cardNumberEl,
    expiration_month: expiryEl,
    expiration_year: expiryEl,
    cvc: cvvEl,
  },
});

console.log('Token ID:', token.id);

CDN Usage

<script src="https://js.basistheory.com/3.0.0-beta.2/web-elements/basis-theory.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', async () => {
    const bt = BasisTheory('pk_test_...');

    const cardNumberEl = bt.createElement('cardNumber');
    const expiryEl = bt.createElement('expiry');
    const cvvEl = bt.createElement('cvv');

    await Promise.all([
      cardNumberEl.mount('#card-number'),
      expiryEl.mount('#expiry'),
      cvvEl.mount('#cvv'),
    ]);
  });
</script>

Element Types

TypecreateElement keyDescription
Card Number'cardNumber'PAN input with Luhn validation and brand detection
Expiry'expiry'MM/YY expiration date input
CVV'cvv'Card verification code input
Text'text'General-purpose secure text input (SSN, routing numbers, etc.)

Shared Options

All element types accept these options in createElement() and element.update():

OptionTypeDefaultDescription
placeholderstring--Placeholder text shown when the input is empty
ariaLabelstringElement-specificARIA label for screen readers
disabledbooleanfalseDisables the input
readOnlybooleanfalseMakes the input read-only

Text Element Options

OptionTypeDescription
validationRegExpPattern the value must match to be valid
requiredbooleanWhether the field is required
maxLengthnumberMaximum character length
passwordbooleanRenders as a password field
inputModestringMobile keyboard hint ('numeric', 'tel', etc.)
mask(RegExp | string)[]Character-by-character input mask
transform[RegExp, string]Transform applied before tokenization

CVV Element Options

OptionTypeDefaultDescription
showTogglebooleanfalseRenders a show/hide toggle button inside the field
concealbooleantrueHides the CVV value. Set to false to render it visible; updatable with element.update()

Element Methods

Every element exposes the same interface:

MethodSignatureDescription
mount(selector: string | HTMLElement) => Promise<void>Attaches the iframe to the DOM
unmount() => voidRemoves the iframe from the DOM
update(options) => Promise<void>Updates options on a mounted element
focus() => voidFocuses the input
blur() => voidBlurs the input
clear() => voidClears the current value
on(event, listener) => () => voidSubscribes to an event; returns an unsubscribe function

Properties: id (string), type (ElementType), mounted (boolean).

Events

EventFires when
readyElement iframe is loaded and interactive
changeInput value changes
focusElement receives focus
blurElement loses focus
errorAn infrastructure or API error occurs

change Event Payload

All elements include these fields in event.detail:

FieldTypeDescription
isValidbooleanInput passes all validation rules
isEmptybooleanInput is empty
errorValidationError | nullValidation error, or null if valid
elementTypestringElement type that fired the event
elementIdstringUnique element ID
timestampnumberUnix timestamp (ms)

The cardNumber element adds: cardBrand, last4, bin, cvvLengths, potentialBrands, and matchStrength.

cardNumberEl.on('change', (event) => {
  const { isValid, cardBrand, last4 } = event.detail;
  console.log(`${cardBrand} ...${last4}`, isValid);
});

error Event Codes

CodeDescription
MOUNT_ERRORFailed to mount the element iframe
POSTMESSAGE_TIMEOUTPostMessage timeout
IFRAME_LOAD_ERRORElement iframe failed to load
INITIALIZATION_ERRORSDK or coordinator failed to initialize
API_ERRORBasis Theory API returned an error
NETWORK_ERRORNetwork request failed
VALIDATION_ERRORInput failed client-side validation
INVALID_CONFIGURATIONInvalid SDK or element options
UNKNOWN_ERRORUnexpected error

SDK Options

const bt = BasisTheory('pk_test_...', {
  debug: false,            // Enable verbose debug logging
  themeMode: 'auto',       // 'light' | 'dark' | 'auto'
  theme: { /* ThemeTokens */ },
  darkTheme: { /* ThemeTokens */ },
  timeoutMs: 30000,        // PostMessage timeout (ms)
});

Services

tokens

// Create a token
const token = await bt.tokens.create({
  type: 'card',
  data: {
    number: cardNumberEl,
    expiration_month: expiryEl,
    expiration_year: expiryEl,
    cvc: cvvEl,
  },
});

// Retrieve a token
const retrieved = await bt.tokens.retrieve(token.id, {
  apiKey: sessionApiKey, // from an authorized session
});

// Update a token
await bt.tokens.update(token.id, {
  metadata: { source: 'updated' },
});

// Encrypt with client-side JWE
const encrypted = await bt.tokens.encrypt(
  { type: 'card', data: { number: cardNumberEl, cvc: cvvEl } },
  publicKeyPEM,
  'key-id-123'
);

tokenize

const result = await bt.tokenize({
  number: cardNumberEl,
  cvv: cvvEl,
  expiry: expiryEl,
});

tokenIntents

const intent = await bt.tokenIntents.create({
  type: 'card',
  data: {
    number: cardNumberEl,
    expiration_month: expiryEl,
    expiration_year: expiryEl,
    cvc: cvvEl,
  },
});

const retrieved = await bt.tokenIntents.get(intent.id);

sessions

const session = await bt.sessions.create();
// Send session.nonce to your backend to authorize
// Backend returns an apiKey for elevated access

const token = await bt.tokens.retrieve(tokenId, {
  apiKey: sessionApiKey,
});

Theming

Pass design tokens at initialization and switch modes at runtime:

const bt = BasisTheory('pk_test_...', {
  themeMode: 'auto',
  theme: {
    colors: {
      primary: '#007bff',
      error: '#dc3545',
      success: '#28a745',
      text: { primary: '#1a1a1a', placeholder: '#6c757d' },
      background: { default: '#ffffff' },
      border: { default: '#dee2e6', focus: '#007bff' },
    },
    typography: {
      fontFamily: 'Inter, sans-serif',
      fontSize: { base: '16px' },
      fontWeight: { normal: '400' },
    },
    spacing: { sm: '8px', md: '12px', lg: '16px' },
    borders: {
      radius: { base: '6px' },
      width: { base: '1px' },
    },
  },
});

// Switch theme mode at runtime
await bt.updateThemeMode('dark');

TypeScript

The package ships full type definitions. Key exports:

import type {
  BasisTheorySDK,
  Element,
  ElementType,
  ElementOptions,
  SDKOptions,
  ChangeEventDetail,
  CardNumberChangeEventDetail,
  ReadyEventDetail,
  ErrorEventDetail,
  ErrorCode,
  ValidationError,
  TokenizeResult,
  Session,
} from '@basis-theory/web-elements';

Documentation

Full documentation: https://developers.basistheory.com/docs/sdks/web/web-elements/

License

Apache-2.0

版本与发布记录

@basis-theory/web-elements 共发布 98 个版本,首次发布于 2025/01/24;过去 12 个月发布了 34 个版本。

版本发布日期距今
3.5.0latest2026/11/053 天前
2.18.1legacy2026/11/053 天前
3.4.02026/11/044 天前
2.18.02026/11/044 天前
3.3.12026/10/2316 天前
3.3.02026/10/2217 天前

其他发布通道:beta → 3.0.0-beta.6,legacy → 2.18.1。

关于 @basis-theory/web-elements 的常见问题

@basis-theory/web-elements 是什么?

Secure, PCI-compliant elements for creating payment input forms

如何安装 @basis-theory/web-elements?

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

@basis-theory/web-elements 支持 TypeScript 吗?

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

@basis-theory/web-elements 支持 ESM 还是 CommonJS?

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

@basis-theory/web-elements 可以商用吗?

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

@basis-theory/web-elements 的下载量有多少?

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

@basis-theory/web-elements 还在维护吗?

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