Search by

basilbook / payway

vandetho

ABA PayWay for PHP: a KHQR for an amount (string or image), whether it was paid, refunds, and PayWay's signing. Framework-free, PSR-18. The PHP twin of @basilbook/payway.

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

This package is auto-updated.

Last update: 2026-11-17 03:33:18 UTC


README

ABA PayWay for PHP: a KHQR for an amount from a shop's own PayWay merchant (as the text or as an image), whether it was paid, refunds, and the signing PayWay checks. No framework: give it the merchant's details 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 PayWay payments with the npm twin, @basilbook/payway. The two have the same calls, with the same names, the same results and the same errors, and the tests check PHP sends the very bytes the TypeScript sends. KHQR itself (make, read, md5, image) is basilbook/khqr; the whole family is listed in packages/README.md.

Install

composer require basilbook/payway guzzlehttp/guzzle

Guzzle is only the default HTTP client. With your own PSR-18 client and PSR-17 factories (Symfony HttpClient, Buzz, ...), leave Guzzle out and pass them in.

Quick start

use BasilBook\Payway\PaywayClient;
use BasilBook\Payway\Exception\PaywayRefusedException;

$payway = new PaywayClient([
    'merchantId' => 'ec000262',          // from ABA
    'apiKey'     => $apiKeyFromYourVault,
    'sandbox'    => true,                // ABA's sandbox: test money
]);

try {
    $qr = $payway->generateQr(amount: 450, currency: 'USD', lifetimeMin: 5);   // $4.50
} catch (PaywayRefusedException $e) {
    $e->paywayCode;                      // "23": KHQR is not switched on for this merchant
}

$qr->tranId;       // keep it: PayWay's callback, check and refund all name it
$qr->qr;           // the KHQR text to draw
$qr->expiresAt;    // DateTimeImmutable
$qr->deeplink;     // ABA Mobile's app link for the same phone, or null
$qr->checkoutUrl;  // PayWay's own checkout page for this QR, or null

// Later, until it is paid or it runs out:
$payway->checkQr($qr->tranId);     // 'pending' | 'paid' | 'failed', never throws

print_r($config) shows only the merchant ID; never log the key.

A string or an image

$qr = $payway->generateQr(450, 'USD', 5, format: 'image');
$qr->image;       // 'data:image/png;base64,…'
$qr->imageFrom;   // 'payway' when PayWay sent its own picture, 'drawn' when drawn from the text

With format: 'image' the text is still there (qr). PayWay's own image (its qrImage, in the template you chose, template3_color unless you pass template:) is handed through as it came; when PayWay sends none, the image is drawn from the text with Khqr::image (pass image: ['size' => 300, 'margin' => 2, 'type' => 'svg'] to choose how).

Money

Every amount you give or get back is integer minor units plus a currency code: 450 with USD is $4.50, 20900 with KHR is 20,900 riel. PayWay's QR takes riel and US dollars only; anything else is refused before a request leaves (PaywayInputException, problem currency). PayWay itself is sent major units (4.5, 5, 20900), written as JavaScript writes them so the hash matches.

Sandbox and production

sandbox: true sandbox: false (default)
Address https://checkout-sandbox.payway.com.kh https://checkout.payway.com.kh
Merchant ABA's sandbox merchant the shop's live merchant
Money test money real money

baseUrl (a proxy, a test server) wins over both. Production needs ABA to switch KHQR on for the merchant and to whitelist your server's IP address (code 6 or 102 until it does). Refunds need ABA to set them up and send you the refund key.

Confirmed on ABA's sandbox (2026-11-12): generate-qr, check-transaction-2, the refund request (path, four fields, hash, RSA PKCS#1 v1.5 in 117-byte pieces), its answers and PTL36 / PTL02 / PTL62. Not yet seen in production; qrImage is read when PayWay sends it.

Refunds

Refunds need ABA's RSA public key for refunds (refundKey, a PEM; one pasted in one line is fine).

