react-payhere
v1.0.2
Published
  
Readme
react-payhere
A lightweight, easy-to-use React & Next.js wrapper for PayHere payments, supporting sandbox and live modes.
✨ Features
- ⚡ Simple integration for React and Next.js
- 🧪 Sandbox and live mode support
- 💎 TypeScript-ready with type safety
- 🖤 Minimal and lightweight
- 🔄 Fully customizable payment event callbacks
🚀 Installation
# npm
npm install react-payhere
# yarn
yarn add react-payhere
# pnpm
pnpm add react-payhere
1️⃣ Project Setup
First, create a new Next.js 15 project with TypeScript:
npx create-next-app@latest react-payhere-next15 --typescript
cd react-payhere-next15
npm install react-payhere
2️⃣ Environment Variables
Create a .env.local file in the root of your project:
NEXT_PUBLIC_PAYHERE_MERCHANT_ID=your_merchant_id
PAYHERE_MERCHANT_SECRET=your_merchant_secret
NEXT_PUBLIC_PAYHERE_MERCHANT_ID: Public merchant ID for frontend use.
PAYHERE_MERCHANT_SECRET: Private merchant secret for backend verification.
3️⃣ Frontend Integration
app/layout.tsx
Wrap your application with PayHereProvider to provide the PayHere context:
// app/layout.tsx
import { PayHereProvider } from 'react-payhere';
export default function RootLayout({ children }: { children: React.ReactNode }) {
const payHereConfig = {
merchant_id: process.env.NEXT_PUBLIC_PAYHERE_MERCHANT_ID!,
return_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
notify_url: 'http://localhost:3000/api/payhere-notify',
};
return (
<html lang="en">
<body>
<PayHereProvider config={payHereConfig} mode="sandbox">
{children}
</PayHereProvider>
</body>
</html>
);
}
app/checkout/page.tsx
Implement the PayHereButton component to initiate the payment process:
// app/checkout/page.tsx
'use client';
import { PayHereButton } from 'react-payhere';
const payment = {
order_id: 'ORDER123',
items: 'Premium Tee',
currency: 'LKR',
amount: '2500.00',
first_name: 'John',
last_name: 'Doe',
email: '[email protected]',
phone: '0771234567',
address: 'Colombo',
city: 'Colombo',
country: 'Sri Lanka',
};
export default function CheckoutPage() {
return (
<div style={{ padding: '2rem' }}>
<h1>Checkout</h1>
<PayHereButton
payment={payment}
label="Pay Now (Sandbox)"
events={{
onCompleted: (id) => console.log('Payment Completed:', id),
onDismissed: () => console.log('Payment Dismissed'),
onError: (err) => console.error('Payment Error:', err),
}}
/>
</div>
);
}
4️⃣ Backend Payment Verification
app/api/payhere-notify/route.ts
Create an API route to handle the payment notification and verify the payment using the merchant secret:
// app/api/payhere-notify/route.ts
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
const MERCHANT_SECRET = process.env.PAYHERE_MERCHANT_SECRET!;
export async function POST(req: NextRequest) {
const body = await req.json();
const { merchant_id, order_id, amount, currency, status_code, md5sig } = body;
const hash = crypto
.createHash('md5')
.update(`${merchant_id}${order_id}${amount}${currency}${status_code}${MERCHANT_SECRET}`)
.digest('hex');
if (hash === md5sig) {
console.log('Payment verified:', order_id);
return NextResponse.json('OK');
} else {
console.error('Invalid payment:', order_id);
return NextResponse.json('Invalid payment', { status: 400 });
}
}
5️⃣ Success and Cancel Pages
app/success/page.tsx
// app/success/page.tsx
export default function SuccessPage() {
return <h1>Payment Successful! ✅</h1>;
}
app/cancel/page.tsx
// app/cancel/page.tsx
export default function CancelPage() {
return <h1>Payment Cancelled ❌</h1>;
}
6️⃣ Running the Application
Start your development server:
npm run dev
Navigate to http://localhost:3000/checkout to test the integration.