PHP code example of nimbbl / nimbbl-sdk

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

    

nimbbl / nimbbl-sdk example snippets





Nimbbl\Api\RestClient\NimbblClient;

$config = [
    'access_key' => 'your_access_key',
    'access_secret' => 'your_access_secret',
    'api_host' => 'https://api.nimbbl.tech',
];

// Initialize the SDK
$api = new NimbblClient(
    $config['access_key'],
    $config['access_secret'],
    rtrim($config['api_host'], '/') . '/api/v3' // API endpoint
);

// Step 1: Generate merchant token (for Transaction Enquiry/Refunds)
$tokenResponse = $api->auth()->generateToken();
$merchantToken = $tokenResponse['token'];

// Step 2: Create an order (uses merchant token initially)
$order = $api->orders()->createOrder([
    'invoice_id' => 'INV-12345',
    'amount_before_tax' => 3.60,
    'tax' => 0.40,
    'total_amount' => 4.00,
    'currency' => 'INR',
    'user' => [
        'email' => '[email protected]',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'mobile_number' => '9876543210',
        'country_code' => '+91'
    ]
], $merchantToken);

// Step 3: Extract order token from response
if (!isset($order['error'])) {
    $orderToken = $order['token']; // Use this for subsequent order-related operations
    echo "Order created: " . ($order['order_id'] ?? $order['nimbbl_order_id']);
}

// 1. Generate merchant token
$tokenResponse = $api->auth()->generateToken();
$merchantToken = $tokenResponse['token'];

// 2. Create order (uses merchant token initially)
$order = $api->orders()->createOrder($orderData, $merchantToken);
$orderToken = $order['token']; // Extract order token

// 3. Use order token for order-related operations
$payment = $api->payments()->initiatePayment($paymentData, $orderToken);

// 4. Use merchant token for admin operations
$enquiry = $api->transactions()->transactionEnquiry($data, $merchantToken);
$refund = $api->refunds()->initiateRefund($refundData, $merchantToken);

// Generate merchant token first
$tokenResponse = $api->auth()->generateToken();
$merchantToken = $tokenResponse['token'];

// Create order (uses merchant token initially)
$order = $api->orders()->createOrder([
    'invoice_id' => 'INV-123',
    'amount_before_tax' => 3.60,
    'tax' => 0.40,
    'total_amount' => 4.00,
    'currency' => 'INR',
    'user' => [
        'email' => '[email protected]',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'mobile_number' => '9876543210',
        'country_code' => '+91'
    ]
], $merchantToken);

// Extract order token from response
$orderToken = $order['token'];

// Retrieve order (uses order token)
$order = $api->orders()->getOrderById('order_id', $orderToken);

// Initiate payment (uses order token)
$payment = $api->payments()->initiatePayment([
    'order_id' => 'order_id',
    'payment_mode_code' => 'net_banking',
    'bank_code' => 'axis',
    'callback_url' => 'https://your-callback-url.com'
], $orderToken);

// Complete payment (for Pay Later with OTP)
$payment = $api->payments()->completePayment([
    'transaction_id' => 'transaction_id',
    'payment_flow' => 'otp',
    'otp' => '123456'
], $orderToken);

// Resend OTP
$api->payments()->resendPaymentOtp([
    'transaction_id' => 'transaction_id'
], $orderToken);

// Capture an authorized payment (collects the held funds — full amount only)
$capture = $api->payments()->capture([
    'transaction_id' => 'o_xxxx-yyyy',
    'comment' => 'Goods dispatched'   // optional
], $merchantToken);
// => ['capture_status' => 'succeeded'|'pending'|'failed', 'transaction_id' => ..., ...]

// Void an authorized payment (releases the hold without charging — cannot be undone)
$void = $api->payments()->void([
    'transaction_id' => 'o_aaaa-bbbb',
    'comment' => 'Customer cancelled' // optional
], $merchantToken);
// => ['void_status' => 'succeeded'|'pending'|'failed', 'transaction_id' => ..., ...]

// Create payment link
$link = $api->paymentLinks()->createPaymentLink([
    'invoice_id' => 'INV-123',
    'total_amount' => 1000,
    'currency' => 'INR',
    'user' => [
        'email' => '[email protected]',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'mobile_number' => '9876543210',
        'country_code' => '+91'
    ],
    'expires_at' => date('Y-m-d H:i:s', strtotime('+7 days'))
]);

