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

问题描述 投票:0回答:1

在 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}`,
    };
  }
};

当我根据终端中的注释中的建议控制台记录标头时:

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

stripe-payments netlify netlify-function
1个回答
0
投票

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

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}`,
    };
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.