NextJS条纹网钩原始主体

7eumitmz  于 2022-12-29  发布在  其他
关注(0)|答案(2)|浏览(137)

拔出我的头发试图通过一个原始的身体条纹webhook对NextJS!。
尝试了很多来自世界各地的解决方案,我似乎无法使它工作。
打开它的开发人员与超能力(其中我仍在收购)。
条带测试错误:
未找到与负载的预期签名匹配的签名。是否正在传递从条带接收的原始请求正文
我的NextJS webhook端点测试:

import { buffer } from 'micro';
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {

    console.log("Payment intent")

    const event = req.body

    console.log(event)

    if (process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET) {
        // Get the signature sent by Stripe
        const signature = req.headers['stripe-signature'];
        console.log(signature)
        try {
          event = stripe.webhooks.constructEvent(
            req.body,
            signature,
            process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET
          );
        } catch (err) {
          console.log(`⚠️  Webhook signature verification failed.`, err.message);
          return res.sendStatus(400);
        }
      }

    console.log(event.type)

    // Handle the event
    switch (event.type) {
        case 'payment_intent.succeeded':
            console.log("Success!")
            break;
        default:
            console.log(`Unhandled event type ${event.type}`);
    }


}

还尝试过:

import { buffer } from 'micro';
import Cors from 'micro-cors';

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

const webhookSecret = process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET_NEW;

// 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, res) => {

  if (req.method === 'POST') {
    const buf = await buffer(req);
    console.log(buf.toString())
    const sig = req.headers['stripe-signature'];
    console.log(process.env.STRIPE_SECRET_KEY)
    console.log(webhookSecret)
    console.log(sig)
    let event;

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

    if (event.type === 'payment_intent.succeeded') {
      const paymentIntent = event.data.object;
      console.log(`💰 PaymentIntent status: ${paymentIntent.status}`);
    } else if (event.type === 'payment_intent.payment_failed') {
      const paymentIntent = event.data.object;
      console.log(
        `❌ Payment failed: ${paymentIntent.last_payment_error?.message}`
      );
    } else if (event.type === 'charge.succeeded') {
      const charge = event.data.object;
      console.log(`💵 Charge id: ${charge.id}`);
    } else {
      console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`);
    }

    res.json({ received: true });
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
};

export default cors(webhookHandler);
yeotifhr

yeotifhr1#

默认情况下,NextJS根据头中传入的Content-Type解析请求主体。您可能希望禁用此[0],然后使用buffer将其作为流使用。
下面的代码适用于我:

export const config = {
  api: {
    bodyParser: false,
  },
};

import { buffer } from 'micro';
const stripe = require('stripe')(process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET);

export default async function handler(req, res) {

    let event;

    if (process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET) {
        // Get the signature sent by Stripe
        const signature = req.headers['stripe-signature'];
        const buf = await buffer(req);

        try {
          event = stripe.webhooks.constructEvent(
            buf,
            signature,
            process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET
          );
...

[0] https://nextjs.org/docs/api-routes/api-middlewares#custom-config

qq24tv8q

qq24tv8q2#

为了解决这个问题,我通过在同一个API路由文件中导出配置对象来禁用NextJS主体解析器:

export const config = {
  api: {
    bodyParser: false,
  },
};

然后我导入了raw-body package,这样就可以将请求流转换为原始缓冲区:

var getRawBody = require('raw-body')

最后我通过promise接口使用了raw-body包:

if (endpointSecret) {
  const signature = request.headers['stripe-signature'];
  console.log("sig", signature);
  getRawBody(request)
    .then(function (buf) {
      rawBody = buf;
      event = stripe.webhooks.constructEvent(
        rawBody,
        signature,
        endpointSecret
      );
      let subscription;
      let status;
      // Handle the event
      switch (event.type) {
        case 'customer.subscription.trial_will_end':
          subscription = event.data.object;
        
        default:
          // Unexpected event type
          console.log(`Unhandled event type ${event.type}.`);
      }
      // Return a 200 response to acknowledge receipt of the event
      return response.status(200);
    })
  .catch(function (err) {
    console.log(`⚠️  Webhook signature verification failed.`, err.message);
    return response.status(500);
  })
} else {
  console.log("Missing endpoint secret");
  return response.status(500);
}

这对我很有效,希望能帮到你。

相关问题