// Enquiry payment link
$link = $api->paymentLinks()->enquiryPaymentLink([
    'payment_link_id' => 'link_id'
]);

// Update payment link
$link = $api->paymentLinks()->updatePaymentLink([
    'payment_link_id' => 'link_id',
    'total_amount' => 1500
]);

// Payment link actions
$api->paymentLinks()->performPaymentLinkActions([
    'payment_link_id' => 'link_id',
    'action' => 'cancel'
]);

// List addresses
$addresses = $api->addresses()->listAddresses(['user_id' => 'user_id']);

// Create address
$address = $api->addresses()->createAddress([
    'addresses' => [
        [
            'first_name' => 'John',
            'last_name' => 'Doe',
            'address_1' => '123 Main St',
            'area' => 'Andheri',
            'city' => 'Mumbai',
            'state' => 'Maharashtra',
            'pincode' => '400001',
            'address_type' => 'home'
        ]
    ],
    'user_id' => 'user_id' // Optional
]);

// Update address
$address = $api->addresses()->updateAddress('address_id', [
    'line1' => '456 New St'
]);

// Delete address
$api->addresses()->deleteAddress('address_id');

// Generate merchant token
$tokenResponse = $api->auth()->generateToken();
$merchantToken = $tokenResponse['token'];

// Full refund by transaction_id
$refund = $api->refunds()->initiateRefund([
    'transaction_id' => 'transaction_id'
], $merchantToken);

// Partial refund with comment
$refund = $api->refunds()->initiateRefund([
    'transaction_id' => 'transaction_id',
    'refund_amount' => 500, // Optional for partial refund
    'comment' => 'Refund reason'
], $merchantToken);

// Refund by invoice_id
$refund = $api->refunds()->initiateRefund([
    'invoice_id' => 'invoice_id',
    'refund_amount' => 250,
    'comment' => 'Refund reason'
], $merchantToken);

// Refund with idempotency (refund_request_id)
$refund = $api->refunds()->initiateRefund([
    'transaction_id' => 'transaction_id',
    'refund_request_id' => 'UNIQUE_REFUND_ID_' . time(),
    'refund_amount' => 100
], $merchantToken);

// Refund with order line items
$refund = $api->refunds()->initiateRefund([
    'transaction_id' => 'transaction_id',
    'order_line_items' => [
        [
            'sku_id' => 'SKU-001',
            'serial_numbers' => ['SN-001', 'SN-002'] // Optional
        ]
    ],
    'comment' => 'Refund specific items'
], $merchantToken);

// Generate merchant token
$tokenResponse = $api->auth()->generateToken();
$merchantToken = $tokenResponse['token'];

// Enquiry by order ID
$status = $api->transactions()->transactionEnquiry([
    'order_id' => 'order_id'
], $merchantToken);

// Enquiry by invoice ID
$status = $api->transactions()->transactionEnquiry([
    'invoice_id' => 'invoice_id'
], $merchantToken);

// Enquiry by transaction ID
$status = $api->transactions()->transactionEnquiry([
    'transaction_id' => 'transaction_id'
], $merchantToken);

// List payment modes
$modes = $api->checkoutUtilities()->listPaymentModes(['order_id' => 'order_id'], $orderToken);

// List banks
$banks = $api->checkoutUtilities()->listBanks(['order_id' => 'order_id'], $orderToken);

// List wallets
$wallets = $api->checkoutUtilities()->listWallets(['order_id' => 'order_id'], $orderToken);

// List EMIs
$emis = $api->checkoutUtilities()->listEMIs(['order_id' => 'order_id'], $orderToken);

// Get offers
$offers = $api->checkoutUtilities()->getOffers([
    'order_id' => 'order_id',
    'payment_mode_code' => 'card'
], $orderToken);

// Get card BIN data
$binData = $api->checkoutUtilities()->getCardBinData([
    'card_bin' => '411111',  // Required: first 6 digits of card number
    'order_id' => 'order_id' // Optional: order for which to validate bin details
], $orderToken);

// Validate UPI VPA
$validation = $api->checkoutUtilities()->validateUpiVpa(['upi_id' => 'user@paytm'], $orderToken);