$payway = new PaywayClient(['merchantId' => 'ec000262', 'apiKey' => $apiKey, 'refundKey' => $abaRefundPem, 'sandbox' => true]);

$payway->checkRefundDetails()->ok;              // true when the API key and refund key both work

$before = $payway->refundedSoFar($tranId, 'USD');     // minor units, or null: then send nothing
$out = $payway->refund($tranId, 450, 'USD');
match ($out->kind) {
    'refunded'  => markRefunded(),
    'refused'   => tellAPerson($out->code, $out->words),   // never try it again unchanged
    'no_answer' => tryAgainLater(),                        // PTL168, a 5xx, no answer
};

Ask refundedSoFar before every refund, so one sent before a crash is never sent twice. A refund with no refund key, or one that is not an RSA public key, throws PaywayConfigException and sends nothing: fix the key, do not try again.

Callbacks

ABA PayWay posts to your callback when a payment moves. Treat it as a doorbell: ask checkQr($tranId) before you settle anything, and settle only on paid.

API reference

All classes are in BasilBook\Payway. Every exception extends BasilBook\Payway\Exception\PaywayException (a RuntimeException).

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

PaywayConfig
merchantId ABA's merchant ID (merchant_id)
apiKey The merchant's API key; every hash is made with it
refundKey ABA's RSA public key for refunds, PEM; only refunds need it
sandbox true: https://checkout-sandbox.payway.com.kh; else https://checkout.payway.com.kh
baseUrl Another host (a proxy, a test server); wins over sandbox
timeoutMs 10000 (the default Guzzle client only)
now fn (): DateTimeInterface, the clock (req_time, expiry)
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

PaywayConfig::fromArray() takes the same keys. No PSR-18 client given and Guzzle not installed: PaywayConfigException.

Method Returns
generateQr(int $amount, string $currency, int $lifetimeMin, ?string $tranId = null, string $format = 'string', array $image = [], ?string $template = null) PaywayQr generate-qr, KHQR only (abapay_khqr). Throws PaywayInputException (format, then currency; nothing sent), PaywayRefusedException, PaywayUnreachableException
checkQr(string $tranId) 'pending'|'paid'|'failed' check-transaction-2. Never throws
checkTransaction(string $tranId, ?string $currency = null) ?PaywayTransaction Null on no clear answer. refunded is read when $currency is given. Never throws
refundedSoFar(string $tranId, string $currency) ?int Minor units already given back. Never throws
refund(string $tranId, int $amount, string $currency) PaywayRefundOutcome The refund API. PaywayConfigException when the refund key is missing or not an RSA public key; never throws otherwise
checkRefundDetails(?string $probeTranId = null) PaywayRefundCheck A probe refund for a transaction that does not exist; PTL36 is the yes. Never throws
baseUrl() string The host in use

payment_status_code reads as: 0 paid, 3 or 7 failed, anything else pending (4 is refunded: refunded says how much).

Static helpers, public so a test (or another client) can make the same bytes:

Method What it does
hash(string $apiKey, array $fields) base64(HMAC-SHA512(fields joined with nothing, the API key)): PayWay's hash.
reqTime(?DateTimeInterface $now = null) PayWay's req_time: UTC YYYYMMDDHHmmss.
merchantAuth(string|OpenSSLAsymmetricKey $key, array $payload) The refund's JSON, RSA PKCS#1 v1.5 in pieces of the key size less 11 bytes, base64. PaywayConfigException when not an RSA public key.
refundPublicKey(string $pem) ABA's refund key as an OpenSSLAsymmetricKey (SPKI or PKCS#1, pasted in one line or not), or null.
refundPem(string $pasted) A pasted key back into PEM lines, or null.
tranId(string $prefix = 'bq', int|DateTimeInterface|null $now = null) 20 characters: prefix, base-36 time, random.
abaDeeplink(mixed $value) The value when it is ABA Mobile's scheme or https on ababank.com or payway.com.kh, else null.
checkoutUrl(mixed $value) The value when it is exactly https:// on payway.com.kh (no user, no port, not even :443), else null.
takes(string $currency) KHR or USD.

