跳到正文

付款 API

x402-paysdk/pay 的支付、钱包、offer、收据、恢复、DID 与交易 API。

TypeScript
import { pay } from 'x402-paysdk/pay';

该入口可以运行在付款客户端。它不接收私钥,只在验证 payment requirements 和 signed offer 后调用宿主 WalletSigner

核心函数

函数签名用途
getPaymentRequired(refUrl: string, amount?: string) => Promise<PaymentRequired>解析 ref 并校验 402,不请求签名
pay(options: PayOptions) => Promise<PayResult>协商、验证 offer、签署 EIP-3009、提交并返回证据
prepareEip3009TypedData(required, payer) => Eip712TypedData构造有时间边界的 TransferWithAuthorization
toReceiveUrl(refUrl: string) => URLx402pay:// 转为 receive URL
decodePaymentRequired(encoded: string) => PaymentRequired解码 payment-required header

pay(options)

TypeScript
interface PayOptions { refUrl: string; wallet: WalletSigner; paymentId?: string; amount?: string; trustedOfferSigners?: string[]; requireSignedOffer?: boolean; fetch?: typeof fetch;}
参数必填行为
refUrlx402pay:// 引用或受支持 receive URL
wallet提供 address 与 signTypedData 的宿主适配器
paymentId幂等 id;默认使用 invoice id 或随机公开 id
amount开放金额 ref 必填原子单位金额
trustedOfferSigners网关 signer allowlist;未提供时使用同源 DID 发现
requireSignedOffer默认 true,只应在受控开发环境关闭
fetch自定义测试或有界 transport
TypeScript
interface WalletSigner { address: string; signTypedData(params: Eip712TypedData): Promise<string>;}

返回签名必须是 65-byte EVM signature。Nonce 和有效时间窗由 SDK 生成,钱包适配器不应修改 typed data。

返回值

PayResult 包含 txHashpayToamountnetworkpayerreceiptStatusstatus: "settled",以及可选的 signedPaymentReceiptreceipt。签名 envelope 和 receipt JSON 必须成对归档,不能修改字段。

Offer 与 DID

函数用途
verifySignedOffer验证 offer 存在性、上下文、签名、signer trust、payment id 和 expiry
fetchGatewayDidDocument加载并校验 /.well-known/did.json,默认最大 16 KiB
discoverGatewayDidSigners返回同源 DID assertion signer
gatewayDidSigners校验已经加载的 DID document
didWebIdFromGateway从网关 origin 推导 did:web id

收据 API

函数网络请求用途
verifySignedPaymentReceipt验证 envelope、content hash、预期字段和 signer allowlist
verifyReceipt调用 /verify-receipt 验证链状态、金额和 payTo
paymentReceiptContentHash生成规范 sha256: payment receipt ref
verifySignedRefundReceipt本地验证退款收据
verifyRefundReceipt验证退款收据与反向链转账
refundReceiptContentHash生成规范退款 receipt hash

verifyReceipt 的结果会分开返回 validconfirmed。签名有效的收据仍可能没有达到要求的确认数。

恢复和链查询

函数签名说明
recoverSettlement(options) => Promise<RecoverSettlementResult>恢复已知结算,不会再次 settle
getTxStatus(gateway, txHash) => Promise<TxStatus>校验 hash 并查询有界状态
getPaymentHistory(gateway, options) => Promise<PaymentHistoryResult>查询有界 USDC Transfer log

getPaymentHistory 必须提供 payTofrom 或 cursor,还支持 assetfromBlocklimit

该入口同时导出 PaymentRequiredPaymentOfferPaymentPayloadPaymentReceiptRefundReceiptEip712TypedDataPayOptionsPayResultWalletSignerTxStatus 以及验证和恢复相关类型。