Integrating Paystack in Next.js
Accepting payments online in Nigeria and Africa is seamlessly handled by Paystack. In this guide, we will look at how to integrate the Paystack Checkout API into a modern Next.js application.
Prerequisites
- A Paystack account (Test or Live keys)
- A Next.js project setup
Step 1: Install the Paystack React Library
We will use the official react-paystack library which makes integration very straightforward.
npm install react-paystack
Step 2: Create a Checkout Component
Create a new file components/PaystackCheckout.js and add the following code:
import React from 'react';
import { usePaystackPayment } from 'react-paystack';
const config = {
reference: (new Date()).getTime().toString(),
email: "user@example.com",
amount: 20000 * 100, // Amount in kobo
publicKey: process.env.NEXT_PUBLIC_PAYSTACK_PUBLIC_KEY,
};
const PaystackHookExample = () => {
const initializePayment = usePaystackPayment(config);
return (
<div>
<button onClick={() => {
initializePayment(
(reference) => console.log('Payment successful', reference),
() => console.log('Payment closed')
)
}}>
Pay ₦20,000
</button>
</div>
);
};
export default PaystackHookExample;
Step 3: Handling Webhooks
Always remember that client-side verification is not enough. You must set up a secure webhook endpoint to receive server-to-server confirmation from Paystack.
Create an API route at pages/api/paystack-webhook.js:
import crypto from 'crypto';
export default function handler(req, res) {
const hash = crypto.createHmac('sha512', process.env.PAYSTACK_SECRET_KEY).update(JSON.stringify(req.body)).digest('hex');
if (hash == req.headers['x-paystack-signature']) {
const event = req.body;
if(event.event === 'charge.success') {
// Fulfill the value to the customer
}
}
res.status(200).send('Webhook received');
}
Conclusion
Integrating Paystack in Next.js is fast and secure when using the React library alongside a reliable webhook backend. Happy building!
Ready to start building?
Explore the most comprehensive directory of APIs for Nigerian developers and find exactly what you need.
Browse the API Directory