Both link filters trim the ends and then refuse a link with a space, a tab or any other control character, anything outside printable ASCII, or a backslash anywhere in it: a reply is never trusted to send a payer somewhere else.

Constants: URL, SANDBOX_URL, CURRENCIES, PATHS (generateQr, checkTransaction, refund), REFUND_WORDS (PayWay's refund codes in words for a person), REFUND_RETRY (PTL168, 11, 429: try again).

Results

  • PaywayQr: tranId, qr, expiresAt (DateTimeImmutable), deeplink, checkoutUrl, image (a data URL with format 'image'), imageFrom ('payway' or 'drawn').
  • PaywayTransaction: status, paymentStatusCode, paymentStatus, refunded (minor units or null), data (the whole data PayWay sent).
  • PaywayRefundOutcome: kind (refunded, refused, no_answer), and when refused code and words.
  • PaywayRefundCheck: ok, and when not, problem (refund_key_bad, no_answer, refused_key, refused_merchant, not_set_up, refused) and code.

Exceptions

Class When Carries
PaywayInputException Not riel or dollars, or a format that is not 'string'/'image'; nothing sent problem: currency, format
PaywayRefusedException generate-qr answered no (1 API key, 6/102 server not whitelisted, 12 money, 23 KHQR off, 44 over the limit, 47 under 100 riel, 96 unknown merchant) paywayCode (also getCode()), paywayMessage
PaywayUnreachableException generate-qr got no answer, or not JSON status
PaywayConfigException No refund key for a refund, a key that is not RSA, no HTTP client

The same calls as the TypeScript

TypeScript (@basilbook/payway) PHP
new PaywayClient(config) new PaywayClient($config)
generateQr({ amount, currency, lifetimeMin, tranId, format, image, template }) generateQr(amount:, currency:, lifetimeMin:, tranId:, format:, image:, template:)
checkQr, checkTransaction, refundedSoFar, refund, checkRefundDetails the same names
client.baseUrl $client->baseUrl()
paywayHash, paywayReqTime, paywayMerchantAuth, paywayRefundPublicKey, paywayRefundPem, paywayTranId PaywayClient::hash, reqTime, merchantAuth, refundPublicKey, refundPem, tranId
abaDeeplink, paywayCheckoutUrl, paywayTakes PaywayClient::abaDeeplink, checkoutUrl, takes
PAYWAY_URL, PAYWAY_SANDBOX_URL, PAYWAY_CURRENCIES, PAYWAY_PATHS, PAYWAY_REFUND_WORDS, PAYWAY_REFUND_RETRY PaywayClient::URL, SANDBOX_URL, CURRENCIES, PATHS, REFUND_WORDS, REFUND_RETRY
PaywayInputError, PaywayRefusedError, PaywayUnreachableError, PaywayConfigError PaywayInputException, PaywayRefusedException, PaywayUnreachableException, PaywayConfigException

What differs is only how each language says it: a package function (paywayHash) is a static method with the package word dropped (PaywayClient::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, with the same properties (PayWay's code is paywayCode in both: PHP's Exception keeps code for itself); a Date is a DateTimeImmutable; a promise is the value itself. The TypeScript also has a send hook (and paywayPost) to reach PayWay its own way; here a PSR-18 client of your own does that.

Requirements

  • PHP 8.1 or later, ext-json, ext-openssl (refunds).
  • A PSR-18 client and PSR-17 factories, or guzzlehttp/guzzle.
  • ext-gd only to draw a PNG when PayWay sends no picture.

Running the tests

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

The tests use a fake HTTP client: nothing reaches ABA. tests/fixtures/ts-vectors.json holds the requests the TypeScript package sent and how it read each answer; the tests check PHP does the same. PayWay's refund tests make a fresh RSA key each run; the vectors carry one public key only, made once, whose private half was never kept.

License

MIT, copyright BasilBook. See LICENSE.