npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@spiellberg/payment

v0.1.0

Published

Headless, framework-agnostic TypeScript payment SDK: normalized sessions, channel executors, reference HTTP adapter and contract tests

Readme

Payment

无 UI、框架无关的 TypeScript 前端支付 SDK。消费方安装后通过内置参考 Adapter(后端按契约实现)或自写 PaymentAdapter 接入业务后端,获得支付动作、渠道前端执行与状态跟踪能力;SDK 不直接调用微信/支付宝服务端接口。

当前交付:P-00 ~ P-02

已包含:

  • PaymentAdapter、PaymentSession、支付/履约分离模型。
  • PaymentClient.createPayment、queryPayment:单次调用、输入/响应验证、原订单关联校验、AbortSignal。
  • PaymentClient.watchPayment:有界轮询控制器(退避、总预算、pause/resume/stop、快照订阅、迟到/乱序响应隔离),只查不建。
  • 渠道前端执行器:invokeWechatJsapi(微信内 H5 调起)、openPaymentRedirect(支付宝 Page 等受控 https 跳转)。执行动作只产出 UX 信号,不代表已付款。
  • createHttpAdapter:参考 HTTP Adapter,后端按 backend-contract 实现即可零对接。
  • runAdapterContract:框架无关的 Adapter 契约测试,宿主自验接入正确性。
  • 固定错误模型(含 UNSUPPORTED/execute)、不自动重试创建、不可变返回快照;Adapter 错误经白名单重建(ADR 0009)。
  • getAvailableAction:支付动作到期判断,不修改支付事实。
  • TypeScript 严格检查、Vitest、ESM/声明构建与产物 smoke。

尚未包含:DramaForge 业务对接、UI/二维码组件、真实支付联调(P-03)。没有 React、Go、数据库或运行时第三方依赖。

首个接入方是 DramaForge 微信 Native 充值。SDK 通用范围包含 wechat_native、wechat_jsapi、alipay_page 三种渠道动作;支付宝是通用能力,不在 DramaForge 本期开通范围。OPC、身份来源、积分及双结算规则不进入 SDK 核心。

文档

开发

工具环境:Node.js >=22.12(.node-version)、pnpm 12.3.4。浏览器运行时不依赖 Node.js。

pnpm install --frozen-lockfile
pnpm check
pnpm test:watch

pnpm check 执行格式检查、类型检查、单元测试、构建、产物 smoke 和打包内容验证(pack:check:tgz 只含 dist+README,解包后可真实导入)。输出在 dist/,入口是 ESM 与 .d.ts。测试使用本地 Fake Adapter,不发生真实付款;Node 单测不是浏览器或生产渠道验收。

运行时要求

  • ES2022+ 宿主:Promise、BigInt、URL、URLSearchParams、AbortSignal。
  • createHttpAdapter 需要 fetch(现代浏览器/Node 18+ 均有),或以 fetch 选项注入。
  • invokeWechatJsapi 需要微信 webview 的 WeixinJSBridge(或注入桥对象);openPaymentRedirect 需要 location.assign(或注入 navigate)。缺环境能力时抛 UNSUPPORTED 而非崩溃。
  • SSR/Node 中导入无副作用:浏览器全局只在执行器调用时经 globalThis 惰性读取。

接入方式

业务应用先创建自己的订单,再把该订单交给 SDK。Adapter 的 API 路径、认证、当前用户/OPC 和 wire 映射由应用提供。

import { PaymentClient, getAvailableAction, type PaymentAdapter } from '@spiellberg/payment'

export async function preparePayment(
  adapter: PaymentAdapter,
  orderId: string,
  idempotencyKey: string,
  signal: AbortSignal,
) {
  const client = new PaymentClient(adapter)
  const session = await client.createPayment(
    { orderId, method: 'wechat_native' },
    { idempotencyKey, signal },
  )
  return { session, action: getAvailableAction(session) }
}

监听支付进度

watchPayment 持续观察一笔已存在的支付尝试,直到后端给出终态、宿主停止或预算耗尽。它只查询原引用,不会重复创建支付。

const watch = client.watchPayment(
  { orderId: session.orderId, paymentId: session.paymentId },
  { signal },
)

const unsubscribe = watch.subscribe((snapshot) => {
  // snapshot: { state, session, lastError, endReason },均为冻结对象
  // state: polling | paused | ended | stopped | expired
  // ended 的 endReason: fulfilled | succeeded | closed | failed | review_required | error
})

