nca / kbz-payment-gateway
Reusable KBZ E-commerce Payment Gateway v3.2.1 client with MMQR and signed webhooks
Requires
- php: ^8.0
- ext-filter: *
- ext-hash: *
- ext-json: *
- guzzlehttp/guzzle: ^7.8
Requires (Dev)
None
Suggests
- ext-curl: Recommended for predictable connection timeouts and HTTPS transport
- illuminate/support: Optional Laravel integration: ^8.83 || ^9.0 || ^10.0 || ^11.0 || ^12.0 || ^13.0
Provides
None
Conflicts
- illuminate/support: <8.83 || >=14.0
Replaces
None
README
A reusable PHP client for KBZ E-commerce Payment Gateway v3.2.1. Use it in an online shop, booking system, subscription service or another PHP project.
The package handles bank API requests and webhook verification. Your application owns its customers, orders, database and fulfillment rules. There are no local/remote booking concepts in the package.
Package structure
config/kbzpg.php Laravel environment configuration
src/ Configuration, Gateway, response decoding, webhook verification
src/Laravel/ Optional Laravel service provider
postman/ Token, checkout and query requests for bank UAT
tests/ Offline payment contract tests and syntax checks
.github/workflows/ PHP and Laravel compatibility jobs
README.md Setup, usage and maintenance
1. Install
Requirements: PHP 8.0+ within PHP 8.x, Composer 2 and Guzzle 7.8+. Laravel is optional.
Install the public package inside your application:
composer require "nca/kbz-payment-gateway:^1.0"
Commit your application's composer.lock so deployments use a reviewed version. The package is licensed under the MIT license.
For local package development only, add the sibling package as a path repository:
composer config repositories.kbzpg path ../kbz-payment-gateway
composer require 'nca/kbz-payment-gateway:@dev'
Remove the local path repository before testing an actual Packagist release. Changes committed locally are not available from Packagist until pushed and tagged as a new release.
2. Configure Laravel
Laravel auto-discovers the provider. Publish its config:
php artisan vendor:publish --tag=kbzpg-config
It creates config/kbzpg_sdk.php. Add your KBZ MMS credentials to your application's .env:
KBZPG_ENABLED=true KBZPG_BASE_URL=https://paymentaggregatoruat.kbzbank.com KBZPG_CLIENT_ID=YOUR_CLIENT_ID KBZPG_API_KEY=YOUR_API_KEY KBZPG_WEBHOOK_SECRET=YOUR_WEBHOOK_SECRET KBZPG_MMQR_ENABLED=true KBZPG_KBZPAY_ENABLED=false
Then run php artisan config:clear in your working application environment. Never commit real secrets. This package does not automatically load its own .env into another project.
If auto-discovery is disabled, register Nca\KbzPaymentGateway\Laravel\KbzPaymentGatewayServiceProvider::class in config/app.php for Laravel 8–10 or bootstrap/providers.php for Laravel 11–13.
Available settings
| Setting | Default / purpose |
|---|---|
KBZPG_ENABLED |
true; optional global switch for new checkout |
KBZPG_BASE_URL |
UAT origin; selects the bank environment |
KBZPG_CLIENT_ID |
Empty; merchant identity |
KBZPG_API_KEY |
Empty; token authentication |
KBZPG_WEBHOOK_SECRET |
Empty; webhook HMAC authentication |
KBZPG_TIMEOUT |
20; total HTTP deadline in seconds |
KBZPG_CONNECT_TIMEOUT |
10; connection deadline, at most the total deadline |
KBZPG_CHECKOUT_OPTION |
Empty; optional 0 or channel list, overrides switches |
KBZPG_KBZPAY_ENABLED |
false; channel 1 |
KBZPG_MMQR_ENABLED |
true; channel 2 |
KBZPG_DIRECTPAY_ENABLED |
false; channel 3 |
KBZPG_MPU_ENABLED |
false; channel 4 |
KBZPG_CYBERSOURCE_ENABLED |
false; channel 5 |
Without an explicit checkout option, at least one channel must be enabled. Several selected channels produce a value such as 1,2,4. Merchant activation and hosted payment options are controlled by KBZ.
Optional KBZPG_TOKEN_URL, KBZPG_INITIATE_PAYMENT_URL and KBZPG_QUERY_PAYMENT_URL overrides default to blank. Normally leave them blank: the package derives the three documented paths from the base URL. An explicit override must use the selected bank HTTPS host and exact path.
Production origin: https://paymentaggregatorprod.kbzbank.com. Change credentials together with the environment and clear any explicit UAT URL overrides.
Select KBZPay, MMQR, Direct Pay, MPU or Cybersource
All five channels use the same token → initiate → hosted checkout → webhook/query flow defined by the supplied KBZ guide. You do not need a separate Gateway implementation for each channel.
| Checkout option | Hosted channel |
|---|---|
0 |
Full gateway selection page |
1 |
KBZPay |
2 |
MMQR |
3 |
Direct Pay |
4 |
MPU |
5 |
Cybersource |
1,2,4 |
Selected channels together |
Use one of these approaches:
- Set channel switches in
.env. To use only MPU, enable MPU and explicitly disable the default MMQR switch. - Set
KBZPG_CHECKOUT_OPTION=4for MPU,0for the full page, or1,2,4for several channels. A nonempty explicit option takes precedence over switches. - Pass the optional sixth
initiate()argument for this payment only. It takes precedence over config without changing a shared singleton.
$session = $gateway->initiate('RESERVED-MPU-ORDER', '25000.00', 'Order payment', '0.00', null, '4');
Only 0 alone or channel IDs 1–5 are accepted. Lists are trimmed, deduplicated and sorted. No new field names or wallet-specific payloads are invented.
KBZ must activate the selected channel for your merchant/environment. Switching an option requests that hosted channel; it does not guarantee bank activation or provide a native KBZPay SDK/MiniApp. KBZPay PWA, native-app and dynamic-QR modes are not separate initiation option IDs in this guide. Exercise each activated channel in UAT. Currency remains MMK in this package; a different currency needs a reviewed code/API change, not just a channel option.
3. Create a checkout
In Laravel, resolve the client from the container:
use Nca\KbzPaymentGateway\Gateway; $gateway = app(Gateway::class); $session = $gateway->initiate( 'YOUR_RESERVED_ORDER_ID', '25000.00', 'Order payment' ); return redirect()->away($session['checkoutUrl']);
Before this call, reserve a unique attempt and read its amount from your database. After the call, durably save pgTxnId and checkoutUrl before redirecting. The short example above shows SDK usage; it does not perform these application writes.
Full method signature:
initiate($orderId, $amount, $description = '', $serviceCharges = '0.00', $email = null, $checkoutOption = null)
Use decimal strings for amounts. Payment amount must be positive, with at most 2 decimal places and 10 integer digits. Currency is MMK. The merchant order reference must be unique and at most 50 bytes. Description accepts up to 250 Unicode characters.
The client gets a fresh token automatically, sends the selected channels and validates the returned checkout session. Creating a checkout does not mean the customer has paid.
4. Verify a bank webhook
Register a public HTTPS POST webhook endpoint with KBZ. Use a route that accepts bank requests without customer login or browser CSRF, and authenticate it with the verifier:
use Nca\KbzPaymentGateway\GatewayException; use Nca\KbzPaymentGateway\WebhookVerifier; try { $callback = app(WebhookVerifier::class)->verify( $request->getContent(), (string) $request->header('X-PG-Timestamp'), (string) $request->header('X-PG-Signature') ); } catch (GatewayException $error) { return response()->json(['message' => 'Invalid webhook'], 401); } $isPaid = WebhookVerifier::successful($callback);
The verifier checks the exact raw body, HMAC-SHA256, timestamp within ±300 seconds, required fields and configured merchant. Do not decode/re-encode the body before verification.
After verification, your application must find the saved MerchantOrderId, lock its payment record and validate the stored order/merchant/environment. Only uppercase Code='00' and Status='Success' authorize success. Record it once and commit before returning HTTP 200 with {"status":"ACK"}. Unknown orders should return 404; failed persistence must return non-2xx. Verified failure/pending callbacks must not mark an order paid.
Register a separate GET browser return URL with KBZ. That page displays saved database state. Browser return parameters never authorize payment, and the return may arrive before the webhook.
5. Query an unconfirmed payment
$result = $gateway->query($savedPgTxnId); $isPaid = Gateway::successful($result); $isTerminal = Gateway::terminal($result);
Query success requires lowercase code='00' and status='Success'. Provider code 99 remains unconfirmed. Confirmed success, Fail, Expired, Closed and Cancelled stop normal polling.
Your application waits at least 30 seconds after checkout redirect, queries at least 30 seconds apart and stops after a final result or 3 minutes. Use the same locked settlement service for query and webhook results. The SDK does not run a scheduler. Query remains available when new checkout is disabled.
Plain PHP usage
Laravel is not required. Load Composer and construct the same services directly:
require __DIR__.'/vendor/autoload.php'; use Nca\KbzPaymentGateway\Configuration; use Nca\KbzPaymentGateway\Gateway; use Nca\KbzPaymentGateway\WebhookVerifier; $config = new Configuration([ 'KBZPG_CLIENT_ID' => getenv('KBZPG_CLIENT_ID') ?: '', 'KBZPG_API_KEY' => getenv('KBZPG_API_KEY') ?: '', 'KBZPG_WEBHOOK_SECRET' => getenv('KBZPG_WEBHOOK_SECRET') ?: '', ]); $gateway = new Gateway($config); $verifier = new WebhookVerifier($config);
Supply credentials through your existing environment loader or hosting configuration. PHP does not load .env automatically. For a plain PHP webhook, read php://input once and pass its bytes and the X-PG-* header values to $verifier->verify().
Payment flow
sequenceDiagram
actor Customer
participant App as Your application
participant SDK as KBZ package
participant Bank as KBZ gateway
Customer->>App: Start payment
App->>App: Reserve unique reference and stored amount
App->>SDK: initiate(reference, amount)
SDK->>Bank: Request token and create checkout
Bank-->>SDK: pgTxnId and checkoutUrl
SDK-->>App: Validated session
App->>App: Save pending session
App-->>Customer: Redirect to checkoutUrl
Customer->>Bank: Authorize payment
Bank->>App: Signed webhook
App->>SDK: Verify raw callback
SDK-->>App: Authenticated result
App->>App: Check success and settle once
Loading
Reliability and scaling
- Reserve before sending: commit a unique payment attempt before calling KBZ. Prevent concurrent initiation with database constraints/atomic state changes. Keep the amount immutable.
- Handle uncertainty: an initiation timeout can happen after KBZ creates a session. Keep the reference and reconcile before retrying. The SDK does not auto-retry. If no
pgTxnIdwas returned, the documented query API cannot look up by merchant order ID. - Settle once: share database locking and a processed marker across webhook/query processing. Never downgrade a paid record or fulfill twice. The callback/query model has no amount, so check your immutable local snapshot against the order.
- Deliver reliably: commit an outbox event with payment and let an idempotent worker deliver tickets, goods or email. A database rollback cannot unsend a notification.
- Use shared state: multiple servers need a shared database, query timestamps and queue. The SDK stores no local payment state. Create separate Configuration/Gateway objects for different merchant accounts.
You can inject a GuzzleHttp\ClientInterface into new Gateway($config, $http). Laravel uses the replaceable kbzpg.http_client binding. Keep TLS verification enabled and avoid retry middleware that resends initiation. Restart long-running workers after config/credential changes.
For errors, catch GatewayException. Its operation(), httpStatus() and paymentStateUncertain() methods expose safe metadata. Do not log secrets, bearer tokens, complete checkout URLs or raw callback bodies. Keep business availability rules in your application.
When KBZ or your application changes
The core has no dependency on booking models, routes or a database framework. HTTP transport, response parsing and application settlement are separate. Existing callers still receive the documented array keys.
| Change | Where to change it |
|---|---|
| Your order tables, routes, tickets or business rules | Your application service; the SDK does not own these |
| Default channel or merchant environment | Configuration, then rebuild Laravel config and restart workers |
| Channel for one checkout | Sixth initiate() argument |
Flat versus data response envelope |
Already supported by ResponseDecoder |
| New bank response wrapper/field names | Update the decoder or inject a reviewed ResponseDecoderInterface implementation |
| New bank endpoints/hosts, success semantics or webhook signature protocol | Review the specification and release a tested SDK change |
Extra response fields are preserved. Unknown/malformed responses and conflicting wrapped query error codes never authorize payment. The SDK does not guess renamed success fields: a bank schema change must be reviewed and tested. This intentionally prevents a new error shape from accidentally becoming a paid result.
The optional third Gateway constructor argument accepts a decoder:
$gateway = new Gateway($config, $http, $yourReviewedDecoder);
Its contract is decode(string $body, string $operation, int $httpStatus): array. Return canonical token/initiation/query fields, reject error envelopes and preserve strict success semantics. Prefer adapting a confirmed new wrapper and delegating to the default ResponseDecoder. Never turn arbitrary fields into a success result.
In Laravel, bind Nca\KbzPaymentGateway\ResponseDecoderInterface to your implementation before resolving Gateway. The provider preserves an existing binding. Keep the existing kbzpg.http_client binding for transport customization. Avoid changing either singleton's merchant/decoder during a request in a long-lived worker; build separate instances for separate merchant contexts.
Webhook authentication stays in WebhookVerifier and is not affected by an HTTP response decoder. A bank change to callback fields, headers or HMAC rules needs a reviewed verifier update. Keep raw-body signature checks, merchant matching, strict success gates and application idempotency in place.
To deliver a change to consuming projects: add regression fixtures, run the compatibility tests, commit, push and publish a new version tag. Applications then run composer update nca/kbz-payment-gateway, review their lock-file changes and deploy. Do not edit a published tag or patch installed vendor/ files. New additive decoder/channel features fit a minor release such as 1.1.0; choose the final version after CI review. Updates are controlled deployments, not automatic changes to running payment applications.
Postman and tests
Import both JSON files from postman/. Select KBZ Payment Gateway - UAT, fill local client_id/api_key, and run:
1 token → 2 checkout → browser authorization → wait 30 seconds → 1 fresh token → 3 query.
These requests test the bank directly and do not create application orders. Each initiation creates a new reference. Do not resend initiation just to refresh a token. Check payment_confirmed, not only whether response tests passed. Control the overall 3-minute polling limit yourself.
From the package directory:
composer install
composer lint
composer test
Tests use fake HTTP and never call KBZ. The core is locally checked on PHP 8.0–8.4 (118 assertions each), with 125 assertions in a Laravel 12 provider run. PHP 8.5/8.6 and the other Laravel versions have CI jobs configured but have not been executed here.
| Runtime/framework | Compatibility target | Current local evidence |
|---|---|---|
| Plain PHP | PHP 8.0–8.x, Guzzle 7.8+ | PHP 8.0.30, 8.1.33, 8.2.30, 8.3.30, 8.4.26 |
| Laravel 8.83+ | PHP 8.0–8.1 | CI configured, not run here |
| Laravel 9 | PHP 8.0.2–8.2 | CI configured, not run here |
| Laravel 10 | PHP 8.1–8.3 | CI configured, not run here |
| Laravel 11 | PHP 8.2–8.4 | CI configured, not run here |
| Laravel 12 | PHP 8.2–8.5 | Provider smoke test on PHP 8.4 |
| Laravel 13 | PHP 8.3–8.5 | CI configured, not run here |
PHP 8.5/8.6 core jobs are configured but not executed here. Do not interpret a Composer constraint or workflow file as proof that every matrix combination passed. Framework patch minimums and transitive dependencies still apply. PHP 8.0/8.1 and Laravel 8–11 are end-of-life compatibility targets; choose a maintained runtime for production. Sources: PHP support, Laravel release policy.
The existing NgUwar application currently uses its own App\Services\KBZPaymentGateway, not this Composer client. Reviewing that implementation does not mean the app has been migrated. To adopt this package, keep its booking/settlement layer and deliberately replace only bank transport/verification through an application adapter, then test database transactions and a real UAT payment.
Before production, test a real UAT payment, public callback delivery, duplicate callbacks, query/webhook races and failed fulfillment. Run dependency audits, retain your application's lock file and monitor unresolved payments.
Updating an older copy
The earlier draft included NgUwar-specific local/remote booking switches and application examples. This cleanup removes those concepts and consolidates documentation here.
- Remove
KBZPG_LOCAL_ENABLEDandKBZPG_REMOTE_ENABLEDfrom the package/application configuration where no longer used. Decide order availability in your own application. Configuration::enabled()replacesenabledFor($scope).initiate()no longer takes$scope. Its fourth argument is now$serviceCharges, followed by$email. Remove the old'local'/'remote'argument from callers. Passing it as an amount is rejected before a bank request.- Core namespace, Composer name, Laravel provider and
kbzpg_sdkconfig namespace remain unchanged. - Application scaffolding and separate guide files were removed. The generic Postman collection now contains only the three bank requests.