PHP code example of usukhbayar / qpay-php

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

    

usukhbayar / qpay-php example snippets


use QPay\Config;
use QPay\QPayClient;
use QPay\Models\CreateSimpleInvoiceRequest;
use QPay\Exceptions\QPayException;

// Configure from environment variables
$config = Config::fromEnv();
$client = new QPayClient($config);

// Or configure manually
$config = new Config(
    baseUrl: 'https://merchant.qpay.mn',
    username: 'YOUR_USERNAME',
    password: 'YOUR_PASSWORD',
    invoiceCode: 'YOUR_INVOICE_CODE',
    callbackUrl: 'https://yoursite.com/callback',
);
$client = new QPayClient($config);

// Create an invoice (token is obtained automatically)
try {
    $invoice = $client->createSimpleInvoice(new CreateSimpleInvoiceRequest(
        invoiceCode: $config->invoiceCode,
        senderInvoiceNo: 'ORDER-001',
        invoiceReceiverCode: 'terminal',
        invoiceDescription: 'Payment for Order #001',
        amount: 10000.0,
        callbackUrl: $config->callbackUrl,
    ));

    echo $invoice->invoiceId;   // Invoice ID
    echo $invoice->qPayShortUrl; // Payment link
    echo $invoice->qrImage;     // QR code image (base64)
} catch (QPayException $e) {
    echo "Error: {$e->errorCode} - {$e->errorMessage}";
}

// All 5 variables must be set, otherwise InvalidArgumentException is thrown
$config = Config::fromEnv();

$config = new Config(
    baseUrl: 'https://merchant.qpay.mn',
    username: 'YOUR_USERNAME',
    password: 'YOUR_PASSWORD',
    invoiceCode: 'YOUR_INVOICE_CODE',
    callbackUrl: 'https://yoursite.com/callback',
);

// Explicitly obtain a token
$token = $client->getToken();
echo $token->accessToken;
echo $token->refreshToken;
echo $token->expiresIn;

// Explicitly refresh the token
$refreshed = $client->refreshTokenRequest();

use QPay\Models\CreateInvoiceRequest;

$invoice = $client->createInvoice(new CreateInvoiceRequest(
    invoiceCode: 'YOUR_INVOICE_CODE',
    senderInvoiceNo: 'ORDER-001',
    invoiceReceiverCode: 'terminal',
    invoiceDescription: 'Payment for services',
    amount: 50000.0,
    callbackUrl: 'https://yoursite.com/callback',
    // Optional fields:
    senderBranchCode: 'BRANCH_01',
    allowPartial: true,
    minimumAmount: 10000.0,
    allowExceed: false,
    maximumAmount: 100000.0,
    note: 'Additional notes',
    lines: [
        [
            'line_description' => 'Product A',
            'line_quantity' => '2',
            'line_unit_price' => '25000',
        ],
    ],
));

echo $invoice->invoiceId;
echo $invoice->qrText;
echo $invoice->qrImage;
echo $invoice->qPayShortUrl;

foreach ($invoice->urls as $url) {
    echo "{$url['name']}: {$url['link']}";
}

use QPay\Models\CreateSimpleInvoiceRequest;

$invoice = $client->createSimpleInvoice(new CreateSimpleInvoiceRequest(
    invoiceCode: 'YOUR_INVOICE_CODE',
    senderInvoiceNo: 'ORDER-002',
    invoiceReceiverCode: 'terminal',
    invoiceDescription: 'Simple payment',
    amount: 5000.0,
    callbackUrl: 'https://yoursite.com/callback',
    senderBranchCode: 'BRANCH_01', // optional
));

use QPay\Models\CreateEbarimtInvoiceRequest;

$invoice = $client->createEbarimtInvoice(new CreateEbarimtInvoiceRequest(
    invoiceCode: 'YOUR_INVOICE_CODE',
    senderInvoiceNo: 'ORDER-003',
    invoiceReceiverCode: 'terminal',
    invoiceDescription: 'Invoice with tax receipt',
    taxType: '1',
    districtCode: '01',
    callbackUrl: 'https://yoursite.com/callback',
    lines: [
        [
            'line_description' => 'Product B',
            'line_quantity' => '1',
            'line_unit_price' => '30000',
            'tax_product_code' => '1234',
        ],
    ],
));

