PHP code example of khalti / php-sdk

1. Go to this page and download the library: Download khalti/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/ */

    

khalti / php-sdk example snippets



KhaltiSDK\Khalti;
use KhaltiSDK\Exceptions\ApiException;
use KhaltiSDK\Exceptions\ValidationException;

// Initialize SDK
$khalti = new Khalti([
    'environment' => 'sandbox', // or 'live' for production
    'secretKey' => 'your_secret_key_here',
    'enableLogging' => true
]);

// Initiate Payment
try {
    $response = $khalti->ePayment()->initiate([
        'return_url' => 'https://yoursite.com/success',
        'website_url' => 'https://yoursite.com',
        'amount' => 1000, // 10 NPR in paisa
        'purchase_order_id' => 'ORDER-123',
        'purchase_order_name' => 'Test Product',
        'customer_info' => [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'phone' => '9800000000'
        ]
    ]);
    
    // Redirect user to payment URL
    header('Location: ' . $response['payment_url']);
    exit;
    
} catch (ValidationException $e) {
    echo "Error: " . $e->getMessage();
} catch (ApiException $e) {
    echo "API Error: " . $e->getMessage();
}


// After user returns from payment
$pidx = $_GET['pidx'];

try {
    $result = $khalti->ePayment()->verify($pidx);
    
    if ($result['status'] === 'Completed') {
        echo "Payment successful!";
        // Update your database, send confirmation email, etc.
    } else {
        echo "Payment failed or pending";
    }
    
} catch (Exception $e) {
    echo "Verification failed: " . $e->getMessage();
}

   $khalti = new Khalti([
       'environment' => 'sandbox',
       'secretKey' => 'live_secret_key_from_sandbox_dashboard',
       'enableLogging' => true
   ]);
   

   $khalti = new Khalti([
       'environment' => 'live',
       'secretKey' => 'live_secret_key_from_production_dashboard',
       'enableLogging' => false // Disable logging in production
   ]);
   


KhaltiSDK\Khalti;
use KhaltiSDK\Exceptions\ApiException;
use KhaltiSDK\Exceptions\ValidationException;

$khalti = new Khalti([
    'environment' => 'sandbox',
    'secretKey' => 'your_secret_key_here',
    'enableLogging' => true
]);

if ($_POST) {
    try {
        $response = $khalti->ePayment()->initiate([
            'return_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/verify.php',
            'website_url' => 'http://' . $_SERVER['HTTP_HOST'],
            'amount' => (int)($_POST['amount'] * 100),
            'purchase_order_id' => 'ORDER-' . time(),
            'purchase_order_name' => $_POST['product_name'],
            'customer_info' => [
                'name' => $_POST['customer_name'],
                'email' => $_POST['customer_email'],
                'phone' => $_POST['customer_phone']
            ]
        ]);
        
        header('Location: ' . $response['payment_url']);
        exit;
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}


KhaltiSDK\Khalti;
use KhaltiSDK\Exceptions\ApiException;

$khalti = new Khalti([
    'environment' => 'sandbox',
    'secretKey' => 'your_secret_key_here',
    'enableLogging' => true
]);

$pidx = $_GET['pidx'] ?? '';

if ($pidx) {
    try {
        $result = $khalti->ePayment()->verify($pidx);
        
        if ($result['status'] === 'Completed') {
            $message = "Payment successful! Transaction ID: " . $result['transaction_id'];
            $status = 'success';
        } else {
            $message = "Payment status: " . $result['status'];
            $status = 'warning';
        }
        
    } catch (Exception $e) {
        $message = "Verification failed: " . $e->getMessage();
        $status = 'error';
    }
} else {
    $message = "No payment ID provided";
    $status = 'error';
}

$khalti = new Khalti([
    'environment' => 'sandbox',
    'secretKey' => 'your_secret_key',
    'publicKey' => 'your_public_key', // Optional
    'enableLogging' => true,
    'logPath' => '/path/to/logs/khalti.log',
    'logLevel' => 'info', // debug, info, warning, error, critical
    'timeout' => 30
]);

$response = $khalti->ePayment()->initiate([
    'return_url' => 'https://yoursite.com/success',     // Required
    'website_url' => 'https://yoursite.com',            // Required
    'amount' => 1000,                                   // Required (in paisa)
    'purchase_order_id' => 'ORDER-123',                 // Required
    'purchase_order_name' => 'Product Name',            // Required
    'customer_info' => [                                // Optional
        'name' => 'John Doe',
        'email' => '[email protected]',
        'phone' => '9800000000'
    ],
    'amount_breakdown' => [                             // Optional
        ['label' => 'Product', 'amount' => 900],
        ['label' => 'VAT', 'amount' => 100]
    ],
    'product_details' => [                              // Optional
        [
            'identity' => 'PROD-001',
            'name' => 'Product Name',
            'total_price' => 1000,
            'quantity' => 1,
            'unit_price' => 1000
        ]
    ]
]);

$result = $khalti->ePayment()->verify($pidx);

// Response:
// [
//     'pidx' => 'payment_id',
//     'total_amount' => 1000,
//     'status' => 'Completed', // Completed, Pending, User canceled, Expired, Refunded
//     'transaction_id' => 'transaction_id',
//     'fee' => 0,
//     'refunded' => false
// ]

use KhaltiSDK\Exceptions\ValidationException;
use KhaltiSDK\Exceptions\ApiException;
use KhaltiSDK\Exceptions\NetworkException;
use KhaltiSDK\Exceptions\ConfigurationException;

try {
    $response = $khalti->ePayment()->initiate($params);
} catch (ValidationException $e) {
    // Invalid parameters
    echo "Validation Error: " . $e->getMessage();
} catch (ApiException $e) {
    // API error
    echo "API Error: " . $e->getMessage();
} catch (NetworkException $e) {
    // Network error
    echo "Network Error: " . $e->getMessage();
} catch (ConfigurationException $e) {
    // Configuration error
    echo "Configuration Error: " . $e->getMessage();
}
bash
composer