PHP code example of bijayx / nepal-pay-laravel

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

    

bijayx / nepal-pay-laravel example snippets


use BijayX\NepalPay\Data\ExpectedPayment;
use BijayX\NepalPay\Facades\NepalPay;

$payment = NepalPay::driver('khalti')->initiate([
    'amount' => 150000,                 // Rs 1,500 in paisa
    'order_id' => 'ORD-1001-a1',        // unique per payment attempt
    'order_name' => 'Charging session',
    'return_url' => route('payments.return', 'khalti'),
]);

// Persist $payment->reference and $payment->amount on your order, then:
return $payment->redirect();            // GatewayRedirectResponse (Responsable)

$result = NepalPay::driver('esewa')->verify(
    $request->query(),
    new ExpectedPayment(amount: $order->amount, reference: $order->payment_reference),
);

if ($result->isPaid()) {
    // Mark the order paid (idempotently, see below).
}

use BijayX\NepalPay\Contracts\PaymentGateway;

public function __construct(private PaymentGateway $gateway) {}

$table->unsignedBigInteger('amount');                 // what the customer owes, in paisa
$table->string('payment_gateway')->nullable();
$table->string('payment_reference')->nullable()->unique();
$table->unsignedBigInteger('payment_amount')->nullable();
$table->string('payment_transaction_id')->nullable();
$table->timestamp('paid_at')->nullable();

Route::post('/orders/{order}/pay/{gateway}', [PaymentController::class, 'store'])
    ->whereIn('gateway', ['khalti', 'esewa'])
    ->name('payments.store');

Route::get('/payments/{gateway}/return/{order}', [PaymentController::class, 'callback'])
    ->whereIn('gateway', ['khalti', 'esewa'])
    ->name('payments.return');



namespace App\Http\Controllers;

use App\Models\Order;
use BijayX\NepalPay\Data\ExpectedPayment;
use BijayX\NepalPay\Exceptions\InvalidSignatureException;
use BijayX\NepalPay\Exceptions\NepalPayException;
use BijayX\NepalPay\Exceptions\PaymentMismatchException;
use BijayX\NepalPay\Facades\NepalPay;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

final class PaymentController
{
    public function store(Order $order, string $gateway): Responsable|RedirectResponse
    {
        abort_if($order->paid_at !== null, 409, 'This order is already paid.');

        try {
            $payment = NepalPay::driver($gateway)->initiate([
                'amount' => $order->amount,
                // A fresh id for every attempt: both gateways reject reused ids.
                'order_id' => $order->id.'-'.Str::lower(Str::random(8)),
                'order_name' => "Order #{$order->id}",
                'return_url' => route('payments.return', [$gateway, $order]),
                'customer' => ['name' => $order->customer_name, 'phone' => $order->customer_phone],
            ]);
        } catch (NepalPayException $e) {
            report($e);

            return back()->with('error', 'We could not start the payment. Please try again.');
        }

        // Store what verify() needs BEFORE redirecting.
        $order->forceFill([
            'payment_gateway' => $gateway,
            'payment_reference' => $payment->reference,
            'payment_amount' => $payment->amount,
        ])->save();

        return $payment->redirect();
    }

    public function callback(Request $request, string $gateway, Order $order): RedirectResponse
    {
        if ($order->payment_gateway !== $gateway || $order->payment_reference === null) {
            abort(404);
        }

        try {
            $result = NepalPay::driver($gateway)->verify(
                $request->query(),
                new ExpectedPayment(amount: $order->payment_amount, reference: $order->payment_reference),
            );
        } catch (PaymentMismatchException|InvalidSignatureException $e) {
            report($e); // possible tampering: investigate, do not fulfil

            return to_route('orders.show', $order)->with('error', 'The payment could not be verified.');
        } catch (NepalPayException $e) {
            report($e); // network/gateway problem: the payment may still complete

            return to_route('orders.show', $order)->with('error', 'We could not confirm the payment yet.');
        }

        if (! $result->isPaid()) {
            return to_route('orders.show', $order)->with('error', "Payment {$result->status->value}.");
        }

        // Callbacks can arrive more than once: lock the row and mark paid only once.
        DB::transaction(function () use ($order, $result): void {
            $locked = Order::query()->whereKey($order->getKey())->lockForUpdate()->firstOrFail();

            if ($locked->paid_at !== null) {
                return;
            }

            $locked->forceFill([
                'paid_at' => now(),
                'payment_transaction_id' => $result->transactionId,
            ])->save();

            // Dispatch fulfilment here (jobs, emails, ...).
        });

        return to_route('orders.show', $order)->with('status', 'Payment received. Thank you!');
    }
}

