NextJS Stripe Webhook 原始主体

Ste*_*veW 11 javascript webhooks stripe-payments serverless-framework next.js

试图在 NextJS 上传递 Stripe webhook 的原始主体时,我费尽心思!

\n

尝试了很多来自各地的解决方案,但我似乎无法使其发挥作用。

\n

打开具有超能力的开发人员(我仍在获取其中)。

\n

条纹测试错误:

\n
\n

未找到与负载的预期签名匹配的签名。您是否传递了从 Stripe 收到的原始请求正文

\n
\n

我的 NextJS webhook 端点测试:

\n
import { buffer } from 'micro';\nconst stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);\n\nexport default async function handler(req, res) {\n\n    console.log("Payment intent")\n\n    const event = req.body\n\n    console.log(event)\n\n    if (process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET) {\n        // Get the signature sent by Stripe\n        const signature = req.headers['stripe-signature'];\n        console.log(signature)\n        try {\n          event = stripe.webhooks.constructEvent(\n            req.body,\n            signature,\n            process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET\n          );\n        } catch (err) {\n          console.log(`\xe2\x9a\xa0\xef\xb8\x8f  Webhook signature verification failed.`, err.message);\n          return res.sendStatus(400);\n        }\n      }\n\n    console.log(event.type)\n\n    // Handle the event\n    switch (event.type) {\n        case 'payment_intent.succeeded':\n            console.log("Success!")\n            break;\n        default:\n            console.log(`Unhandled event type ${event.type}`);\n    }\n\n\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

也尝试过:

\n
import { buffer } from 'micro';\nimport Cors from 'micro-cors';\n\nconst stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);\n\nconst webhookSecret = process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET_NEW;\n\n// Stripe requires the raw body to construct the event.\nexport const config = {\n  api: {\n    bodyParser: false,\n  },\n};\n\nconst cors = Cors({\n  allowMethods: ['POST', 'HEAD'],\n});\n\nconst webhookHandler = async (req, res) => {\n\n  if (req.method === 'POST') {\n    const buf = await buffer(req);\n    console.log(buf.toString())\n    const sig = req.headers['stripe-signature'];\n    console.log(process.env.STRIPE_SECRET_KEY)\n    console.log(webhookSecret)\n    console.log(sig)\n    let event;\n\n    try {\n      event = stripe.webhooks.constructEvent(\n        buf.toString(),\n        sig,\n        webhookSecret\n      );\n    } catch (err) {\n      console.log(`\xe2\x9d\x8c Error message: ${err.message}`);\n      res.status(400).send(`Webhook Error: ${err.message}`);\n      return;\n    }\n\n\n    if (event.type === 'payment_intent.succeeded') {\n      const paymentIntent = event.data.object;\n      console.log(` PaymentIntent status: ${paymentIntent.status}`);\n    } else if (event.type === 'payment_intent.payment_failed') {\n      const paymentIntent = event.data.object;\n      console.log(\n        `\xe2\x9d\x8c Payment failed: ${paymentIntent.last_payment_error?.message}`\n      );\n    } else if (event.type === 'charge.succeeded') {\n      const charge = event.data.object;\n      console.log(` Charge id: ${charge.id}`);\n    } else {\n      console.warn(`\xe2\x80\x8d\xe2\x99\x80\xef\xb8\x8f Unhandled event type: ${event.type}`);\n    }\n\n    res.json({ received: true });\n  } else {\n    res.setHeader('Allow', 'POST');\n    res.status(405).end('Method Not Allowed');\n  }\n};\n\nexport default cors(webhookHandler);\n
Run Code Online (Sandbox Code Playgroud)\n

ale*_*lex 7

默认情况下,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
          );
...
Run Code Online (Sandbox Code Playgroud)

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

  • 有没有办法在没有“微型”包的情况下做到这一点?我不愿意为此引入另一个依赖项...... (3认同)