$client->cancelInvoice('INVOICE_ID');

$payment = $client->getPayment('PAYMENT_ID');

echo $payment->paymentId;
echo $payment->paymentStatus;   // e.g. "PAID"
echo $payment->paymentAmount;
echo $payment->paymentCurrency; // e.g. "MNT"
echo $payment->paymentWallet;
echo $payment->transactionType;
echo $payment->paymentDate;

use QPay\Models\PaymentCheckRequest;

$result = $client->checkPayment(new PaymentCheckRequest(
    objectType: 'INVOICE',
    objectId: 'INVOICE_ID',
    pageNumber: 1,  // optional
    pageLimit: 10,   // optional
));

echo $result->count;
echo $result->paidAmount;

foreach ($result->rows as $row) {
    echo "{$row['payment_id']}: {$row['payment_status']} ({$row['payment_amount']})";
}

use QPay\Models\PaymentListRequest;

$result = $client->listPayments(new PaymentListRequest(
    objectType: 'INVOICE',
    objectId: 'INVOICE_ID',
    startDate: '2026-01-01',
    endDate: '2026-01-31',
    pageNumber: 1,
    pageLimit: 20,
));

echo $result->count;

foreach ($result->rows as $row) {
    echo "{$row['payment_id']}: {$row['payment_amount']} {$row['payment_currency']}";
}

use QPay\Models\PaymentCancelRequest;

$client->cancelPayment('PAYMENT_ID', new PaymentCancelRequest(
    callbackUrl: 'https://yoursite.com/cancel-callback', // optional
    note: 'Reason for cancellation',                      // optional
));

use QPay\Models\PaymentRefundRequest;

$client->refundPayment('PAYMENT_ID', new PaymentRefundRequest(
    callbackUrl: 'https://yoursite.com/refund-callback', // optional
    note: 'Reason for refund',                            // optional
));

use QPay\Models\CreateEbarimtRequest;

$ebarimt = $client->createEbarimt(new CreateEbarimtRequest(
    paymentId: 'PAYMENT_ID',
    ebarimtReceiverType: 'citizen',
    ebarimtReceiver: 'AA12345678',    // optional
    districtCode: '01',                // optional
    classificationCode: '1234',        // optional
));

echo $ebarimt->id;
echo $ebarimt->barimtStatus;
echo $ebarimt->ebarimtQrData;
echo $ebarimt->ebarimtLottery;
echo $ebarimt->amount;
echo $ebarimt->vatAmount;

$ebarimt = $client->cancelEbarimt('PAYMENT_ID');

echo $ebarimt->barimtStatus;

use QPay\Exceptions\QPayException;

try {
    $client->createSimpleInvoice($request);
} catch (QPayException $e) {
    echo $e->statusCode;    // HTTP status code (0 for network errors)
    echo $e->errorCode;     // QPay error code string
    echo $e->errorMessage;  // Human-readable error message
    echo $e->rawBody;       // Raw response body
    echo $e->getMessage();  // "qpay: ERROR_CODE - message (status 400)"
    echo $e->getCode();     // Same as statusCode
}

use QPay\Exceptions\QPayException;

try {
    $client->cancelInvoice('inv_123');
} catch (QPayException $e) {
    match ($e->errorCode) {
        QPayException::INVOICE_NOTFOUND => handleNotFound(),
        QPayException::INVOICE_ALREADY_CANCELED => handleAlreadyCancelled(),
        QPayException::INVOICE_PAID => handleAlreadyPaid(),
        QPayException::AUTHENTICATION_FAILED => handleAuthError(),
        QPayException::PERMISSION_DENIED => handlePermissionDenied(),
        default => handleUnknownError($e),
    };
}

use GuzzleHttp\Client as HttpClient;

$http = new HttpClient([
    'timeout' => 60,
    'proxy' => 'tcp://localhost:8080',
]);

$client = new QPayClient($config, $http);
bash
composer