You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stripe测试时钟无法获取invoice.created上报的计量事件求助

Stripe用量计费Test Clock验证问题

我有一个基于用量计费的Stripe产品,账单周期为月度,周期结束时生成发票。我尝试用Test Clock验证用量是否被正确记录到发票中,但遇到了问题。

我通过监听invoice.created webhook,在发票处于草稿状态时计算用量并上报到计量器(Meter),上报的时间戳确保在该发票的计费周期内。但订阅生成的发票始终不显示我提交的用量。

测试环境操作步骤

  • 创建Test Clock
  • 在Test Clock中创建客户
  • 为该客户创建月度订阅,订阅起始时间设为当前时间
  • 将Test Clock推进一个月,触发invoice.created webhook事件
  • 我的webhook执行以下用量记录逻辑:
const invoice = event.data.object;
const {
  id,
  customer: stripeCustomerId,
  customer_email: email,
  period_start: invoicePeriodStart,
  period_end: invoicePeriodEnd,
  subscription: stripeSubscriptionId,
  status,
} = invoice;

try {
  // 用户首次订阅用量计费产品时会生成已定稿的发票,忽略该发票
  if (status !== 'draft') return;

  // 忽略无订阅关联的手动创建发票
  if (!stripeSubscriptionId) return;

  // 仅处理目标用量计费订阅的发票
  const subscription = await stripe.subscriptions.retrieve(stripeSubscriptionId);
  if (subscription.items.data[0].price.lookup_key !== myLookupKey) {
    console.log(
      `Subscription lookup key ${subscription.items.data[0].price.lookup_key} !== ${myLookupKey}`,
    );
    return;
  }

  const user = await users.findByEmail(email);

  // 调用其他服务获取该周期的用量数据
  const organization = user.organization;
  const startDate = new Date(invoicePeriodStart * 1000);
  const endDate = new Date(invoicePeriodEnd * 1000);
  const usageString = await crossServerPostRequest(
    new URL(`<URL FOR GETTING USAGE FOR PERIOD>`),
    {
      organization,
      startDate,
      endDate,
    },
  );

  await stripe.billing.meterEvents.create({
    event_name: 'event_name',
    identifier: crypto.randomUUID(),
    payload: {
      value: parseInt(usageString, 10),
      stripe_customer_id: stripeCustomerId,
    },
    timestamp: invoicePeriodEnd, invoicePeriodStart + (invoicePeriodEnd - invoicePeriodStart) / 2, // 尝试过多个时间戳值:invoicePeriodStart、invoicePeriodEnd等
  });

  postSlackMessage(
      `Usage reported to Stripe for ${user.organization}: ${usageString} (${startDate.toDateString()} - ${endDate.toDateString()})`,
    );
} catch (error) {
  console.error(error);
  postSlackMessage(
    `Error during invoice.created Stripe webhook for ${id} for ${request.body.email}; usage may not have been reported\n${error}`,
  );
}
  • 在Stripe控制台中确认计量事件已关联到Test Clock中的客户
  • 将Test Clock再推进一小时,触发发票定稿
  • 查看定稿后的发票,发现未包含上报的用量

疑问与额外尝试

  • 我的操作是否存在错误?Test Clock是否不支持这种计量器的使用方式?Stripe文档的Test Clock限制章节未提及计量器相关内容。
  • 我还尝试过将Test Clock推进到周期中途,手动在控制台为客户添加计量事件,再推进到周期结束,发票中仍未显示用量。
  • 曾将计量事件时间戳设为invoicePeriodStart时成功过几次,但结果不稳定。已知计量事件是异步处理的——这是否会导致结果不一致?我需要确保该流程在生产环境中稳定运行。

内容的提问来源于stack exchange,提问作者Scotty H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:39:59