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

Add NextJS webhook sample #1683

Merged
merged 6 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions examples/webhook-signing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Verify the events that Stripe sends to your webhook endpoints. Additional detail
Available examples:
- [`express`](./express) - Express 4
- [`koa`](./koa) - Koa 2
- [`nextjs`](./nextjs) - NextJS 13

### Requirements

Expand Down
3 changes: 2 additions & 1 deletion examples/webhook-signing/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@types/koa": "^2.13.5",
"@types/koa-bodyparser": "^4.3.10",
"@types/node": "^13.1.4",
"typescript": "^4.8.3"
"typescript": "^4.8.3",
"ts-node": "^10.9.1"
}
}
1 change: 1 addition & 0 deletions examples/webhook-signing/nextjs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.next
17 changes: 17 additions & 0 deletions examples/webhook-signing/nextjs/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env -S npm run-script run

/*
ATTENTION: this file exists to support github/stripe/stripe-node example test infrastructure
You don't need to copy this file to your NextJS project.
*/

import child_process from 'child_process';

const process = child_process.exec('npm run dev --verbose');
process.stdout.on('data', (line) => {
const match = /url: (.*)/gm.exec(line);
if (match) {
console.log(`Webhook endpoint available at ${match[1]}/api/webhooks`);
}
console.log(line);
});
5 changes: 5 additions & 0 deletions examples/webhook-signing/nextjs/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
28 changes: 28 additions & 0 deletions examples/webhook-signing/nextjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "webhook-signing-example-nextjs",
"version": "1.0.0",
"description": "NextJS webhook parsing sample",
"repository": {},
"main": "./main.ts",
"scripts": {
"run": "ts-node-transpile-only ./main.ts",
"prepare": "../prepare.sh",
"dev": "next dev --port 0"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"next": "^13.1.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"stripe": "^11.9.1"
},
"devDependencies": {
"@types/node": "^13.1.4",
"@types/react": "18.0.27",
"eslint": "^8.33.0",
"typescript": "^4.8.3",
"ts-node": "^10.9.1"
}
}
74 changes: 74 additions & 0 deletions examples/webhook-signing/nextjs/pages/api/webhooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Stripe from 'stripe';
import {NextApiRequest, NextApiResponse} from 'next';

const handler = async (
req: NextApiRequest,
res: NextApiResponse
): Promise<void> => {
const stripe = new Stripe(process.env.STRIPE_WEBHOOK_SECRET, {
apiVersion: '2022-11-15',
});

const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET;

if (req.method === 'POST') {
const sig = req.headers['stripe-signature'];

let event: Stripe.Event;

try {
const body = await buffer(req);
event = stripe.webhooks.constructEvent(body, 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);

// 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
res.json({received: true});
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
};

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

const buffer = (req: NextApiRequest) => {
return new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];

req.on('data', (chunk: Buffer) => {
chunks.push(chunk);
});

req.on('end', () => {
resolve(Buffer.concat(chunks));
});

req.on('error', reject);
});
};

export default handler;
4 changes: 3 additions & 1 deletion test/Integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as childProcess from 'child_process';
const testUtils = require('../testUtils');

describe('Integration test', function() {
this.timeout(30000);
this.timeout(50000);
pakrym-stripe marked this conversation as resolved.
Show resolved Hide resolved
const testExec = (cmd: string): Promise<void> => {
const child = childProcess.exec(cmd);

Expand Down Expand Up @@ -89,4 +89,6 @@ describe('Integration test', function() {
it('Webhook sample express', () => runWebhookTest('express'));

it('Webhook sample koa', () => runWebhookTest('koa'));

it('Webhook sample nextjs', () => runWebhookTest('nextjs'));
});