跳到主要内容

Payment Kit 事件监听机制

Payment Kit 提供两种事件监听方式,让您能够及时响应系统中的各类事件。

监听方式

方式一:Webhook

适用于分布式系统,支持跨服务通信。

  1. 注册 Webhook 端点:
javascript
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);
};
  1. 实现回调处理:
javascript
// 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

适用于单应用内的事件处理,实现更简单。

javascript
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 - 退款成功