用途:本技能用于把 Better Auth 与 Dodo Payments 打通,实现用户注册时自动创建 Dodo 客户,并为已登录用户提供结账、客户门户、订阅与支付列表、计量用量上报和 Webhook 接收能力。
安装:npm install @dodopayments/better-auth dodopayments better-auth。服务端导出 dodopayments、checkout、portal、usage、webhooks;客户端入口导出 dodopaymentsClient。
服务端用法:在 betterAuth 的 plugins 中调用 dodopayments({ client, createCustomerOnSignUp, getCustomerParams, use: [...] })。每个端点由 use 中启用的功能注册,缺少某个功能时其路由返回 404。checkout 的 products 把应用 slug 映射到 Dodo 产品 ID,authenticatedUsersOnly: true 要求存在 Better Auth 会话。getCustomerParams 在客户同步时附加元数据;注意 user 仅含 Better Auth 基础字段,其他字段需先在 user.additionalFields 声明。
浏览器用法:用 createAuthClient 配合 dodopaymentsClient() 创建客户端,方法自动携带会话 Cookie,不要传 request.headers。可调用 checkoutSession({ slug, referenceId }) 跳转结账,customer.portal() 打开门户,customer.subscriptions.list 与 customer.payments.list 查询列表(返回 items 信封,支持 page、limit、status),usage.ingest 上报计量事件(customer_id 由会话推导,event_id 为幂等键)。
Webhook:webhooks({ webhookKey, onPayload }) 自行校验并处理请求,默认路径为 /api/auth/dodopayments/webhooks,不要另建路由,也不要调用不存在的 verifyWebhook。
已注册端点:POST /dodopayments/checkout、POST /dodopayments/checkout-session、GET /dodopayments/customer/portal、GET /dodopayments/customer/subscriptions/list、GET /dodopayments/customer/payments/list、POST /dodopayments/usage/ingest、GET /dodopayments/usage/meters/list、POST /dodopayments/webhooks。
限制与常见错误:只启用 portal() 会导致结账、用量、Webhook 路由不存在;混用浏览器与服务端 API;createCustomerOnSignUp 开启后不要重复调用 client.customers.create();权限判定应以校验过的 Webhook 事件或服务端查询为准,不要依赖浏览器状态;不要自行添加 Webhook 校验器。