In the first series, you learned how to accept payments using the Paystack initialize API and record every transaction in your database. Next, verify every payment you receive via webhooks before you deliver value.
Webhooks let you receive instant notifications from Paystack when an event happens; in this case, charge.success, which fires when the customer completes the payment successfully.
However, to ensure the webhook event you receive is genuinely from Paystack, you have to verify it. Anyone can send a webhook event, so you must confirm that every webhook you receive is from Paystack before delivering value to customers after they make payments.
Verify Paystack Webhook Signature
Step 1: Create a new webhook.js file in your controller folder.
Step 2: Create a webhook function that verifies the webhook signature.
Side Note: The code below verifies Paystack events using its legacy webhook signature header,
x-paystack-signature. If your event carries the new Paystack signature, i.e.,Paystack-Signature, check the official Paystack documentation to learn how to verify it.
import crypto from 'crypto' import 'dotenv/config' const webhook = async (req, res)=>{ const secret = process.env.PAYSTACK_SECRET const event = req.body; const headers = req.headers['x-paystack-signature'] const signature = crypto.createHmac('sha512', secret).update(JSON.stringify(event)).digest('hex'); if(signature !== headers){ return res.status(401).json({ success: false, data: { msg: "Invalid signature!" } }) } res.sendStatus(200) if(event.event !== "charge.success"){ return; } console.log("Event is genuinely from Paystack"); } export{ webhook } In the webhook function:
Secret: Holds your Paystack API key.
Event: Retrieves the Paystack webhook payload via req.body. This payload provides all the necessary information about a successful payment, including the status, amount, reference, email, and more.
Headers: This retrieves the Paystack webhook signature from the request header.
Signature: This manually constructs the Paystack webhook signature using Sha512, your secret key, and the event payload. This is exactly how Paystack creates every webhook signature it sends.
Then it compares your manually constructed signature with the one Paystack sends. If it does not match, it rejects it. Otherwise, it sends a 200 response to acknowledge the event.
The second if block ignores the event if it is not charge.success.
Step 3: Update the transaction status in your database immediately after verifying that the charge.success webhook event is genuinely from Paystack.
import crypto from 'crypto' import { paymentInitiationModel } from '../model/payment-initiation.js' // import transaction model import 'dotenv/config' const webhook = async (req, res)=>{ const secret = process.env.PAYSTACK_SECRET const event = req.body; const headers = req.headers['x-paystack-signature'] const signature = crypto.createHmac('sha512', secret).update(JSON.stringify(event)).digest('hex'); if(signature !== headers){ return res.status(401).json({ success: false, data: { msg: "Invalid signature!" } }) } res.sendStatus(200) // acknowledges the event if(event.event !== "charge.success"){ return; } // update database const amount = event.data.amount const status = event.data.status const updatedAt = Date.now(); const reference = event.data.reference try { const getTransaction = await paymentInitiationModel.findOne({reference}) if(!getTransaction){ throw new Error(`Transaction not found ${reference}!`) } if(getTransaction.amount * 100 !== amount ){ console.log(`Amount mismatch for ${reference}`); return; } const updateStatus = await paymentInitiationModel.findOneAndUpdate( {reference: reference}, {$set: {status: status, updatedAt: updatedAt}}, {returnDocument: "after"} ) } catch (error) { console.log('Webhook processing failed', reference, error); } } export{ webhook } After acknowledging the event:
Amount: Retrieves the transaction amount from the event payload.
Status: Retrieves the transaction status from the event payload.
updatedAt: Gets the current time.
Reference: Retrieves the transaction reference from the payload.
getTransaction: Finds the transaction reference in your database. If the transaction reference is not found in your database, the first if statement catches it and throws a “Transaction not found" error.
If the amount in the event payload does not match the amount stored in your database (100 converts it to Kobo), the second if statement catches it and logs an “Amount mismatch” error.
updateStatus: Retrieves the transaction you want to update by its reference, updates its status from pending to success, and updates the updatedAt property, indicating the last time the document was updated.
The catch blocks run if you are unable to process the webhook.
Set Up Webhook Route
Step 1: Create a webhook.js file in your Route folder to set up your webhook route.
import express from 'express' import { webhook } from '../controller/webhook.js'; const webhookRoute = express.Router(); webhookRoute.post('/webhook', webhook); export { webhookRoute } Step 2: Import webhook routes in your index.js file.
import express from 'express' import 'dotenv/config' import { initiatePaymentRoute } from './route/initiate-payment-route.js'; import {connectString} from './database/connectString.js' import { webhookRoute } from './route/webhook.js'; //imports the webhook route const app = express(); app.use(express.json()) app.use('/api/v1',initiatePaymentRoute) app.use('/', webhookRoute); // constructs the webhook route url const PORT = process.env.PORT || 5000 const start = async ()=>{ await connectString(process.env.MONGOURI) app.listen(PORT,()=>{ console.log('Server is running...'); }) } start(); Receive Webhook Events From Paystack
To receive webhook events from Paystack, your webhook routes (URL) must be publicly available. One fast workaround is to set up a temporary public URL using a Cloudflare Tunnel and add it to your Paystack dashboard.
Note: You must replace the temporary Cloudflare URL with a stable one once you are ready to go live.
Step 1: Open PowerShell and run this command to install cloudflared.
winget install --id Cloudflare.cloudflared --source winget If everything works as expected, you should receive a success message
Step 2: Run this command to confirm Cloudflared has been installed successfully.
You should see the Cloudflared version.
cloudflared --version Step 3: Navigate to VS Code to start your app.
npm run start Step 4: Open PowerShell and run this command to get a temporary URL.
cloudflared tunnel --url http://localhost:5000 You should receive a random URL.
Step 5: Log in to your Paystack dashboard and navigate to “Settings” > “API Keys & Webhooks” and paste the URL.
Step 6: Add the webhook path to the URL.
For example:
https://fiction-sell-goat-equivalent.trycloudflare.com/webhook Step 7: Click the “Save Changes" button to save your changes.
Step 8: Test the initiate payment route in Postman and complete the payment.
You should receive the webhook event in your terminal, and the transaction status should automatically be updated to success in your database.
Step 9: Open your database and check the status of the transaction you initiated.
If the flow works as expected, the status should be success, and updatedAt should show the last time it was updated.
Refactor the Webhook Controller
Your current webhook logic works as expected. Immediately after Paystack sends an event when a customer completes a payment, you verify it and update the transaction status in the database from "pending" to "success." However, this approach has issues.
First, the webhook controller is doing a lot of work. It verifies the webhook signature, acknowledges the event, and processes it to update the database.
The second issue is this: if Paystack sends charge.success events three times for the same transaction, the database will update three times even if the transaction status is the same.
To fix this, move the database update logic out of the controller and create a update-database service to handle it. Then make the database update idempotent, i.e., update the database once even if Paystack sends a webhook event multiple times.
Separate Database Update Logic and Make it Idempotent
Step 1: Create an update-database.js file in your existing Service folder.
Step 2: Create an updateDatabase function inside the file and use the reference parameter to find the specific transaction you want to update in the database. Then throw an error if the transaction has already been processed.
I.e., if a transaction status has already been updated from “pending” to “success” status, then it should throw an error if you try updating it again when a webhook event fires multiple times.
import { paymentInitiationModel } from "../model/payment-initiation.js" // imports the database model const updateDatabase = async (reference, amount, status)=>{ try { const findTransaction = await paymentInitiationModel.findOne({ reference: reference }); if(!findTransaction){ throw new Error(`Transaction not found ${reference}!`) } if(findTransaction.status=="success"){ throw new Error(`Transaction with reference:${reference} has already been processed.`) } if(amount !== findTransaction.amount * 100){ // amount in kobo throw new Error(`Amount mismatch for ${reference}`) } } catch (error) { console.log(` ${error.message}`); } } export { updateDatabase } In this code:
findTransaction: Retrieves the transaction you want to update.
The first if statement: Checks whether the transaction exists. If it does not, it throws a “Transaction not found.”
The second if statement: Checks whether the transaction status has been updated to success. If yes, it throws an error to avoid updating the status again.
The third if statement: Checks whether the amount stored in the database matches the webhook amount. If it does not, it throws an “Amount mismatch” error message.
Step 3: Update a transaction only when its current status is “pending.”
try { const updatedAt = Date.now() const updateTransactionStatus = await paymentInitiationModel.findOneAndUpdate( {reference, status: "pending"}, {$set: {status: status, updatedAt: updatedAt}}, {returnDocument:"after"} ) if(!updateTransactionStatus){ console.log(`Transaction with reference:${reference} has already been processed.`) } } catch (error) { console.log('Could not update transaction status', reference, error); } In this code,
updatedAt: Gets the current time.
updateTransactionStatus: Finds the transaction you want to update using the reference parameter and ensures its current status is pending. Then it updates the transaction status from pending to the latest webhook event status and updates the updatedAt field.
findOneAndUpdate returns null when no pending transaction matches. The if block catches this, which handles multiple webhooks that arrive at the same time.
Your update-database.js file should look like this:
import { paymentInitiationModel } from "../model/payment-initiation.js" // imports the database model const updateDatabase = async (reference, amount, status)=>{ try { const findTransaction = await paymentInitiationModel.findOne({ reference: reference }); if(!findTransaction){ throw new Error(`Transaction not found ${reference}!`) } if(findTransaction.status=="success"){ throw new Error(`Transaction with reference:${reference} has already been processed.`) } if(amount !== findTransaction.amount * 100){ // amount in kobo throw new Error(`Amount mismatch for ${reference}`) } try { const updatedAt = Date.now() const updateTransactionStatus = await paymentInitiationModel.findOneAndUpdate( {reference, status: "pending"}, {$set: {status: status, updatedAt: updatedAt}}, {returnDocument:"after"} ) if(!updateTransactionStatus){ console.log(`Transaction with reference:${reference} has already been processed.`) } } catch (error) { console.log('Could not update transaction status', reference, error); } } catch (error) { console.log(` ${error.message}`); } } export { updateDatabase } Step 4: Navigate to your webhook.js file and remove the line of code updating the database.
i.e.,
try { const getTransaction = await paymentInitiationModel.findOne({reference}) if(!getTransaction){ throw new Error(`Transaction not found ${reference}!`) } if(getTransaction.amount * 100 !== amount ){ console.log(`Amount mismatch for ${reference}`); return; } const updateStatus = await paymentInitiationModel.findOneAndUpdate( {reference: reference}, {$set: {status: status, updatedAt: updatedAt}}, {returnDocument: "after"} ) } catch (error) { console.log('Webhook processing failed', reference, error); } Step 5: Import update-database.js at the top of your webhook.js file and call the updateDatabase function.
await updateDatabase(reference, amount, status) This calls the updateDatabase function and passes the webhook event reference, amount, and status as parameters.
Your webhook.js file should look like this:
import crypto from 'crypto' import { updateDatabase } from '../service/update-database.js' import 'dotenv/config' const webhook = async (req, res)=>{ const secret = process.env.PAYSTACK_SECRET const event = req.body; const headers = req.headers['x-paystack-signature'] const signature = crypto.createHmac('sha512', secret).update(JSON.stringify(event)).digest('hex'); if(signature !== headers){ return res.status(401).json({ success: false, data: { msg: "Invalid signature!" } }) } res.sendStatus(200) // acknowledges the event if(event.event !== "charge.success"){ return; } // update database const amount = event.data.amount const status = event.data.status const reference = event.data.reference await updateDatabase(reference, amount, status) } export{ webhook } Now, the database update logic is handled separately in a different file. Only a transaction with “pending” status can be updated, so even if Paystack sends the same charge.success event multiple times or sends several at the same time, the database updates once.
Step 6: Initiate a new transaction to test the flow.
If everything works as expected, the transaction status should update from “pending” to “success.”
Note: To receive the Paystack webhook event, ensure your Cloudflare tunnel is still running.
Verify Database Update Logic and Idempotency
To confirm the database update logic works as expected and updates once, you need to send the same webhook event multiple times. Paystack usually sends the event only once, so you have to send it manually instead; i.e., use webhook.site to receive the event, which keeps your transaction pending because your app never processes it. Then send the same event (signature and payload) to your local webhook URL in Postman.
Step 1: Navigate to Webhook.site. This tool allows you to create random URLs to receive webhook events.
Step 2: Copy one of the URLs.
Step 3: Add this URL to your [Paystack dashboard (https://dashboard.paystack.com/).
“Settings”> “API Keys & Webhooks"
Step 4: Initiate a new transaction in Postman.
You should receive an instant webhook event in the webhook.site tool once you complete the payment.
Step 5: Add a new request in your Postman collections and paste your local webhook URL.
I.e.,
http://localhost:5000/webhook Step 6: Navigate to webhook.site and copy the Paysta...





