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

如何通过代码实现Stripe的「立即开票」功能?

问题:如何通过代码实现Stripe后台的「立即开票」功能?

我通过以下代码创建了多个未关联发票ID的Invoice Item:

const invoiceItem = await stripe.invoiceItems.create({
    customer: customerId,
    price,
});

现在我想发送包含所有已创建Invoice Item的发票,但直接创建发票后更新Invoice Item关联发票ID的方法无法实现(Stripe不允许此操作):

// ===== DOES NOT WORK =====
const invoice = await stripe.invoices.create({
  customer: customerId,
  collection_method: 'send_invoice',
  days_until_due: 30,
});
await stripe.invoiceItems.update({
  customer: customerId,
  price,
  invoice: invoice.id,
})

我实际想要实现的是Stripe后台中「立即开票」按钮的功能,请问如何通过代码实现?是否需要重新创建所有Invoice Item?


解决方案

不需要重新创建Invoice Item,利用Stripe的原生机制即可实现后台「立即开票」的功能,具体步骤如下:

1. 创建发票(自动关联未绑定的Invoice Item)

调用stripe.invoices.create时,Stripe会自动将该客户名下所有未关联到任何发票的pending状态Invoice Item添加到新创建的发票中,无需手动关联:

const invoice = await stripe.invoices.create({
  customer: customerId,
  collection_method: 'send_invoice',
  days_until_due: 30,
});

2. 完成发票生成

新创建的发票处于draft(草稿)状态,必须调用finalizeInvoice将其转为open(有效)状态,这一步对应后台点击「立即开票」后的确认流程:

const finalizedInvoice = await stripe.invoices.finalizeInvoice(invoice.id);

3. 发送发票给客户

如果需要自动将发票发送到客户邮箱,调用sendInvoice接口即可:

await stripe.invoices.sendInvoice(finalizedInvoice.id);

关键注意事项

  • Stripe不允许修改已创建Invoice Item的invoice字段,因此无需尝试手动关联,创建发票时会自动完成关联。
  • 只有pending状态且未绑定任何发票的Invoice Item会被自动加入新发票,已绑定或已结算的Item不会被重复添加。

内容的提问来源于stack exchange,提问作者Ping Kee Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:09