Skip to content

Instantly share code, notes, and snippets.

@darul75
Last active April 14, 2021 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darul75/ace5cae198b693ca80678b5a3bc3ea5b to your computer and use it in GitHub Desktop.
Save darul75/ace5cae198b693ca80678b5a3bc3ea5b to your computer and use it in GitHub Desktop.
stripe_webhook.js
const app = require('express')();
/*
Instructions:
1) run your node server
--command to run--
> node stripe_webhook.js
2) tunnelling traffic
---docs--
https://stripe.com/docs/cli/listen
https://stripe.com/docs/stripe-cli/webhooks#forward-events
--command to run--
> stripe listen --forward-to http://localhost:8000/webhook
3) submit test stripe events
---docs--
https://stripe.com/docs/cli/trigger
--command to run--
> stripe trigger charge.failed
> stripe trigger charge.dispute.created
> stripe trigger customer.subscription.created
Make sure to only subscribing to necessary events by connecting to your Stripe account
and navigate into the Developers>Webhooks section
*/
const bodyParser = require('body-parser');
const setupForStripeWebhooks = {
verify: function (req, _, buf) {
var url = req.originalUrl;
if (url.startsWith('/webhook')) {
req.rawBody = buf.toString();
}
}
};
app.use(bodyParser.json(setupForStripeWebhooks));
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
const event = request.body;
// NOTE:
// please ensure to put some asychronous non blocking logic so this method
// returns quickly and Stripe backend can aknowledge this event has
// been consumed, avoiding multiple retries.
switch (event.type) {
case 'charge.failed':
const charge = event.data.object;
console.log('charge.failed');
// Then define and call a method to handle the failed charge.
// handlePaymentChargeFailed(charge);
break;
case 'charge.dispute.created':
const chargeDispute = event.data.object;
console.log('charge.dispute.created');
break;
case 'customer.subscription.created':
const customerSubCreated = event.data.object;
console.log('customer.subscription.created');
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a response to acknowledge receipt of the event
response.json({received: true});
});
app.listen(8000, () => console.log('Running on port 8000'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment