Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Next.js App Router example for Webhook signing #2245

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions examples/webhook-signing/nextjs/app/api/webhooks/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Stripe from 'stripe';
import {NextRequest} from 'next/server';

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

export async function POST(req: NextRequest) {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const sig = req.headers.get('stripe-signature');
const wh_sec = process.env.STRIPE_WEBHOOK_SECRET;
let event: Stripe.Event;
if (!sig) {
throw new Error('Invalid Signature');
}
try {
const body = Uint8Array.from(await buffer(req)) as Buffer<ArrayBufferLike>;
event = stripe.webhooks.constructEvent(body, sig!, wh_sec);
} catch (err) {
console.log(`❌ Error message: ${err.message}`);
return new Response(`Webhook Error: ${err.message}`, {status: 400});
}
console.log('✅ Success:', event.id);

// Cast event data to Stripe object
if (event.type === 'payment_intent.succeeded') {
const stripeObject: Stripe.PaymentIntent = event.data
.object as Stripe.PaymentIntent;
console.log(`💰 PaymentIntent status: ${stripeObject.status}`);
} else if (event.type === 'charge.succeeded') {
const charge = event.data.object as Stripe.Charge;
console.log(`💵 Charge id: ${charge.id}`);
} else {
console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`);
}

// Return a response to acknowledge receipt of the event
return Response.json({received: true}, {status: 200});
}

const buffer = async (req: NextRequest) => {
const body = req.body;
if (!body) {
throw new Error('Request body is null');
}
const reader = body.getReader();
const chunks = [];
let done, value;
while ((({done, value} = await reader.read()), !done)) {
chunks.push(value);
}
const buf = new Uint8Array(
chunks.reduce((acc, chunk) => acc + chunk.length, 0)
);
let offset = 0;
for (const chunk of chunks) {
buf.set(chunk, offset);
offset += chunk.length;
}
return buf;
};
Loading