Pages

Wednesday, April 2, 2025

Integrating PayHere Payment Gateway in PHP

How to Integrate PayHere Payment Gateway in PHP - Complete Guide

How to Integrate PayHere Payment Gateway in PHP – Complete Guide

PayHere is one of Sri Lanka's most popular payment gateways, offering seamless online payment solutions for businesses. If you're running an e-commerce store, SaaS platform, or any web application that requires payments, integrating PayHere can help you accept credit/debit cards, bank transfers, and mobile wallets securely.

In this step-by-step guide, we'll cover:

  1. PayHere Payment Gateway Overview
  2. Prerequisites for Integration
  3. Setting Up PayHere Sandbox Account
  4. PHP Integration Code (Complete Working Example)
  5. Handling Payment Notifications (IPN)
  6. Testing & Going Live
  7. Common Issues & Troubleshooting
Note: This guide assumes you have basic knowledge of PHP and web development concepts.

1. PayHere Payment Gateway Overview

PayHere supports:

  • One-time payments
  • Recurring/subscription payments
  • Mobile and online banking
  • Visa/Mastercard payments
  • Real-time payment notifications

It's widely used in Sri Lanka and is ideal for businesses looking for a local, secure, and easy-to-integrate payment solution.

2. Prerequisites for Integration

Before integrating PayHere, ensure you have:

  • A PayHere merchant account (Sign up here)
  • A web server with PHP (PHP 7.0+ recommended)
  • SSL certificate (HTTPS required for security)
  • Basic knowledge of PHP and HTML
Important: PayHere requires all transactions to be conducted over HTTPS. Make sure your website has SSL installed before proceeding.

3. Setting Up PayHere Sandbox Account

Before going live, test your integration in sandbox mode:

  1. Go to PayHere Developer Dashboard
  2. Register for a sandbox merchant account
  3. Get your Merchant ID and Merchant Secret (keep these secure!)

4. PHP Integration Code (Complete Working Example)

Here's a full implementation of PayHere in PHP:

Step 1: Create the Payment Form (payment.php)

<?php
// PayHere Configuration
$merchant_id = "your_merchant_id"; // Replace with your sandbox ID
$merchant_secret = "your_merchant_secret"; // Keep this secret!

// Generate a unique order ID
$order_id = uniqid();
$amount = "1000.00"; // LKR
$currency = "LKR";

// Calculate the secure hash
$hash = strtoupper(
    md5(
        $merchant_id . 
        $order_id . 
        number_format($amount, 2, '.', '') . 
        $currency .  
        strtoupper(md5($merchant_secret))
    )
);
?>

<!DOCTYPE html>
<html>
<head>
    <title>PayHere Payment Integration</title>
</head>
<body>
    <h1>Complete Your Payment</h1>
    <form method="post" action="https://sandbox.payhere.lk/pay/checkout">
        <!-- Required Fields -->
        <input type="hidden" name="merchant_id" value="<?php echo $merchant_id; ?>">
        <input type="hidden" name="return_url" value="https://yourwebsite.com/return.php">
        <input type="hidden" name="cancel_url" value="https://yourwebsite.com/cancel.php">
        <input type="hidden" name="notify_url" value="https://yourwebsite.com/notify.php">
        
        <!-- Order Details -->
        <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
        <input type="hidden" name="items" value="Test Product">
        <input type="hidden" name="currency" value="<?php echo $currency; ?>">
        <input type="hidden" name="amount" value="<?php echo $amount; ?>">
        
        <!-- Customer Details -->
        <input type="hidden" name="first_name" value="John">
        <input type="hidden" name="last_name" value="Doe">
        <input type="hidden" name="email" value="customer@example.com">
        <input type="hidden" name="phone" value="0771234567">
        <input type="hidden" name="address" value="No.1, Galle Road">
        <input type="hidden" name="city" value="Colombo">
        <input type="hidden" name="country" value="Sri Lanka">
        
        <!-- Security Hash -->
        <input type="hidden" name="hash" value="<?php echo $hash; ?>">
        
        <button type="submit">Pay with PayHere</button>
    </form>
</body>
</html>
Security Tip: Never expose your Merchant Secret in client-side code. The hash calculation should always be done server-side.

Step 2: Handle Payment Notification (notify.php)

<?php
// Validate PayHere IPN (Instant Payment Notification)
function verifyPayment($merchant_secret) {
    $merchant_id = $_POST['merchant_id'];
    $order_id = $_POST['order_id'];
    $amount = $_POST['payhere_amount'];
    $currency = $_POST['payhere_currency'];
    $status_code = $_POST['status_code'];
    $md5sig = $_POST['md5sig'];
    
    // Recompute the hash for verification
    $local_md5sig = strtoupper(
        md5(
            $merchant_id . $order_id . $amount . 
            $currency . $status_code . 
            strtoupper(md5($merchant_secret))
        )
    );
    
    // Check if the signature matches and payment is successful
    return ($local_md5sig === $md5sig && $status_code == 2);
}

// Your Merchant Secret
$merchant_secret = "your_merchant_secret";

if (verifyPayment($merchant_secret)) {
    // Payment is successful
    $order_id = $_POST['order_id'];
    $amount = $_POST['payhere_amount'];
    
    // Update your database or trigger order fulfillment
    file_put_contents('payments.log', "SUCCESS: Order $order_id, Amount $amount\n", FILE_APPEND);
    
    // Return HTTP 200 to PayHere
    header("HTTP/1.1 200 OK");
} else {
    // Payment failed or verification error
    file_put_contents('payments.log', "FAILED: " . json_encode($_POST) . "\n", FILE_APPEND);
    header("HTTP/1.1 400 Bad Request");
}
?>

Step 3: Handle Return URL (return.php)

<?php
$order_id = $_GET['order_id'];
$status = $_GET['status'];

if ($status === 'success') {
    echo "<h1>Payment Successful!</h1>";
    echo "<p>Thank you for your payment. Order ID: <strong>$order_id</strong></p>";
} else {
    echo "<h1>Payment Cancelled</h1>";
    echo "<p>Your payment was not completed. Order ID: <strong>$order_id</strong></p>";
}
?>

5. Testing & Going Live

Testing in Sandbox Mode

  1. Use sandbox credentials (merchant_id & merchant_secret)
  2. Test with PayHere's test cards:
    • Visa: 4111 1111 1111 1111 (any expiry/CVV)
    • Mastercard: 5555 5555 5555 4444

Going Live

  1. Replace sandbox.payhere.lk with www.payhere.lk
  2. Use your live merchant credentials
  3. Ensure your site has SSL (HTTPS)
Pro Tip: Before going live, thoroughly test all scenarios including successful payments, cancellations, and IPN verification.

6. Common Issues & Troubleshooting

Issue Solution
Payment not redirecting Check if merchant_id is correct
IPN not working Ensure notify_url is HTTPS
Hash verification failed Double-check merchant_secret
"Invalid Amount" error Format amount as 1000.00 (2 decimal places)

7. Conclusion

Integrating PayHere in PHP is straightforward if you follow these steps:

  1. Set up sandbox testing
  2. Generate a secure hash for each transaction
  3. Handle IPN properly to confirm payments
  4. Test thoroughly before going live

If you need recurring payments, check PayHere's subscription API documentation.

Final Notes:

Would you like me to add Laravel-specific integration or WordPress plugin instructions? Let me know in the comments! 👇

Back to Top

No comments:

Post a Comment

Fiverr Fee Calculator – Know What You Really Earn or Pay!

Fiverr Fee Calculator – Know What You Really Earn or Pay! 💸 "How much will I actually earn after Fiverr takes its cut?...