You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stripe Webhook生产环境无法执行回调问题排查与解决

Stripe Webhook生产环境无法触发回调函数

基于Next.js、Strapi和Stripe搭建的项目中,支付成功后触发的Webhook需调用markProductAsSold回调函数。本地环境下功能正常,但生产环境中Webhook触发后该回调函数不执行。单独触发回调(比如页面按钮点击)时,本地和生产环境均能正常工作。

已多次验证metadata.MarkAsSold及所有环境变量均有效,仅生产环境中由Stripe Webhook触发时回调无法执行。

Webhook代码

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

export default async function webhookHandler(req, res) {
    const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET, {
        apiVersion: '2022-11-15',
    });

    if (req.method === 'POST') {
        const buf = await buffer(req);
        const sig = req.headers['stripe-signature'];
        const webhookSecret = process.env.NEXT_PUBLIC_STRAPI_WEBHOOK_KEY;

        let event;

        try {
            if (!sig || !webhookSecret) return;

            event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
        } catch (error) {
            return res.status(400).send(`Webhook error: ${error.message}`);
        }

        if (event.data.object.status === 'succeeded') {
            await markProductAsSold(event.data.object.metadata.MarkAsSold);
        }
    }

    res.status(200).send();
}

回调函数代码

const markProductAsSold = async (slug: string) => {
    const findProduct = await fetch(
        `${process.env.NEXT_PUBLIC_DATABASE_URL}/api/products?filters[slug][$eq]=${slug}`
    );

    const data = await findProduct.json();

    const isSold = data.data[0].attributes.isSold;

    const productData = {
        ...data.data[0]
    };
    productData.attributes.isSold = !isSold;

    await fetch(
        `${process.env.NEXT_PUBLIC_DATABASE_URL}/api/products/${productData.id}`, {
            method: 'PUT',
            headers: {
                Authorization: `Bearer ${process.env.NEXT_PUBLIC_STRAPI_TOKEN}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                data: productData.attributes,
            }),
        }
    );

    return productData;
};

export default markProductAsSold;

已解决

将markProductAsSold函数直接移入Webhook处理函数中if (event.data.object.status === 'succeeded')的逻辑块内后,生产环境功能恢复正常。

内容的提问来源于stack exchange,提问作者Lazarusss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:45:22