use Nimbbl\Api\Common\SignatureVerifier;
use Nimbbl\Api\Common\JsonKeys;

$accessSecret = 'your_access_secret';
$verifier = new SignatureVerifier();

// Standard Checkout callback — pass the RAW body:
//   - redirect/GET mode:  the base64 `response` query param
//   - popup/POST mode:    the raw request body
$rawBody = $_GET['response'] ?? file_get_contents('php://input');

$result = $verifier->verifyCallback($rawBody, $accessSecret);
// => ['success' => bool, 'version' => 'v4'|'legacy', 'event_type' => ..., 'payload' => [...]]

if (!$result['success']) {
    http_response_code(400);   // signature/decryption failed — do NOT trust the callback
    exit;
}
$payload = $result['payload'];

$transactionId = $payload[JsonKeys::NIMBBL_TRANSACTION_ID] ?? null;   // v4: top level
if ($transactionId) {
    $enq  = $api->transactions()->transactionEnquiry([JsonKeys::TRANSACTION_ID => $transactionId]);
    $txn  = $enq['transaction'][0] ?? [];
    $status = $txn['payment_status'] ?? null;   // 'succeeded' | 'pending' | 'failed' — authoritative
    // 'succeeded' -> fulfil ; 'pending' -> still processing ; 'failed' -> failed
}
// Pre-auth: reason === 'payment_authorized' means funds are HELD, not captured — do NOT fulfil; capture first.

$status        = $payload['transaction']['status'] ?? $payload['status'] ?? null;
$orderId       = $payload['nimbbl_order_id'] ?? $payload['order']['order_id'] ?? null;
$transactionId = $payload['transaction']['transaction_id'] ?? null;
// Treat webhook / Transaction Enquiry as the source of truth before fulfilling the order.

use Nimbbl\Api\Common\Encryption;

// Initialize encryption with access secret
$encryption = new Encryption($accessSecret);

// Encrypt data for API requests (if needed)
$data = [
    'user_id' => 'user_123',
    'email' => '[email protected]'
];
$encrypted = $encryption->encrypt($data);

// Decrypt encrypted response
$decrypted = $encryption->decrypt($encrypted, true); // true = return as array

use Nimbbl\Api\Common\SignatureVerifier;

$rawBody = file_get_contents('php://input');
$accessSecret = 'your_access_secret';

$verifier = new SignatureVerifier();
$result = $verifier->verifyWebhook($rawBody, $accessSecret);
// => ['success' => bool, 'version' => 'v4'|'legacy', 'event_type' => ..., 'payload' => [...]]

if ($result['success']) {
    $payload       = $result['payload'];
    $eventType     = $result['event_type'] ?? $payload['event_type'] ?? null;
    $orderId       = $payload['nimbbl_order_id'] ?? $payload['order']['order_id'] ?? null;
    $transactionId = $payload['transaction']['transaction_id'] ?? null;

    // Branch on the event type. Pre-auth lifecycle: payment_authorized ->
    // capture_success / void_success (or *_pending / *_failed).
    switch ($eventType) {
        case 'capture_success': /* funds captured — safe to fulfil */ break;
        case 'void_success':    /* hold released — cancel the order */ break;
        // 'payment_success', 'refund_success', ... handle as needed
    }

    // Respond 200 within 15s to acknowledge; reconcile via Transaction Enquiry.
    http_response_code(200);
}

use Nimbbl\Api\Exception\NimbblException;
use Nimbbl\Api\Exception\AuthenticationException;
use Nimbbl\Api\Exception\BadRequestException;
use Nimbbl\Api\Exception\NotFoundException;

try {
    $order = $api->orders()->createOrder([...]);
} catch (AuthenticationException $e) {
    // Handle 401 errors
    echo "Authentication failed: " . $e->getMessage();
} catch (BadRequestException $e) {
    // Handle 400/422 errors
    echo "Invalid request: " . $e->getMessage();
} catch (NotFoundException $e) {
    // Handle 404 errors
    echo "Resource not found: " . $e->getMessage();
} catch (NimbblException $e) {
    // Handle other Nimbbl exceptions
    echo "Error: " . $e->getMessage();
    echo "Error Code: " . $e->getErrorCode();
    echo "Request ID: " . $e->getRequestId();
}