basilbook / acleda
ACLEDA ToanChet Pay (XPAY) for PHP: a KHQR for a payment (string or image), whether it was paid, refunds, the hash, and one-time callback tokens. Framework-free, PSR-18. The PHP twin of @basilbook/acleda.
Requires
- php: >=8.1
- ext-json: *
- basilbook/khqr: ^0.1
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.8
- phpunit/phpunit: ^10.5 || ^11.0
Suggests
- ext-gd: To draw a KHQR picture (format 'image').
- guzzlehttp/guzzle: Used as the HTTP client when you do not pass a PSR-18 client of your own.
Provides
None
Conflicts
None
Replaces
None
README
ACLEDA Bank's ToanChet Pay (XPAY) for PHP: ACLEDA makes the KHQR for a payment (you get it as the text or as an image), says whether it was paid, and gives money back; with the hash ACLEDA checks and one-time tokens for its callback. 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 ACLEDA payments with the npm twin,
@basilbook/acleda. 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
- Quick start
- A string or an image
- Money
- Sandbox and production
- Verifying the callback
- Refunds
- API reference
- The same calls as the TypeScript
- Not yet confirmed with ACLEDA
- Requirements
- Running the tests
- License
Install
composer require basilbook/acleda 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\Acleda\AcledaClient; use BasilBook\Acleda\Exception\AcledaRefusedException; $acleda = new AcledaClient([ 'loginId' => $loginId, 'password' => $password, 'merchantId' => $merchantId, 'merchantName' => 'LOTUSLIME', // the merchant's name in ACLEDA's addresses 'secretKey' => $secretKey, 'sandbox' => true, // ACLEDA's UAT ]); $token = AcledaClient::callbackToken(); saveCallbackTokenHash('ORD-20261115-0042', AcledaClient::callbackTokenHash($token)); // keep the hash only try { $opened = $acleda->open( txid: 'ORD-20261115-0042', amount: 450, // $4.50 currency: 'USD', description: 'Order 42', lifetimeMin: 5, callbackUrl: AcledaClient::callbackUrl('https://api.example.com/payments/acleda', $token), ); } catch (AcledaRefusedException $e) { echo $e->getMessage(); // ACLEDA's own words when it gave some $e->acledaCode; // its code, or null } $opened->qr; // the KHQR text ACLEDA made: draw it $opened->expiresAt; // Keep these three for status and refunds: $opened->txid; $opened->paymentTokenId; $opened->sessionId; $acleda->status($opened->paymentTokenId, amount: 450, currency: 'USD'); // 'pending' | 'paid', never throws
A string or an image
ACLEDA sends the text only. open(..., format: 'image') also gives $opened->image, a data URL
drawn from the text with Khqr::image from basilbook/khqr; pass
image: ['type' => 'svg', 'size' => 300] to choose how. A PNG needs ext-gd; an SVG needs nothing.
Money
Every amount is integer minor units plus a currency code: 450 with USD is $4.50. ACLEDA is
sent a decimal string in major units, two places for dollars ("4.50", "5.00"). Only US dollars
are taken until ACLEDA confirms riel; a shop that has it confirmed sets
'currencies' => ['USD', 'KHR']. Any other money is refused before a request leaves
(AcledaInputException, problem currency).
Sandbox and production
sandbox: true |
sandbox: false (default) |
|
|---|---|---|
| Payments | https://epaymentuat.acledabank.com.kh unless baseUrl |
baseUrl: the production address ACLEDA gives the merchant |
| Refunds | https://epaymentuat.acledabank.com.kh:8443 unless refundBaseUrl |
refundBaseUrl |
ACLEDA does not publish its production addresses. Until baseUrl is set, a live open throws
AcledaConfigException and sends nothing, and a live status is pending; until
refundBaseUrl is set, a live refund is pending.
Every call goes to <base>/<merchantName>/XPAYConnectorServiceInterfaceImplV2/XPAYConnectorServiceInterfaceImplV2RS/<operation>.
Verifying the callback
ACLEDA's callback carries no signature, so it proves nothing by itself. Put a one-time token in the callback address (above), keep only its hash, and when the callback comes:
$token = $_GET['token'] ?? null; $row = findUnusedCallbackToken(AcledaClient::callbackTokenHash((string) $token)); // by hash if ($row === null || !AcledaClient::verifyCallback($token, $row->tokenHash)) { http_response_code(401); exit; } markTokenUsed($row); // claim it once: a replay must be refused // Then ask ACLEDA itself, the only proof of payment: if ($acleda->status($row->paymentTokenId, $row->amount, $row->currency) === 'paid') { settle($row); }
status says paid only when ACLEDA says success, gives a coreRefNum, and its amount and money
are the ones the QR asked for. Anything else stays pending: confirm by hand.
Refunds
$out = $acleda->refund($opened->txid, $opened->paymentTokenId, $opened->sessionId, 450, 'USD', 'Customer cancelled'); match ($out->kind) { 'refunded' => markRefunded(), 'refused' => tellAPerson($out->code, $out->words), // 334845: not refundable 'pending' => tryAgainLater(), // no answer };
API reference
All classes are in BasilBook\Acleda. Every exception extends
BasilBook\Acleda\Exception\AcledaException (a RuntimeException).
new AcledaClient(AcledaConfig|array $config, ?ClientInterface $http = null, ?RequestFactoryInterface $requests = null, ?StreamFactoryInterface $streams = null)
AcledaConfig |
|
|---|---|
loginId, password, merchantId |
The merchant's login and ACLEDA's merchant ID (merchantID) |
merchantName |
The merchant's path name: ACLEDA's <MERCHANTNAME> in its URLs |
secretKey |
The shared secret the hash is made with |
sandbox |
ACLEDA's UAT instead of production |
baseUrl |
The address for openSessionV2 and getTxnStatus; UAT's for a sandbox client, needed for production |
refundBaseUrl |
The address for refundTxn; UAT's (port 8443) for a sandbox client, needed for production |
currencies |
The monies taken; ['USD'] unless given (fromArray takes 'USD,KHR' too) |
maxExpiryMin |
The longest expiryTime ACLEDA allows, in minutes; 5 unless given |
operationType, terminalId |
Sent on openSessionV2 when given |
timeoutMs |
10000 (the default Guzzle client only) |
now |
fn (): DateTimeInterface, the clock (purchaseDate, 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 |
print_r of a config shows no secret. No PSR-18 client given and Guzzle not installed:
AcledaConfigException.
| Method | Returns | Throws |
|---|---|---|
open(string $txid, int $amount, string $currency, string $description, int $lifetimeMin, string $callbackUrl, string $format = 'string', array $image = []) |
AcledaOpened |
AcledaInputException (format), AcledaConfigException (no production address), AcledaInputException (currency) — all before anything is sent; AcledaUnreachableException, AcledaRefusedException |
status(string $paymentTokenId, int $amount, string $currency) |
'pending'|'paid' |
never |
refund(string $txid, string $paymentTokenId, string $sessionId, int $amount, string $currency, string $reason) |
AcledaRefundOutcome |
never |
currencies() |
The monies taken |
The lifetime is cut to between 1 minute and maxExpiryMin.
Static helpers:
| Method | What it does |
|---|---|
hash(AcledaConfig|array $signer, string ...$parts) |
HMAC-SHA512 with secretKey over merchantId + loginId + password + the parts, upper-case hex. open and refund sign the txid; status signs the paymentTokenId. |
url(string $base, string $merchantName, string $operation) |
The call's address. |
purchaseDate(DateTimeInterface $now) |
UTC YYYYMMDDHHmmss. |
callbackToken() |
32 random bytes, base64url. |
callbackTokenHash(string $token) |
Its SHA-256 hex: what to keep. |
callbackUrl(string $base, string $token) |
$base with token= in its query. |
verifyCallback(?string $token, string $storedHash) |
The token matches the kept hash (constant time). |
Constants: SANDBOX_URL, SANDBOX_REFUND_URL, SERVICE_PATH, NOT_REFUNDABLE ('334845').
Results
AcledaOpened:txid,sessionId,paymentTokenId,qr,expiresAt,image.AcledaRefundOutcome:kind(refunded,refused,pending), and when refusedcodeandwords.
Exceptions
| Class | When | Carries |
|---|---|---|
AcledaInputException |
A money not taken, or a format that is not 'string'/'image'; nothing sent |
problem: currency, format |
AcledaConfigException |
No production address (baseUrl); no HTTP client (PHP only) |
|
AcledaRefusedException |
ACLEDA answered and gave no QR | acledaCode (also getCode()), details |
AcledaUnreachableException |
No answer, an HTTP error, or an unreadable answer | operation |
The same calls as the TypeScript
TypeScript (@basilbook/acleda) |
PHP |
|---|---|
new AcledaClient(config) |
new AcledaClient($config) |
open({ txid, amount, currency, description, lifetimeMin, callbackUrl, format, image }) |
open(txid:, amount:, currency:, description:, lifetimeMin:, callbackUrl:, format:, image:) |
status(paymentTokenId, { amount, currency }) |
status($paymentTokenId, amount:, currency:) |
refund({ txid, paymentTokenId, sessionId }, amount, currency, reason) |
refund($txid, $paymentTokenId, $sessionId, $amount, $currency, $reason) |
client.currencies |
$client->currencies() |
acledaHash, acledaUrl, acledaPurchaseDate |
AcledaClient::hash, url, purchaseDate |
acledaCallbackToken, acledaCallbackTokenHash, acledaCallbackUrl, verifyAcledaCallback |
AcledaClient::callbackToken, callbackTokenHash, callbackUrl, verifyCallback |
ACLEDA_SANDBOX_URL, ACLEDA_SANDBOX_REFUND_URL, ACLEDA_SERVICE_PATH, ACLEDA_NOT_REFUNDABLE |
AcledaClient::SANDBOX_URL, SANDBOX_REFUND_URL, SERVICE_PATH, NOT_REFUNDABLE |
AcledaInputError, AcledaConfigError, AcledaRefusedError, AcledaUnreachableError |
AcledaInputException, AcledaConfigException, AcledaRefusedException, AcledaUnreachableException |
What differs is only how each language says it: a package function (acledaHash) is a static
method with the package word dropped (AcledaClient::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 (ACLEDA's code is acledaCode in both: PHP's Exception
keeps code for itself); a Date is a DateTimeImmutable; a promise is the value itself.
Not yet confirmed with ACLEDA
Taken from ACLEDA's XPAY documents as far as they go, and not yet seen working end to end:
the production addresses; whether riel is taken; the longest expiryTime; the callback field's
name (callbackUrl) and whether it may change per payment; where the status answer puts the
amount (read from xTran.purchaseAmount, else amount; with neither, never paid); the
purchaseDate format; and whether operationType and terminalId are needed. Try UAT first.
Requirements
- PHP 8.1 or later,
ext-json. - A PSR-18 client and PSR-17 factories, or
guzzlehttp/guzzle. ext-gdonly for a PNG image.
Running the tests
cd packages/php/acleda composer install # takes basilbook/khqr from ../khqr composer test
The tests use a fake HTTP client: nothing reaches ACLEDA. 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.