#Track payment status
1 messages · Page 1 of 1 (latest)
To track the payment status in Stripe Checkout with a Next.js application, you can use Stripe Webhooks. Webhook events allow you to get notified about events that happen on your Stripe account. This is especially useful for asynchronous payments, subscriptions with Stripe Billing, or building a marketplace with Stripe Connect.
Here's how you can set it up:
- By default, Next.js API routes are same-origin only. To allow Stripe webhook event requests to reach your API route, add
micro-cors:
// Partial of ./pages/api/webhooks/index.ts
import Cors from 'micro-cors';
const cors = Cors({ allowMethods: ['POST', 'HEAD'],});
// ...
export default cors(webhookHandler as any);
- To make sure that a webhook event was sent by Stripe, not by a malicious third party, you need to verify the webhook event signature:
// Partial of ./pages/api/webhooks/index.ts
// ...
const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET!
// Stripe requires the raw body to construct the event.
export const config = { api: { bodyParser: false, },}
const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const buf = await buffer(req)
const sig = req.headers['stripe-signature']!
let event: Stripe.Event
try {
event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret)
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`)
res.status(400).send(`Webhook Error: ${err.message}`)
return
}
// Successfully constructed event
console.log('✅ Success:', event.id)
// ...
This way your API route is able to receive POST requests from Stripe but also makes sure, only requests sent by Stripe are being processed.
For more information, you can refer to the Getting started with Next.js, TypeScript, and Stripe Checkout guide (https://vercel.com/guides/getting-started-with-nextjs-typescript-stripe) on the Vercel website.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@versed bear kapa.ai is still learning and improving, please let us know how it did by reacting below