收款
使用 Stripe Terminal 收取线下付款:先注册监听器,再初始化插件、连接读卡器并确认 PaymentIntent。
注册应用级监听器
每次 JavaScript 应用启动时注册一次 Terminal 事件监听器,越早越好,并在初始化或开始任何操作前完成注册。可在 main.ts、应用初始化器或启动时初始化的单例服务中注册,并让监听器与应用级持有者保持相同生命周期。
enum TerminalEventsEnum
| 成员 | 值 |
|---|---|
Loaded |
'terminalLoaded' |
DiscoveredReaders |
'terminalDiscoveredReaders' |
DiscoveringReaders |
'terminalDiscoveringReaders' |
CancelDiscoveredReaders |
'terminalCancelDiscoveredReaders' |
ConnectedReader |
'terminalConnectedReader' |
DisconnectedReader |
'terminalDisconnectedReader' |
ConnectionStatusChange |
'terminalConnectionStatusChange' |
UnexpectedReaderDisconnect |
'terminalUnexpectedReaderDisconnect' |
ConfirmedPaymentIntent |
'terminalConfirmedPaymentIntent' |
CollectedPaymentIntent |
'terminalCollectedPaymentIntent' |
Canceled |
'terminalCanceled' |
Failed |
'terminalFailed' |
RequestedConnectionToken |
'terminalRequestedConnectionToken' |
ReportAvailableUpdate |
'terminalReportAvailableUpdate' |
StartInstallingUpdate |
'terminalStartInstallingUpdate' |
ReaderSoftwareUpdateProgress |
'terminalReaderSoftwareUpdateProgress' |
FinishInstallingUpdate |
'terminalFinishInstallingUpdate' |
BatteryLevel |
'terminalBatteryLevel' |
ReaderEvent |
'terminalReaderEvent' |
RequestDisplayMessage |
'terminalRequestDisplayMessage' |
RequestReaderInput |
'terminalRequestReaderInput' |
PaymentStatusChange |
'terminalPaymentStatusChange' |
ReaderReconnectStarted |
'terminalReaderReconnectStarted' |
ReaderReconnectSucceeded |
'terminalReaderReconnectSucceeded' |
ReaderReconnectFailed |
'terminalReaderReconnectFailed' |
那些经过类型化的addListener方法重载版本,涵盖了上述大部分成员功能。而DiscoveringReaders和CancelDiscoveredReaders这两个方法则是通过原生发现机制来触发调用的,不过它们并没有对应的专门重载版本;有关详细信息,请参考相关 API 文档。
初始化
优先通过 RequestedConnectionToken 和 setConnectionToken 由应用发起已认证的请求,这样可以附加常规授权凭据并检查失败情况。在 initialize 前注册监听器。Terminal SDK 每次需要连接令牌时都会请求新的单次使用令牌。开发期间请设置 isTest。
method initialize(...)
初始化 Stripe Terminal SDK 及其连接令牌提供程序。在发现读卡器之前调用一次。若提供 tokenProviderEndpoint,插件会发送 POST 请求,并期待格式为 { secret: string } 的响应。若省略该选项,请处理 RequestedConnectionToken 并调用 setConnectionToken()。
initialize(options: StripeTerminalInitializationOptions) => Promise<void>
tokenProviderEndpoint 兼容模式
简单部署可以使用 tokenProviderEndpoint,但目前原生客户端只发送基本的 HTTP POST 请求,调用方不能添加授权请求头或请求体。仅当服务器能通过其他方式验证并保护该请求时才使用此模式。绝不可公开不受限制的令牌创建端点。
设置 tokenProviderEndpoint 后,插件会发送请求体为空的 HTTP POST 请求。响应必须是 JSON,且包含字符串类型的 secret:
{ "secret": "pst_..." }
此值是 Stripe Terminal 的连接令牌。请在服务器上用私密 API 密钥(stripe.terminal.connectionTokens.create())创建令牌。不要在应用二进制文件、日志或公开的客户端配置中包含私密密钥、有权创建令牌的受限密钥,以及原始连接令牌。
官方演示中,接口路径为POST /connection/token,返回的内容为{ secret }。请根据需求调整系统的认证和授权机制,以适用于你的应用。
Web 端的 initialize 需要全新的插件实例。初始化成功后再次调用会抛出 Stripe Terminal has already been initialized。
安全提供连接令牌
省略 tokenProviderEndpoint,并在 initialize 之前注册 RequestedConnectionToken。SDK 需要令牌时,插件会触发该事件并等待 setConnectionToken({ token })。
通过常用授权机制发起请求,要求响应成功,验证 secret 后将其作为 token 传入。仅在存在待处理请求时调用 setConnectionToken;在 Android 和 iOS 上,多余调用会以 Stripe Terminal do not pending fetchConnectionToken 被拒绝。切勿记录响应或令牌。
import { StripeTerminal, TerminalEventsEnum } from '@capacitor-community/stripe-terminal';
const tokenListener = await StripeTerminal.addListener(TerminalEventsEnum.RequestedConnectionToken, async () => {
try {
const response = await fetch('https://your-backend.example.com/terminal/token', {
method: 'POST',
headers: { Authorization: `Bearer ${await getAuthToken()}` },
});
if (!response.ok) throw new Error('Connection token request failed');
const { secret } = await response.json();
if (typeof secret !== 'string' || secret.length === 0) {
throw new Error('Missing connection token');
}
await StripeTerminal.setConnectionToken({ token: secret });
} catch (error) {
showConnectionError(error);
// 请勿传入缓存的令牌,也不要在未经身份验证的情况下重试。
}
});
await StripeTerminal.initialize({ isTest: true });
getAuthToken 和 showConnectionError 由应用实现。保留 tokenListener,直至其应用级持有者销毁。捕获网络请求错误不会结束 SDK 中等待令牌的请求。请显示失败信息,并提供针对此请求的已认证重试。不要假设插件自动超时或提供取消 API。
method setConnectionToken(...)
在收到 RequestedConnectionToken 后提供连接令牌密钥。每个令牌都必须由服务器创建且只能使用一次。
setConnectionToken(options: SetConnectionTokenOptions) => Promise<void>
在后端创建 PaymentIntent
请在服务器上创建 PaymentIntent。官方示例使用 POST /connection/intent,并将 { paymentIntent } 作为客户端密钥返回。
插件和示例共同遵循的要求:
payment_method_types必须包含card_present- 将 Stripe 私密密钥保留在服务端
- 仅将客户端密钥传给
collectPaymentMethod({ paymentIntent }) - 不要在应用中用可发布密钥创建或确认线下刷卡支付的 PaymentIntent
示例服务器的响应结构:
await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
payment_method_types: ['card_present'],
capture_method: 'automatic',
});
发现读卡器
搜索附近的实体读卡器或模拟读卡器。传入 TerminalConnectTypes 的值,如果该连接类型需要位置,还须提供 Stripe Terminal 的 locationId。
locationId 用于发现互联网读卡器,也是连接 Tap to Pay、Bluetooth 和 Android USB 读卡器的必填项。互联网读卡器可在发现时按地点筛选;Tap to Pay 和 Bluetooth 则将地点传入连接配置。
平台差异:
- Web 仅支持
Internet。其他type值均不可用。 - 在 iOS Bluetooth 发现过程中,随着扫描结果更新,读卡器会通过
DiscoveredReaders多次报告。参见 Stripe:在 iOS 上连接 Bluetooth 读卡器。可设置bluetoothScanWaitTime(毫秒),让discoverReaders等待相应时长再返回当前列表。设置为0或省略时会直接返回首次扫描结果。 - 在 iOS 上,扫描开始时也会触发
DiscoveringReaders。USB、HandOff 以及作为type的Simulated均未实现。 - Android 需要在运行时获取
ACCESS_FINE_LOCATION,否则discoverReaders会被拒绝。Simulated按 Bluetooth 发现处理,HandOff对应 Apps on Devices。 - 如果用户离开扫描界面,请调用
cancelDiscoverReaders。Web 上取消操作不生效。务必让用户可以停止耗时较长的 Bluetooth 扫描。
等待 Promise 的同时也要监听 DiscoveredReaders。在 iOS Bluetooth 发现期间,监听器提供实时列表,而 Promise 可能在最后一次事件之前完成。
method discoverReaders(...)
通过指定的连接方式发现读卡器。返回的读卡器列表是当前快照;要获取持续发现过程中的后续结果,请监听 DiscoveredReaders。
discoverReaders(options: DiscoverReadersOptions) => Promise<{ readers: ReaderInterface[]; }>
interface DiscoverReadersOptions
| 属性 | 类型 | 说明 | 起始版本 |
|---|---|---|---|
type |
TerminalConnectTypes |
用于发现读卡器的方式及连接类型。 | 5.1.0 |
locationId |
string |
Stripe Terminal Location ID,用于限定联网读卡器的发现范围,并在需要时限定注册范围。 | 5.1.0 |
bluetoothScanWaitTime |
number |
仅适用于 iOS 上的 Bluetooth 扫描发现。在发现过程中,通过 DiscoveryDelegate.didUpdateDiscoveredReaders 报告读卡器。此超时时间决定 discoverReaders 等待多久后返回当前列表。如果未指定或设为 0,则返回首次扫描的结果。 |
7.2.0 |
enum TerminalConnectTypes
| 成员 | 值 |
|---|---|
Simulated |
'simulated' |
Internet |
'internet' |
Bluetooth |
'bluetooth' |
Usb |
'usb' |
TapToPay |
'tap-to-pay' |
HandOff |
'hand-off' |
连接读卡器
采集付款信息前,请先连接已发现的读卡器之一。reader 对象必须来自本次发现结果,插件以 serialNumber 作为其主要标识符。
autoReconnectOnUnexpectedDisconnect 的默认值为 false,适用于 Tap to Pay 和 Bluetooth。Android 上的 USB 连接目前会在原生连接配置中启用自动重连;互联网连接不接受此标志。
merchantDisplayName 和 onBehalfOf 适用于 iOS Tap to Pay(LocalMobileReader)。在 Android 上,请改为在 PaymentIntent 中设置关联账户和显示值。
method connectReader(...)
连接到 discoverReaders() 返回的读卡器。
connectReader(options: ConnectReaderOptions) => Promise<void>
采集付款方式
将后端返回的 PaymentIntent 客户端密钥传给 collectPaymentMethod。插件先获取该 PaymentIntent,再通过已连接的读卡器采集付款方式。
method collectPaymentMethod(...)
为服务端创建的 PaymentIntent 采集付款方式,然后调用 confirmPaymentIntent() 进行确认。
collectPaymentMethod(options: CollectPaymentMethodOptions) => Promise<void>
确认 PaymentIntent
处理并确认已采集的 PaymentIntent。若此前未成功采集,confirmPaymentIntent 会返回 PaymentIntent not found for confirmPaymentIntent 错误。
method confirmPaymentIntent()
确认读卡器最近采集的 PaymentIntent。
confirmPaymentIntent() => Promise<void>
ConfirmedPaymentIntent 仅是客户端界面信号,不能作为履约依据。只有在后端验证了 payment_intent.succeeded 等 Stripe webhook 后,才能履约。
处理取消和错误
cancelCollectPaymentMethod取消正在进行的采集操作。取消成功时 Promise 正常完成并触发Canceled。collectPaymentMethod或confirmPaymentIntent失败时触发Failed,对应调用的 Promise 也会被拒绝。事件数据可能包含message、code和declineCode。- 请不要使用
ConnectionStatusChange方法来检测意外的断开连接情况。应使用UnexpectedReaderDisconnect事件来处理此类情况;对于蓝牙/USB 连接,还需要使用DisconnectedReader事件。详情请参阅Reader 生命周期。
method cancelCollectPaymentMethod()
取消正在进行的 collectPaymentMethod() 调用。
cancelCollectPaymentMethod() => Promise<void>
断开读卡器连接
在支付流程完成或不再需要该阅读器时,请断开连接。
method disconnectReader()
断开当前读卡器的连接。若未连接读卡器,Promise 会立即完成。
disconnectReader() => Promise<void>
import {
StripeTerminal,
TerminalConnectTypes,
TerminalEventsEnum,
} from '@capacitor-community/stripe-terminal';
const paymentStatusListener = await StripeTerminal.addListener(
TerminalEventsEnum.PaymentStatusChange,
({ status }) => console.log(status),
);
const confirmedListener = await StripeTerminal.addListener(
TerminalEventsEnum.ConfirmedPaymentIntent,
() => console.log('Payment processed; waiting for the server webhook'),
);
const failedListener = await StripeTerminal.addListener(
TerminalEventsEnum.Failed,
(error) => console.error(error),
);
// Register the authenticated RequestedConnectionToken provider first.
await StripeTerminal.initialize({ isTest: true });
const { readers } = await StripeTerminal.discoverReaders({
type: TerminalConnectTypes.TapToPay,
locationId: '**************',
});
const reader = readers[0];
if (!reader) throw new Error('No compatible reader found');
await StripeTerminal.connectReader({
reader,
});
try {
const response = await fetch('https://example.com/connection/intent', {
method: 'POST',
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!response.ok) throw new Error(`PaymentIntent request failed: ${response.status}`);
const { paymentIntent } = (await response.json()) as { paymentIntent: string };
await StripeTerminal.collectPaymentMethod({ paymentIntent });
await StripeTerminal.confirmPaymentIntent();
} finally {
await StripeTerminal.disconnectReader();
}
// Remove the three listeners when their application-level owner is destroyed.
import { StripeTerminal, TerminalEventsEnum } from '@capacitor-community/stripe-terminal';
await StripeTerminal.addListener(
TerminalEventsEnum.RequestedConnectionToken,
async () => {
try {
const response = await fetch('https://example.com/connection/token', {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) throw new Error(`Connection token request failed: ${response.status}`);
const data = (await response.json()) as { secret?: unknown };
if (typeof data.secret !== 'string' || !data.secret) {
throw new Error('Connection token response is missing secret');
}
await StripeTerminal.setConnectionToken({ token: data.secret });
} catch (error) {
// An empty token fails the pending native callback instead of leaving it hanging.
try {
await StripeTerminal.setConnectionToken({ token: '' });
} finally {
console.error('Unable to supply a connection token', error);
}
}
},
);
await StripeTerminal.initialize({
isTest: true,
});