Search by

basilbook / canadia

vandetho

Canadia Bank's KHQR gateway for PHP: a KHQR for an amount (string or image), where a payment stands, refunds, and the gateway's signing. Framework-free, PSR-18. The PHP twin of @basilbook/canadia.

v0.1.0 2026-11-15 08:54 UTC

This package is auto-updated.

Last update: 2026-11-17 03:31:49 UTC


README

Canadia Bank's KHQR payment gateway for PHP: a KHQR for an amount from a shop's own Canadia merchant (as the text or as an image), where a payment stands, and refunds. The sign-in token is kept for you. No framework: give it the merchant's login and, if you like, your own PSR-18 HTTP client. Your credentials are passed in, never read from the environment.

Made by BasilBook, MIT licensed; Bill&Go takes its Canadia payments with the npm twin, @basilbook/canadia. The two have the same calls, with the same names, the same results and the same errors, and the tests check PHP signs and sends the very bytes the TypeScript does. The whole family is listed in packages/README.md.

Install

composer require basilbook/canadia guzzlehttp/guzzle

Guzzle is only the default HTTP client; pass your own PSR-18 client and PSR-17 factories to leave it out.

Quick start

use BasilBook\Canadia\CanadiaClient;
use BasilBook\Canadia\Exception\CanadiaRefusedException;
use BasilBook\Canadia\Exception\CanadiaUnreachableException;

$canadia = new CanadiaClient([
    'username' => $login,
    'password' => $password,
    'apiKey'   => $hashKey,      // the merchant's hash key
    'sandbox'  => true,
]);

try {
    $khqr = $canadia->createKhqr(externalId: 'ORD-20261115-0042', amount: 450, currency: 'USD');
} catch (CanadiaRefusedException $e) {
    $e->reason;        // 'duplicate', 'merchant_inactive', ... (see below)
    $e->canadiaCode;   // 'PG_EXTERNAL_ID_EXIST'
} catch (CanadiaUnreachableException) {
    // Canadia did not answer: try again.
}

$khqr->qr;          // the KHQR text to draw
$khqr->expiresAt;   // DateTimeImmutable
$khqr->link;        // Canadia's hosted KHQR page, or null
$khqr->paymentId;   // Canadia's id, beside your externalId

$payment = $canadia->status('ORD-20261115-0042');
$payment->status;     // 'pending' | 'paid' | 'failed' | 'cancelled' | 'expired'
$payment->refNumber;  // what a refund names
$payment->amount;     // minor units, or null

Before settling, check $payment->amount and $payment->currency are what the QR asked for.

A string or an image

Canadia sends the text only. createKhqr(..., format: 'image') also gives $khqr->image, a data URL drawn from the text with Khqr::image from basilbook/khqr:

$khqr = $canadia->createKhqr('ORD-1', 450, 'USD', format: 'image', image: ['size' => 300]);
echo '<img src="' . htmlspecialchars($khqr->image) . '" alt="Scan to pay $4.50">';

A PNG needs ext-gd; ask image: ['type' => 'svg'] for an SVG, which needs nothing.

Money

Every amount is integer minor units plus a currency code: 450 with USD is $4.50, 20900 with KHR is 20,900 riel. Canadia is sent major units (4.5, 20900), and amounts it sends back are turned into minor units again.

Sandbox and production

sandbox: true sandbox: false (default)
Address https://sandbox-pay.canadiabank.com.kh/sandbox https://pay.canadiabank.com.kh/payment-gateway/v2
Money test money real money

baseUrl (a proxy, a test server) wins over both. The paths (/api/authenticate, /tps/api/payment/init, /status, /refund) are joined onto it.

Keeping the login's token

Every call needs the login's token (a JWT from /api/authenticate). The client signs in once, keeps the token until a minute before its exp (five minutes when it has none), and when Canadia says PG_UNAUTHORIZED it signs in again and tries once more.

A PHP app usually makes a new client per request, so keep the token somewhere that lasts by passing a CanadiaTokenStore as tokens:

use BasilBook\Canadia\CanadiaTokenStore;

final class CacheTokenStore implements CanadiaTokenStore
{
    public function __construct(private \Psr\SimpleCache\CacheInterface $cache) {}

    public function get(string $key): ?array { return $this->cache->get('canadia.' . sha1($key)); }
    public function set(string $key, string $token, int $expiresAt): void
    {
        $this->cache->set('canadia.' . sha1($key), ['token' => $token, 'expiresAt' => $expiresAt]);
    }
    public function delete(string $key): void { $this->cache->delete('canadia.' . sha1($key)); }
}

$canadia = new CanadiaClient($config + ['tokens' => new CacheTokenStore($cache)]);

The token is a credential: keep it where the shop's secrets are kept.

The callback

createKhqr(callbackUrl: ...) tells Canadia where to post when the money moves. Canadia's callback is not signed in what we have seen, so treat it as a doorbell: when it rings, ask status($externalId) and settle only on paid with the amount and money you asked for. Put a one-time token of your own in the callback address if you want to know the call is yours.

API reference

All classes are in BasilBook\Canadia. Every exception extends BasilBook\Canadia\Exception\CanadiaException (a RuntimeException).

new CanadiaClient(CanadiaConfig|array $config, ?ClientInterface $http = null, ?RequestFactoryInterface $requests = null, ?StreamFactoryInterface $streams = null)

