PHP code example of chamikasamaraweera / payhere-php-sdk

1. Go to this page and download the library: Download chamikasamaraweera/payhere-php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chamikasamaraweera / payhere-php-sdk example snippets



Payhere\Payhere;

// Initialize with your credentials
$payhere = new Payhere(
    'YOUR_MERCHANT_ID',
    'YOUR_MERCHANT_SECRET',
    true // true for sandbox, false for live
);

// Create a payment request
$payment = $payhere->createPaymentRequest()
    ->setOrderId('ORDER_' . time())
    ->setAmount(1000.00)
    ->setCurrency('LKR')
    ->setItems('Product Name', 1)
    ->setCustomer(
        'John',
        'Doe',
        '[email protected]',
        '0771234567',
        '123 Main Street',
        'Colombo',
        'Sri Lanka'
    )
    ->setReturnUrl('https://yoursite.com/payment/return')
    ->setCancelUrl('https://yoursite.com/payment/cancel')
    ->setNotifyUrl('https://yoursite.com/payment/notify');

// Option 1: Generate HTML form
echo $payment->generateForm('Pay Now');

// Option 2: Auto-redirect to PayHere
$payment->redirect();

// Option 3: Get data array for custom implementation
$paymentData = $payment->getData();


Payhere\Payhere;

$payhere = new Payhere(
    'YOUR_MERCHANT_ID',
    'YOUR_MERCHANT_SECRET',
    true
);

// Handle the notification
$notification = $payhere->handleNotification();

// Verify the notification
if ($notification->verify()) {
    
    // Check if payment was successful
    if ($notification->isSuccess()) {
        $orderId = $notification->getOrderId();
        $paymentId = $notification->getPaymentId();
        $amount = $notification->getAmount();
        $currency = $notification->getCurrency();
        
        // Update your database
        // Mark order as paid
        // Send confirmation email, etc.
        
        echo "Payment successful!";
    } else {
        $status = $notification->getStatusText();
        echo "Payment status: " . $status;
    }
    
} else {
    // Invalid notification
    http_response_code(400);
    echo "Invalid notification";
}

// Sandbox (for testing)
$payhere = new Payhere('MERCHANT_ID', 'MERCHANT_SECRET', true);

// Live (for production)
$payhere = new Payhere('MERCHANT_ID', 'MERCHANT_SECRET', false);

$payhere = new Payhere('MERCHANT_ID', 'MERCHANT_SECRET', true);
bash
composer