Webhook 错误:无法从标头中提取时间戳和签名 - Netlify Functions 和 Stripe

问题描述

我正在尝试在 checkout.session.completed 事件完成后控制台记录 Stripe customerID。但我收到此 400 状态代码错误无法从标题提取时间戳和签名”。我似乎无法找到将 Stripe 客户 ID 写入控制台日志的解决方案。

感谢任何帮助或指示。这是我的代码

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

exports.handler = async ({ body,headers }) => {
  try {
    const stripeEvent = stripe.webhooks.constructEvent(
      body,headers['stripe-signature'],process.env.STRIPE_WEBHOOK_SECRET
    );

    if (stripeEvent.type === 'checkout.session.completed') {
      const eventObject = stripeEvent.data.object;
      const customerID = eventObject.customer;
      console.log(customerID);
      console.log(headers);
    }
    return {
      statusCode: 200,body: JSON.stringify(customerID),};
  } catch (err) {
    console.log(`Stripe webhook Failed with ${err}`);
    return {
      statusCode: 400,body: `Webhook Error: ${err.message}`,};
  }
};

当我按照在终端中获取评论中的建议控制台记录标题时:

console.log(headers)

我现在可以在终端中看到客户 ID (cus_JOqbW95ulF3zx0),但是我需要什么来将其记录为 customerID?当终端说customerID 未定义时。

解决方法

我能够弄清楚。我在 IF 语句之后的返回是 400 状态代码错误的原因。 customerID 显示在控制台中,我将正文统计代码中的返回值更改为字符串“success”。

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

exports.handler = async ({ body,headers }) => {
  try {
    const stripeEvent = stripe.webhooks.constructEvent(
      body,headers['stripe-signature'],process.env.STRIPE_WEBHOOK_SECRET
    );

    if (stripeEvent.type === 'checkout.session.completed') {
      const eventObject = stripeEvent.data.object;
      const customerID = eventObject.customer;
      console.log(customerID);
    }
    return {
      statusCode: 200,body: 'success',};
  } catch (err) {
    console.log(`Stripe webhook failed with ${err}`);
    return {
      statusCode: 400,body: `Webhook Error: ${err.message}`,};
  }
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...