Payment Kit 事件监听机制
Payment Kit 提供两种事件监听方式,让您能够及时响应系统中的各类事件。
监听方式#
方式一:Webhook#
适用于分布式系统,支持跨服务通信。
- 注册 Webhook 端点:
const ensureWebhooks = async () => {
const enabledEvents = [
'customer.subscription.started',
'customer.subscription.renewed',
];
const result = await payment.webhookEndpoints.list({ page: 1, size: 100 });
if (result.list.length) {
const webhook = await payment.webhookEndpoints.update(result.list[0].id, {
url: getUrl('/api/payment/callback'),
enabled_events: enabledEvents,
});
logger.info('webhooks updated', webhook);
return;
}
const webhook = await payment.webhookEndpoints.create({
url: getUrl('/api/payment/callback'),
enabled_events: enabledEvents,
});
logger.info('webhooks created', webhook);
};
- 实现回调处理:
// api/routes/payment/callback.js
const { verifySig } = require('@blocklet/sdk/lib/middlewares/component');
router.post('/payment/callback', verifySig, (req, res) => {
const event = req.body;
switch(event.type) {
case 'customer.subscription.started':
await handleSubscriptionStart(event.data);
break;
case 'customer.subscription.renewed':
await handleSubscriptionRenew(event.data);
break;
}
}
方式二:EventBus#
适用于单应用内的事件处理,实现更简单。
const EventBus = require('@blocklet/sdk/service/eventbus');
EventBus.subscribe((event) => {
switch(event.type) {
case 'customer.subscription.started':
handleSubscriptionStart(event.data);
break;
case 'customer.subscription.renewed':
handleSubscriptionRenew(event.data);
break;
}
});
事件类型说明#
结账事件#
checkout.session.completed
- 支付结账完成checkout.session.nft_minted
- NFT 铸造完成
订阅事件#
customer.subscription.created
- 订阅创建customer.subscription.started
- 订阅开始customer.subscription.renewed
- 订阅续期customer.subscription.upgraded
- 订阅升级customer.subscription.updated
- 订阅更新customer.subscription.deleted
- 订阅取消customer.subscription.paused
- 订阅暂停customer.subscription.resumed
- 订阅恢复
试用期事件#
customer.subscription.trial_start
- 试用开始customer.subscription.trial_will_end
- 试用即将结束customer.subscription.trial_end
- 试用结束
支付事件#
payment_intent.succeeded
- 支付成功payment_intent.payment_failed
- 支付失败invoice.paid
- 发票支付完成refund.succeeded
- 退款成功