$result = NepalPay::driver($order->payment_gateway)
    ->lookup($order->payment_reference, $order->payment_amount);

use BijayX\NepalPay\Data\{Breakdown, Customer, PaymentRequest};

$request = new PaymentRequest(
    amount: 113000,
    orderId: 'ORD-1002-b7',
    orderName: 'Charging session',
    returnUrl: route('payments.return', ['esewa', $order]),
    customer: new Customer(name: 'Ram Bahadur', phone: '9800000001'),
    breakdown: new Breakdown(tax: 13000),
);

use BijayX\NepalPay\Support\Money;

Money::paisaToRupeeString(11050); // "110.50"
Money::paisaToRupeeString(11000); // "110"
Money::parseRupees('1,000.0');    // 100000

use BijayX\NepalPay\Exceptions\NepalPayException;
use BijayX\NepalPay\Exceptions\ValidationException;

try {
    $payment = NepalPay::driver('khalti')->initiate($data);
} catch (ValidationException $e) {
    return back()->withErrors($e->fields());
} catch (NepalPayException $e) {
    report($e);           // context() adds nepal_pay_code, gateway and details to the log
    return back()->with('error', 'Payment is unavailable right now.');
}

use Illuminate\Support\Facades\Http;

Http::fake([
    'dev.khalti.com/api/v2/epayment/initiate/' => Http::response([
        'pidx' => 'test-pidx',
        'payment_url' => 'https://test-pay.khalti.com/?pidx=test-pidx',
        'expires_at' => now()->addMinutes(30)->toIso8601String(),
        'expires_in' => 1800,
    ]),
    'dev.khalti.com/api/v2/epayment/lookup/' => Http::response([
        'pidx' => 'test-pidx',
        'total_amount' => 150000,
        'status' => 'Completed',
        'transaction_id' => 'TXN-1',
        'fee' => 0,
        'refunded' => false,
    ]),
]);

$this->get(route('payments.return', ['khalti', $order]).'?pidx=test-pidx')
    ->assertRedirect(route('orders.show', $order));

expect($order->fresh()->paid_at)->not->toBeNull();

use BijayX\NepalPay\Gateways\Esewa\EsewaConfig;
use BijayX\NepalPay\Gateways\Esewa\EsewaSignature;

$payload = [
    'transaction_code' => '000AE01',
    'status' => 'COMPLETE',
    'total_amount' => '1,500.0',
    'transaction_uuid' => $order->payment_reference,
    'product_code' => 'EPAYTEST',
    'signed_field_names' => 'transaction_code,status,total_amount,transaction_uuid,product_code,signed_field_names',
];
$payload['signature'] = (new EsewaSignature(EsewaConfig::SANDBOX_SECRET_KEY))
    ->sign(EsewaSignature::message($payload, $payload['signed_field_names']));

Http::fake([
    'rc.esewa.com.np/api/epay/transaction/status/*' => Http::response([
        'product_code' => 'EPAYTEST',
        'transaction_uuid' => $order->payment_reference,
        'total_amount' => 1500.0,
        'status' => 'COMPLETE',
        'ref_id' => '000AE01',
    ]),
]);

$this->get(route('payments.return', ['esewa', $order]).'?data='.urlencode(base64_encode(json_encode($payload))));

use BijayX\NepalPay\Data\{ExpectedPayment, InitiatedPayment, PaymentRequest, PaymentResult};
use BijayX\NepalPay\Gateways\AbstractGateway;
use BijayX\NepalPay\Http\GatewayHttpClient;

final class FonepayGateway extends AbstractGateway
{
    public function __construct(private GatewayHttpClient $http, array $config, $events = null)
    {
        parent::__construct($events);
    }

    public function name(): string
    {
        return 'fonepay';
    }

    protected function createPayment(PaymentRequest $request): InitiatedPayment { /* ... */ }

    protected function confirm(array $callback, ?ExpectedPayment $expected): PaymentResult { /* ... */ }

    public function lookup(string $reference, ?int $amount = null): PaymentResult { /* ... */ }
}

use BijayX\NepalPay\Facades\NepalPay;
use BijayX\NepalPay\NepalPayManager;

NepalPay::extend('fonepay', function ($app) {
    $manager = $app->make(NepalPayManager::class);

    return new FonepayGateway(
        $manager->httpClient('fonepay'),       // shares timeout and retry settings
        $manager->gatewayConfig('fonepay'),    // reads nepal-pay.gateways.fonepay
        $app['events'],
    );
});

NepalPay::driver('fonepay')->initiate([...]);

return $payment->redirect()->withNonce(Vite::cspNonce());
bash
php artisan vendor:publish --tag=nepal-pay-config
bash
php artisan vendor:publish --tag=nepal-pay-views