Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.paybridgenp.com/llms.txt

Use this file to discover all available pages before exploring further.

Installation

composer require paybridge-np/sdk

Initialization

use PayBridgeNP\PayBridge;

$paybridge = new PayBridge([
    'apiKey'     => getenv('PAYBRIDGE_API_KEY'), // sk_sandbox_... or sk_live_...
    'baseUrl'    => 'https://api.paybridgenp.com', // optional
    'timeout'    => 30,                            // optional, seconds. default: 30
    'maxRetries' => 2,                             // optional. default: 2
]);

$paybridge->checkout

checkout->create(array $params)

Creates a checkout session.
$session = $paybridge->checkout->create([
    'amount'    => 10000,                              // required - paisa (NPR × 100)
    'returnUrl' => 'https://yoursite.com/success',    // required
    'cancelUrl' => 'https://yoursite.com/cart',       // optional
    'provider'  => 'khalti',                          // optional - omit to let customer pick
    'currency'  => 'NPR',                             // optional, default: "NPR"
    'metadata'  => ['orderId' => 'ORD-001'],          // optional
]);

echo $session['checkout_url'];  // redirect customer here
echo $session['id'];            // cs_...
echo $session['expires_at'];    // ISO timestamp
Parameters:
NameTypeRequiredDescription
amountintYesIn paisa. NPR 100.00 = 10000
returnUrlstringYesRedirect URL after payment
cancelUrlstringNoRedirect URL on cancellation
providerstringNo"esewa", "khalti", "fonepay"
currencystringNoDefault: "NPR"
metadataarrayNoPassed through to webhooks and payment records

checkout->expire(string $id)

Marks a session as expired so it can no longer accept payment. Use this when you mint a fresh session for a logical purchase that already had one outstanding (e.g. a customer requesting a new payment link), so the old URL stops being payable immediately rather than waiting for its 30-minute TTL. Mirrors Stripe’s POST /checkout/sessions/{id}/expire.
$paybridge->checkout->expire('cs_6f2jHn2…');
Idempotent: calling on an already-terminal session is a no-op that returns the current row state without error.

$paybridge->payments

payments->list(array $params = [])

$response = $paybridge->payments->list([
    'limit'  => 20,  // optional, default 20, max 100
    'offset' => 0,   // optional, default 0
]);

echo $response['meta']['total'];

foreach ($response['data'] as $payment) {
    echo $payment['id'] . ' ' . $payment['amount'] . ' ' . $payment['status'];
}

payments->retrieve(string $id)

$payment = $paybridge->payments->retrieve('pay_6f2jHn2...');

echo $payment['status'];       // "success" | "failed"
echo $payment['amount'];       // paisa
echo $payment['provider'];     // "esewa" | "khalti" | ...
echo $payment['provider_ref']; // provider's transaction reference

$paybridge->webhooks

webhooks->create(array $params)

$endpoint = $paybridge->webhooks->create([
    'url'    => 'https://yoursite.com/webhooks/paybridge',
    'events' => ['payment.succeeded', 'payment.failed'], // optional - omit for all
]);

echo $endpoint['signing_secret']; // save this - shown only once

webhooks->list()

$response = $paybridge->webhooks->list();
foreach ($response['data'] as $wh) {
    echo $wh['id'] . ' ' . $wh['url'];
}

webhooks->delete(string $id)

$paybridge->webhooks->delete('wh_...');

PayBridge::constructEvent(string $body, string $signature, string $secret) (static)

Verifies a webhook signature and returns the parsed event. Use this in your webhook handler.
use PayBridgeNP\PayBridge;
use PayBridgeNP\Exceptions\SignatureVerificationException;

$body      = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_PAYBRIDGE_SIGNATURE'] ?? '';

try {
    $event = PayBridge::constructEvent($body, $signature, getenv('PAYBRIDGE_WEBHOOK_SECRET'));
} catch (SignatureVerificationException $e) {
    http_response_code(400);
    exit('Invalid signature');
}

switch ($event['type']) {
    case 'payment.succeeded':
        // $event['data']['id'], $event['data']['amount'], $event['data']['metadata']
        fulfillOrder($event['data']['metadata']['orderId'] ?? null);
        break;

    case 'payment.failed':
        notifyOrderFailed($event['data']['session_id']);
        break;
}

http_response_code(200);
echo json_encode(['received' => true]);
Throws SignatureVerificationException if:
  • The signature header is missing or malformed
  • The HMAC doesn’t match
  • The timestamp is more than 5 minutes old (replay attack protection)

$paybridge->billing

The billing methods provide access to plans, customers, subscriptions, and invoices. Billing API access requires the Premium plan.

