Welcome folks today in this blog post we will be integrating the stripe webhooks
in node.js and express for the payment checkout
event in command line. All the full source code of the application is shown below.
Get Started
In order to get started you need to first of all download the stripe cli
inside your local machine by executing the below commands as shown below
https://github.com/stripe/stripe-cli/releases/latest
And now you need to extract
the content from the file and move the exe
file into the working
directory
And now after that you need to make a new node.js
project using the below command
npm init -y
npm i express stripe
Now you will see the below directory
structure of the node.js app as shown below
And now we need to make the index.js
file of the express app and copy paste the below code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 |
const stripe = require("stripe")("##secretkey##"); const express = require('express') const bodyparser = require('body-parser') const app = express() app.listen(5000, () => { console.log("App is listening on port 5000") }) |
Here you need to copy paste your own secret key
from the stripe dashboard as shown below
Now we need to execute the below commands to login
in the stripe account and make the hook
inside the stripe
stripe login
This will login into your stripe account automatically.
And now we need to create the webhook
for our endpoint which is localhost:5000
it can be done as shown below
stripe listen --forward-to=http://localhost:5000/hooks
Now after you execute this command
you will get your signing secret
as shown below
And now you need to make the post
request inside the index.js
file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
app.post('/hooks',bodyparser.raw({type:'application/json'}),async(req, res) => { const payload = req.body const sig = req.headers['stripe-signature'] const endpointsecret = "##endpointsecret##"; let event; try { event = stripe.webhooks.constructEvent(payload,sig,endpointsecret) } catch (error) { console.log(error.message) res.status(400).json({ success: false }) return; } console.log(event.type) console.log(event.data.object) console.log(event.data.object.id) res.json({ success:true }) }) |
And now we need to trigger
the event where the payment
checkout takes place by the customer and for this we can execute the below command as shown below
stripe trigger customer.created
Now if you execute the command after you start the application by executing the command
nodemon index.js
So you can see the customer
object will be created automatically when the payment checkout
event takes place.