DEV Community

Cover image for Paystack Integration Series 2: How to Verify Payments with Webhooks and Handle Idempotency
Gloria Tejuosho
Gloria Tejuosho

Posted on Edited on

Paystack Integration Series 2: How to Verify Payments with Webhooks and Handle Idempotency

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
}
Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Step 3: Navigate to VS Code to start your app.

npm run start
Enter fullscreen mode Exit fullscreen mode

Step 4: Open PowerShell and run this command to get a temporary URL.

cloudflared tunnel --url http://localhost:5000
Enter fullscreen mode Exit fullscreen mode

You should receive a random URL.

Cloudflare 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
Enter fullscreen mode Exit fullscreen mode

Paystack webhook setup page

Step 7: Click the “Save Changes" button to save your changes.
Step 8: Test the initiate payment route in Postman and complete the payment.

Paystack checkout url

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
}
Enter fullscreen mode Exit fullscreen mode

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);
       }
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
   }
Enter fullscreen mode Exit fullscreen mode

Step 5: Import update-database.js at the top of your webhook.js file and call the updateDatabase function.

       await updateDatabase(reference, amount, status)
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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.

Webhook site url

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.

webhook event payload

Step 5: Add a new request in your Postman collections and paste your local webhook URL.

I.e.,

http://localhost:5000/webhook
Enter fullscreen mode Exit fullscreen mode

Step 6: Navigate to webhook.site and copy the Paystack x-paystack-signature.

Paystack signature

Step 7: Open Postman and paste the Paystack webhook signature under the “Headers” tab.

Webhook signature

Step 8: Navigate to webhook.site and copy the webhook event payload.

Webhook body

Step 9: Open Postman and paste the webhook event payload under the “body” tab.

test event

Step 10: Click the “Send” button to send your request.
You should receive a 200 OK response.

Step 11: Click the “Send” button to resend the request.

Postman still returns a 200 OK response. Check your terminal, where you should receive a “Transaction with reference has already been processed” message.

transaction already processed

Test Database Idempotency When Multiple Events Fire at the Same Time

You have implemented the database idempotency logic. However, you need to confirm that the database updates only once, even if Paystack sends webhooks multiple times at the same time.
For example, if Paystack sends 3 webhooks at once, the database should update once and ignore the remaining two webhooks.
That is exactly what you want to test in this section.

Step 1: Create a separate test-simulation.js file in your project folder.

Note: This is a standalone file in your project folder.

Step 2: Use the Promise.allSettled() method to send multiple webhooks concurrently, i.e., at the same time.

import 'dotenv/config'

import crypto from 'crypto'
import axios from 'axios'

const secret = process.env.PAYSTACK_SECRET

const payload = {}
const body = JSON.stringify(payload)
const signature = crypto.createHmac('sha512', secret).update(body).digest('hex')

const sendWebhook = () =>
  axios.post('http://localhost:5000/webhook', payload, {
    headers: {
      'Content-Type': 'application/json',
      'x-paystack-signature': signature,
    }
  })

// fire the three at the same time, not one after another
await Promise.allSettled([sendWebhook(), sendWebhook(), sendWebhook()])
Enter fullscreen mode Exit fullscreen mode

Secret: Retrieves your Paystack API key.
payload: This will hold the webhook payload.
body: Stringifies the webhook payload.
signature: Creates a Paystack webhook signature using the ‘sha512’ algorithm, your Paystack API key, and the webhook payload.
sendWebhook: Sends the webhook payload to your webhook URL.
results: Sends the webhook payload three times concurrently.

Step 3: Initiate a new transaction in Postman.

Step 4: Copy the webhook payload (i.e., body) from webhook.site.

Step 5: Paste the webhook payload into the empty payload variable in your test-simulation.js file.

Note: Ensure you remove the empty curly braces and paste the webhook payload directly.

Step 6: Split your terminal.

Note:To split your terminal, click the three dots next to the “Run” option at the top of VS Code, > ”Terminal” > “Split Terminal."

Split terminal

Step 7: Enter npm run start in your first terminal.

Step 8: Enter node test-simulation.js to run the test script in the second terminal.

This sends three webhook events at the same time. If the database idempotency logic works as expected, it should process one request and ignore the remaining two requests. You should see two “Transaction with reference has already been processed” messages in your terminal.

Note: If you run the test on a transaction that has already been updated, you will receive three “Transaction with reference has already been processed” messages in your terminal.

terminal displaying outcome after firing same event multiple times

Now, even if Paystack delivers the same webhook event multiple times, your database idempotency logic ensures your database updates once and ignores other webhooks.

Troubleshooting Common Issues

1. The Paystack event does not fire when a payment succeeds.
Fix: If you are using a Cloudflare temporary URL, ensure the tunnel is still running. Otherwise, confirm that you have configured the correct URL in your Paystack dashboard.

Next Step

Check the next series to handle pending, abandoned, and expired transactions using the Paystack Verify API

Top comments (1)

Collapse
 
krusenas profile image
Karolis •

The check that stops a transaction being updated twice doesn't cover deploys. A charge.success lands on the instance you're shutting down, the write never commits, and Paystack's retry is the only thing that saves it. Usually fine, but worth treating the retry as real rather than a duplicate to ignore. I built Webhook Relay around that. It stores every hit and retries failed deliveries.