我正确接收了 Stripe webhooks POST 请求,但在处理请求时遇到问题。 我有什么遗漏的吗? Console.logs 不会打印到终端。
这是我到目前为止的代码,其中概述了从 stripe 收到
checkout.session.completed
时我想要处理的内容。
./api/webhook/route.ts
import { createClient } from '@supabase/supabase-js';
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { NextApiRequest, NextApiResponse } from 'next';
import Stripe from 'stripe';
import { Resend } from 'resend';
import EmailTemplate from '@/components/email-template';
const resend = new Resend(process.env.NEXT_RESEND_API_KEY);
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`, {
apiVersion: '2023-08-16',
});
//Handling incoming POST req
async function POST(request: NextRequest) {
try {
const body = await request.text();
const endpointSecret = process.env.STRIPE_SECRET_WEBHOOK_KEY!;
const sig = headers().get('stripe-signature') as string;
// const sig = headers().get('Stripe-Signature') as string;
let event: Stripe.Event;
//read the event data from stripe
try {
event = stripe.webhooks.constructEvent(body, sig, endpointSecret);
} catch (err) {
return new Response(`Webhook Error: ${err}`, {
status: 400,
});
}
console.log(`Received event !webhook!: ${event?.type}`);
// Handle the event: checkout.session.completed
switch (event.type) {
case 'checkout.session.completed':
const session: any = event.data.object;
console.log('!Checkout session completed!:', session.payment_status);
// get customer name, email
const customerEmail = session.customer_details.email;
const customerName = session.customer_details.name;
// create the customer in db
const { data: customer, error: errorCustomer } = await supabase
.from('Customer')
.insert({ customerName, customerEmail })
.select()
.single();
if (errorCustomer) throw new Error(errorCustomer.message);
break;
default:
}
return NextResponse.json({ received: true });
} catch (error) {
return NextResponse.json({ error }, { status: 400 });
}
}
async function GET(request: NextApiRequest, response: NextApiResponse) {
// Bad Request or how ever you want to respond.
return response.status(400).json({ error: 'Bad Request' });
}
export { POST, GET };
提前谢谢您。
收到 Stripe CLI post 请求 Webhooks - 正常。
checkout.session.completed 已收到 - 确定 checkout.session.completed 会触发 supabase 和进一步的操作,尽管有正确的 POST 响应,但这些操作并未发生。
Noob 代表我犯错误:
听错路线了:
条带监听 --forward-to localhost:3000/api/checkout (NO)
stripe 监听 --forward-to localhost:3000/api/webhook (是)