Skip to content

Commit

Permalink
Add the start of a webhook handler (#210)
Browse files Browse the repository at this point in the history
* Add the start of a webhook handler

* fix handler

* Apply suggestions from code review

Co-authored-by: Jorge Aguirre Gonzalez <[email protected]>
Signed-off-by: Chris Streeter <[email protected]>

---------

Signed-off-by: Chris Streeter <[email protected]>
Co-authored-by: Jorge Aguirre Gonzalez <[email protected]>
  • Loading branch information
streeter-stripe and jorgea-stripe authored Jan 7, 2025
1 parent 0e96d6d commit 8fa34a5
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Get your Stripe keys from https://stripe.com/docs/keys
STRIPE_SECRET_KEY="sk_INSERT_YOUR_SECRET_KEY"
STRIPE_PUBLIC_KEY="pk_INSERT_YOUR_PUBLISHABLE_KEY"
STRIPE_WEBHOOK_SECRET="whsec_INSERT_YOUR_WEBHOOK_SECRET"

NEXT_PUBLIC_STRIPE_PUBLIC_KEY=$STRIPE_PUBLIC_KEY

Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,15 @@ yarn dev
```

Go to `http://localhost:{process.env.PORT}` in your browser to start using the app.

To test events sent to your event handler, you can run this command in a separate terminal:

```
stripe listen --forward-to localhost:3000/api/webhooks
```

Then, trigger a test event with:

```
stripe trigger payment_intent.succeeded
```
48 changes: 48 additions & 0 deletions app/api/webhooks/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {type NextRequest} from 'next/server';
import {NextResponse} from 'next/server';
import {stripe} from '@/lib/stripe';

export async function POST(req: NextRequest) {
const body = await req.text();

const sig = req.headers.get('stripe-signature');
if (!sig) {
return NextResponse.json(
{error: 'Cannot find the webhook signature'},
{status: 400}
);
}

const secret = process.env.STRIPE_WEBHOOK_SECRET;
if (!secret) {
return NextResponse.json(
{error: 'Cannot find the webhook secret'},
{status: 400}
);
}

let event;
try {
event = stripe.webhooks.constructEvent(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET || ''
);
} catch (err: any) {
return NextResponse.json(
{error: `Webhook Error: ${err.message}`},
{status: 400}
);
}

// Handle events - see full event list: https://docs.stripe.com/api/events/types
switch (event.type) {
case 'account.updated':
break;
default:
console.log('Unhandled event type', event.type);
break;
}

return NextResponse.json({});
}

0 comments on commit 8fa34a5

Please sign in to comment.