Stripe - 检索结帐会话的 line_items

Posted

技术标签:

【中文标题】Stripe - 检索结帐会话的 line_items【英文标题】:Stripe - Retrieving the line_items of checkout session 【发布时间】:2021-12-24 13:16:59 【问题描述】:

我正在尝试在 Stripe 中获取结帐会话的 line_items,以便我可以发送包含产品下载链接的电子邮件,但不幸的是,当我尝试在 checkout_session 中检索 line_items 时,我得到了一个空值。

前端:Next.js

这是我在/pages/api/webhooks/index.ts中的代码:

检查线:77

import  buffer  from "micro";
import Cors from "micro-cors";
import  NextApiRequest, NextApiResponse  from "next";

import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, 
  // https://github.com/stripe/stripe-node#configuration
  apiVersion: "2020-08-27",
);

const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET!;

// Stripe requires the raw body to construct the event.
export const config = 
  api: 
    bodyParser: false,
  ,
;

const cors = Cors(
  allowMethods: ["POST", "HEAD"],
);

const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => 
  if (req.method === "POST") 
    const buf = await buffer(req);
    const sig = req.headers["stripe-signature"]!;

    let event: Stripe.Event;

    try 
      event = stripe.webhooks.constructEvent(
        buf.toString(),
        sig,
        webhookSecret
      );
     catch (err) 
      // On error, log and return the error message.
      console.log(`❌ Error message: $err.message`);
      res.status(400).send(`Webhook Error: $err.message`);
      return;
    

    // Successfully constructed event.
    console.log(`✅ Success: $event.id`);

    // Cast event data to Stripe object.
    if (event.type === "payment_intent.created") 
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      console.log(`???? PaymentIntent status: $paymentIntent.status`);
      console.log('-----------------------------------------------------');
     else if (event.type === "payment_intent.payment_failed") 
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      console.log(
        `❌ Payment failed: $paymentIntent.last_payment_error?.message`
      );
      console.log('-----------------------------------------------------');
     else if (event.type === "customer.created") 
      const customer = event.data.object as Stripe.Customer;
      console.log(`Customer created: $customer.id`);
      console.log('-----------------------------------------------------');
     else if(event.type === 'payment_intent.requires_action') 
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      console.log(`❌ Payment requires action: $paymentIntent.id`);
     else if (event.type === "payment_intent.succeeded") 
      const paymentIntent = event.data.object as Stripe.PaymentIntent;
      console.log(`???? Payment succeeded: $paymentIntent.id`);
      console.log('-----------------------------------------------------');
     else if (event.type === "charge.succeeded") 
      const charge = event.data.object as Stripe.Charge;
      console.log(`???? Charge id: $charge.id`);
      console.log('-----------------------------------------------------');
     else if (event.type === "checkout.session.completed") 
      const checkout_session = event.data.object as Stripe.Checkout.Session;
      console.log(`???? Session id: $checkout_session.id`);
      console.log(`Customer email: $checkout_session.customer_details.email`);
      console.log(`Order products: $checkout_session.line_items`);
      console.log('-----------------------------------------------------');
     else 
      console.warn(`????‍♀️ Unhandled event type: $event.type`);
      console.log('-----------------------------------------------------');
    

    // Return a response to acknowledge receipt of the event.
    res.json( received: true );
   else 
    res.setHeader("Allow", "POST");
    res.status(405).end("Method Not Allowed");
  
;

export default cors(webhookHandler as any);

当我尝试在checkout_session 中记录line_items 时,我得到一个空值。

【问题讨论】:

【参考方案1】:

如API reference 中所述,会话的line_items 是“可扩展的”,默认情况下不包括在内。这意味着它们在 webhook 事件中传递时不包含在对象中,并且您必须在检索对象时通过 expansion 显式请求该值。

要获得这些,您需要检索 Session 并请求将line_items 包含在响应中:

const session = await stripe.checkout.sessions.retrieve(
  'cs_test_123', 
  expand: ['line_items']
);

【讨论】:

以上是关于Stripe - 检索结帐会话的 line_items的主要内容,如果未能解决你的问题,请参考以下文章

将 Stripe 结帐会话与订阅 webhook 关联

Stripe:如何更新通过订阅结帐会话创建的发票?

您如何为 Stripe 结帐会话生成付费发票 PDF?

使用 Java 在 Stripe 上创建包含多个项目的结帐会话

Stripe - 在创建结帐会话和付款时/之后将元数据添加到连接/目标帐户中

从条带事件中获取产品 ID(结帐会话已完成)