CanadiaConfig
username, password The merchant's login
apiKey The merchant's hash key; every hash is made with it
sandbox Canadia's sandbox: test money
baseUrl Another base URL (a proxy, a test server); wins over sandbox
timeoutMs 8000 (the default Guzzle client only)
now fn (): DateTimeInterface, the clock (timestamps, token lifetimes)
tokens A CanadiaTokenStore; a CanadiaMemoryTokenStore of the client's own unless given
decimals fn (string $currency): int; riel 0, dollars 2, anything else 2 unless given
log fn (string $level, string $message): info, warn, error; never a secret

CanadiaConfig::fromArray() takes the same keys; print_r shows only the username. No PSR-18 client given and Guzzle not installed: CanadiaConfigException.

Method Returns Throws
createKhqr(string $externalId, int $amount, string $currency, ?string $customerName = null, ?string $callbackUrl = null, string $format = 'string', array $image = []) CanadiaKhqr CanadiaInputException (format; nothing sent), CanadiaRefusedException (no QR in the answer: reason unknown, code NO_QR), CanadiaUnreachableException
status(string $externalId) CanadiaPayment; an expired QR is status expired CanadiaRefusedException, CanadiaUnreachableException
refund(string $refNumber, string $reason, ?int $amount = null, ?string $currency = null) CanadiaRefund. No amount: the whole payment. CanadiaInputException (amount: a partial refund with no currency, or not above zero; nothing sent), CanadiaRefusedException, CanadiaUnreachableException
baseUrl() The base URL in use.
CanadiaClient::hash(string $apiKey, array $values, int $timestampMs) SHA-256 hex of the values run together, then the timestamp, then the key.
CanadiaClient::jwtExpiresAt(string $token) The token's exp in epoch milliseconds, or null.

What each call signs: sign-in [username, password]; init [amount, externalId, currency]; status [externalId]; whole refund [reason, refNumber]; partial refund [reason, refNumber, amount, currency]. Each body carries timestamp (milliseconds, as a string) and hash.

Constants: URL, SANDBOX_URL, PATHS (authenticate, init, status, refund), REFUSALS (Canadia's code => reason, below).

Results

  • CanadiaKhqr: paymentId, qr, expiresAt, link, image.
  • CanadiaPayment: status, refNumber, amount, currency. Constants PENDING, PAID, FAILED, CANCELLED, EXPIRED.
  • CanadiaRefund: refundRef, amount (minor units, or null when Canadia gave none), currency, at.
  • CanadiaTokenStore (interface: get, set, delete) and CanadiaMemoryTokenStore (the default).

Exceptions

Class When Carries
CanadiaInputException What was asked cannot be sent; nothing sent problem: format, amount
CanadiaRefusedException The gateway said no; message Canadia Bank refused the request: <reason> (<code>) reason, canadiaCode
CanadiaUnreachableException No connection, a timeout, or an answer with no readable status status (HTTP, or null)
CanadiaConfigException No HTTP client (PHP only)
Canadia's code reason
PG_UNAUTHORIZED unauthorized
PG_INVALID_REQUEST invalid_request
PG_EXTERNAL_ID_EXIST duplicate
PYM_NOT_FOUND not_found
PG_GET_STATUS_FAILED expired
PG_GENERATE_DEEPLINK_FAILED deeplink
PG_MERCHANT_INACTIVE merchant_inactive
PG_MERCHANT_NOT_EXIST merchant_unknown
PG_MERCHANT_UNAUTHORIZED merchant_unauthorized
PG_SYSTEM_UNDER_MAINTENANCE maintenance
anything else unknown

The same calls as the TypeScript

TypeScript (@basilbook/canadia) PHP
new CanadiaClient(config) new CanadiaClient($config)
createKhqr({ externalId, amount, currency, customerName, callbackUrl, format, image }) createKhqr(externalId:, amount:, currency:, customerName:, callbackUrl:, format:, image:)
status(externalId) status($externalId)
refund({ refNumber, reason, amount, currency }) refund(refNumber:, reason:, amount:, currency:)
client.baseUrl $client->baseUrl()
canadiaHash, jwtExpiresAt CanadiaClient::hash, CanadiaClient::jwtExpiresAt
CanadiaTokenStore, CanadiaMemoryTokenStore the same names
CANADIA_URL, CANADIA_SANDBOX_URL, CANADIA_PATHS, CANADIA_REFUSALS CanadiaClient::URL, SANDBOX_URL, PATHS, REFUSALS
CanadiaInputError, CanadiaRefusedError, CanadiaUnreachableError CanadiaInputException, CanadiaRefusedException, CanadiaUnreachableException

What differs is only how each language says it: a package function (canadiaHash) is a static method with the package word dropped (CanadiaClient::hash); an options object is named arguments with the same names; a getter is a method; fetch is a PSR-18 client; an Error is an Exception; a Date is a DateTimeImmutable; a promise is the value itself.

Not yet confirmed with Canadia

Read from Canadia's developer portal and public samples, not yet from a signed spec: the hash convention (values, then timestamp, then key; hex), paymentTimeoutMillis read as epoch milliseconds, the token's lifetime when it has no exp, and how the paths join the base address. Try the sandbox before going live.

Requirements

  • PHP 8.1 or later, ext-json.
  • A PSR-18 client and PSR-17 factories, or guzzlehttp/guzzle.
  • ext-gd only for a PNG image.

Running the tests

cd packages/php/canadia
composer install       # takes basilbook/khqr from ../khqr
composer test

The tests run against a fake gateway that checks every hash and token as Canadia's portal describes: nothing reaches Canadia. tests/fixtures/ts-vectors.json holds what the TypeScript package sent and how it read each answer; the tests check PHP does the same.

License

MIT, copyright BasilBook. See LICENSE.