我无法将 publicMetadata 发送给 Clerk(auth 提供者),因为 Stripe 无法找到 /api/webhook 路由并调用它以调用将发送 publicMetadata 的某些函数。
/api/stripe/route.ts
import Stripe from 'stripe';
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@clerk/nextjs/server';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);
export async function POST(request: NextRequest) {
try {
const { userId } = auth()
console.log("userId = ", userId)
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price: "price_1Q6CYqHP9wN4meCvzklGUQbx",
quantity: 1,
}
],
mode: 'payment',
success_url: 'https://chatti-jade.vercel.app/dashboard/habits',
// success_url: 'http://localhost:3000/dashboard/habits',
cancel_url: 'https://chatti-jade.vercel.app/dashboard/habits',
// cancel_url: 'http://localhost:3000/dashboard/habits',
metadata: {
userId: userId,
priceId: "price_1Q6CYqHP9wN4meCvzklGUQbx",
}
});
return NextResponse.json({ result: checkoutSession, ok: true });
} catch (error) {
console.log(error);
return NextResponse.json({ error: error}, { status: 500 });
}
}
api/webhooks/route.ts
import { NextRequest, NextResponse } from 'next/server';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string)
import { clerkClient } from '@clerk/nextjs/server'
export async function POST(request: NextRequest) {
try {
const buf = await request.text(); // Get the raw body
const sig = request.headers.get('stripe-signature') as string;
// Construct the event with Stripe's signature
const event = stripe.webhooks.constructEvent(buf, sig, process.env.STRIPE_WEBHOOK_SECRET!);
// Handle the event (for example, checkout.session.completed)
if (event.type === 'checkout.session.completed') {
const session = event.data.object as Stripe.Checkout.Session;
console.log(`Payment was successful for session ID: ${session.id}`);
// Process the session or update your database here.
const userId = session.metadata?.userId || 'user_2kbeVlEvHUAj35OGinSns4FktxF';
console.log(`User ID: ${userId}`);
if (userId) {
await clerkClient.users.updateUserMetadata(userId, {
publicMetadata: {
paid: true,
paymentId: session.id,
},
})
} else {
console.error('User ID not found in session metadata');
}
}
return NextResponse.json({ received: true });
} catch (err: any) {
console.error('Error:', err.message);
return NextResponse.json({ error: err.message }, { status: 400 });
}
}
我的项目建设: 我的项目建设 条纹问题: 条纹问题 另外,github链接可以更好地理解: https://github.com/NatigAgarzayev/chatti
我尝试将 api/webhook 放入忽略的路由,但它对我不起作用。 付款成功,但没有向店员发送信息。 我检查了所有密钥,它们都是正确的。
看起来 Stripe 发送到您服务器的 Webhook 事件失败并返回 404,这意味着您的服务器无法正确提供
https://chatti-jade.vercel.app/api/webhooks
。
您需要首先调试您的 webhook 端点,即。将自己卷曲到
https://chatti-jade.vercel.app/api/webhooks
以确保它返回 200 或 400,这样您就知道 api/webhooks/route.ts
中的代码实际正在运行。