watch.pause() // 页面隐藏时暂停;resume() 恢复;stop() 终止
const final = await watch.settle // 终态快照,永不 reject

要点:

  • 有界轮询:interval/maxInterval/maxElapsed/maxAttempts/jitter 有默认值(3s/30s/15min/100 次/20%),从创建时刻计时,暂停时间也计入预算。
  • succeeded + fulfillment: 'pending' 会继续轮询等履约;unknown 继续查;鉴权/非法响应等非重试错误以 ended + endReason: 'error' 终止并保留在 lastError。
  • 页面可见性由宿主决定何时 pause/resume,SDK 不读取 document。
  • expired/stopped/ended 后不再活动;要继续观察须新建 watch。

上述为接入模式,不是已存在的 DramaForge Adapter。包当前 private: true,包名暂定,尚未发布;不要执行安装已发布包的假设命令。

渠道执行器

支付动作的执行是前端交互,不是支付事实。执行器惰性读取浏览器全局(WeixinJSBridge、location.assign),全部可注入、SSR 安全。

import { invokeWechatJsapi, openPaymentRedirect } from '@spiellberg/payment'

// 微信 JSAPI(微信内 H5):action.type === 'jsapi_invoke'
const outcome = await invokeWechatJsapi(action) // 'ok' | 'cancel' | 'fail',仅 UX 信号

// 支付宝 Page / 其他 redirect:action.type === 'redirect'
openPaymentRedirect(action) // 仅跳转 https 且无凭据的 URL

invokeWechatJsapi 返回 'ok' 只表示用户在钱包里完成操作,到账仍须由 watchPayment/queryPayment 的后端观测确认。环境缺少渠道能力时抛出 UNSUPPORTED(operation: 'execute')。

参考 HTTP Adapter

后端按 backend-contract 实现支付会话接口时,前端无需自写 Adapter:

import { createHttpAdapter, PaymentClient } from '@spiellberg/payment'

const adapter = createHttpAdapter({
  baseUrl: 'https://api.example.com',
  headers: () => ({ authorization: `Bearer ${token()}` }), // 认证由宿主注入
  // fetch、mapError 均可注入覆盖
})
const client = new PaymentClient(adapter)

宿主自写 Adapter 时可用 runAdapterContract(adapter, { failingReference }) 在测试中断言契约逐项成立。

Adapter 约定

  • createPayment 为已有订单准备支付尝试,返回后端持久化的 paymentId;不得在浏览器伪造 ID 或支付成功。
  • queryPayment 必须返回原 orderId/paymentId,不能静默换成最新订单。
  • amount.minor 是人民币分的正整数字符串,revision 是后端单调版本字符串。不要做浮点金额计算。
  • action 是 qr_code/redirect/jsapi_invoke 或 null;expiresAt 是 epoch 毫秒。二维码图片由应用生成,SDK 不渲染 DOM。getAvailableAction 只接受 SDK 返回的会话对象。
  • status: succeeded 与 fulfillment: fulfilled 不同;仅后端确认履约。无独立履约的项目用 not_applicable。
  • Adapter 需复用应用受控 HTTP Client,捕获并复核会话世代,使用传入 signal;不接收商户密钥。
  • 请求超时、取消或失败不证明未支付。复用原业务键查单/恢复,不自动换键或创建另一笔支付。

取消与错误

取消仅停止浏览器等待,不是关闭订单。Adapter 即使忽略取消,SDK 也不会交付取消后的迟到结果;后端仍可能完成原请求。

SDK 不自动读取 window、document、存储、认证或环境变量。未知 Adapter 错误使用固定安全消息,不附带原始异常;Adapter 抛出的 PaymentError 也会按白名单重建(operation 取当前操作,outcome 只在"确未发出"的错误码下可信,cause 等附加字段被丢弃)。单次调用没有隐式超时,宿主通过 AbortSignal 设置预算;watchPayment 有内置预算。

发布边界

许可证已定 Apache-2.0(见 LICENSE);npm scope @spiellberg 已建立;尚无 Git remote,repository 字段在建仓后补充。发布步骤(首次):

  1. 移除 "private": true,确认 version。
  2. pnpm check(含 pack:check:包内容只含 dist+README+LICENSE,解包可导入)。
  3. npm publish --access public(scoped 首次发布必须显式声明公共访问)。

构建包仅包含 dist、README 与 LICENSE,不包含测试和商户配置。

三种 DramaForge 接入方式的同次上线、真实渠道确认、账本一致性和资金恢复需要前后端共同验收,不因 SDK 单测通过而视作完成。