Plans

// Create a plan
$plan = $paybridge->plans->create([
    'name'          => 'Pro Monthly',
    'amount'        => 99900,   // paisa - NPR 999/month
    'interval'      => 'month',
    'intervalCount' => 1,
    'trialDays'     => 14,      // optional
]);

// List plans
$response = $paybridge->plans->list();

// Get a plan
$plan = $paybridge->plans->retrieve('plan_...');

// Update a plan
$updated = $paybridge->plans->update('plan_...', ['name' => 'Pro Monthly v2']);

Customers

// Create a customer
$customer = $paybridge->customers->create([
    'name'               => 'Aarav Sharma',
    'email'              => 'aarav@example.com',
    'externalCustomerId' => 'user_123',  // optional
]);

// List customers
$response = $paybridge->customers->list();

// Get a customer
$customer = $paybridge->customers->retrieve('cus_...');

// Update a customer
$updated = $paybridge->customers->update('cus_...', ['email' => 'new@example.com']);

// Delete a customer
$paybridge->customers->delete('cus_...');

Subscriptions

// Create a subscription
$sub = $paybridge->subscriptions->create([
    'customerId' => 'cus_...',
    'planId'     => 'plan_...',
]);

// List subscriptions
$response = $paybridge->subscriptions->list();

// Get a subscription
$sub = $paybridge->subscriptions->retrieve('sub_...');

// Lifecycle actions
$paybridge->subscriptions->pause('sub_...');
$paybridge->subscriptions->resume('sub_...');
$paybridge->subscriptions->cancel('sub_...');

// Change plan
$paybridge->subscriptions->changePlan('sub_...', ['planId' => 'plan_...']);

Invoices

// List invoices
$response = $paybridge->invoices->list([
    'subscriptionId' => 'sub_...',  // optional
]);

// Get an invoice
$invoice = $paybridge->invoices->retrieve('inv_...');

echo $invoice['status'];      // "pending" | "paid" | "overdue" | "cancelled"
echo $invoice['amount'];      // paisa
echo $invoice['due_date'];    // ISO timestamp
echo $invoice['payment_url']; // hosted payment link

Error handling

All SDK methods throw typed exceptions you can catch and inspect:
use PayBridgeNP\Exceptions\AuthenticationException;
use PayBridgeNP\Exceptions\PayBridgeException;

try {
    $paybridge->checkout->create(['amount' => 1000, 'returnUrl' => '...']);
} catch (AuthenticationException $e) {
    // Invalid API key
    error_log('Check your PAYBRIDGE_API_KEY');
} catch (PayBridgeException $e) {
    error_log($e->getMessage());    // human-readable message
    error_log($e->getStatusCode()); // HTTP status
    error_log($e->getCode());       // machine-readable code
}

Exception classes

ClassStatusWhen
AuthenticationException401Invalid or missing API key
InvalidRequestException400Bad request parameters
NotFoundException404Resource not found
RateLimitException429Too many requests
PayBridgeException5xxServer error
SignatureVerificationException-Webhook HMAC mismatch or replay

Framework examples

// config/services.php
'paybridge' => [
    'key'    => env('PAYBRIDGE_API_KEY'),
    'secret' => env('PAYBRIDGE_WEBHOOK_SECRET'),
],
// app/Http/Controllers/CheckoutController.php
use PayBridgeNP\PayBridge;

class CheckoutController extends Controller
{
    public function create(Request $request)
    {
        $paybridge = new PayBridge(['apiKey' => config('services.paybridge.key')]);

        $session = $paybridge->checkout->create([
            'amount'    => $request->amount,
            'returnUrl' => route('checkout.success'),
            'cancelUrl' => route('cart.index'),
            'metadata'  => ['orderId' => $request->order_id],
        ]);

        return redirect($session['checkout_url']);
    }
}
// app/Http/Controllers/WebhookController.php
use PayBridgeNP\PayBridge;
use PayBridgeNP\Exceptions\SignatureVerificationException;

class WebhookController extends Controller
{
    public function handle(Request $request)
    {
        try {
            $event = PayBridge::constructEvent(
                $request->getContent(),
                $request->header('X-PayBridge-Signature'),
                config('services.paybridge.secret'),
            );
        } catch (SignatureVerificationException $e) {
            return response()->json(['error' => 'Invalid signature'], 400);
        }

        if ($event['type'] === 'payment.succeeded') {
            Order::where('id', $event['data']['metadata']['orderId'] ?? null)
                ->update(['status' => 'paid']);
        }

        return response()->json(['received' => true]);
    }
}