diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3d93dcf --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +* text=auto eol=lf +*.php diff=php +/tests export-ignore +/scripts export-ignore +/SPEC_VERSION export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.github export-ignore +/phpstan.neon.dist export-ignore +/phpunit.xml.dist export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6c60ae8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4', '8.5'] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 (2.40.0) + with: + php-version: ${{ matrix.php }} + extensions: json, hash, mbstring + coverage: none + tools: composer:v2 + + - name: Validate composer.json + run: composer validate --strict + + - name: Install dependencies + run: composer install --no-interaction --no-progress --prefer-dist + + - name: Dependency advisories + run: composer audit + + - name: Vectors match selcom-spec at SPEC_VERSION + run: bash scripts/check-spec.sh + + - name: Static analysis (PHPStan, max level) + run: composer analyse + + - name: Tests (spec vectors, unit tests; the sandbox test is skipped) + run: composer test + + - name: Build (the package archive) + run: composer archive --format=zip --dir=build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ab2c4c4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor/ +/composer.lock +.phpunit.cache/ +.phpunit.result.cache +/build/ +.idea/ +.vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0ea2a15 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [0.1.0] - 2026-11-21 + +First release. + +### Added + +- Configuration with an explicit environment (no default), credentials held outside the objects that use them (the API key prints its last 4 characters), per-profile timeouts, and an optional second credential set for checkout. +- A pure request signer (flattening, value text, `Signed-Fields`, query string or JSON body) with a pluggable digest signer and HS256. +- A replaceable `Transport` interface and a PSR-18 default using `php-http/discovery` for the factories and a Guzzle client per timeout profile, or your own client (a per-profile closure, or a ready client with `clientManagesTimeouts: true`). Payments and writes use a fresh connection and are never retried. `NOT_SENT` / `UNKNOWN_OUTCOME` classification from cURL request-byte counters, error numbers and connect-phase messages. +- A client with typed request and result objects for the 16 v1 operations: checkout, utility payments, wallet cash-in and vendor balance. Amounts accept an int, a digit string or an integral float. +- The five typed statuses (`SUCCESS`, `PENDING`, `AMBIGUOUS`, `FAILED`, `NOT_FOUND`) with the raw HTTP status and body. +- A webhook verifier following selcom-spec v0.2.1 (`order_id` and `transid` signed, no `&` in signed names or values, bounded number handling, replay entries kept until max(now, signed time) + window), a replay store interface, `ReplayStoreException` for store failures (answer 5xx), and payload parsing with strict amount parsing. +- A redaction helper for logs. +- Secret parameters marked `#[\SensitiveParameter]`; masked output for `var_dump`, `print_r`, `var_export` and array casts. +- Tests that run every case, reject, response scenario and webhook sample of selcom-spec v0.2.1 (copy in `tests/vectors`, recorded in `SPEC_VERSION`, refreshed by `scripts/refresh-spec.sh`, checked by `scripts/check-spec.sh`), plus an opt-in sandbox test. +- GitHub Actions CI on PHP 8.2, 8.3, 8.4 and 8.5: `composer validate --strict`, `composer audit`, vectors match the spec, PHPStan (max level, strict rules), tests and a package build. Actions are pinned to commit SHAs. + +[Unreleased]: https://github.com/selcom-developers/selcom-php/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/selcom-developers/selcom-php/releases/tag/v0.1.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..18a3a2e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing + +Thanks for helping. This is a community client for the Selcom API gateway, and it is **not affiliated with Selcom Paytech Ltd.** + +## Ground rules + +- **The spec is the source of truth.** Signing, result codes, retries and webhooks are defined in [selcom-spec](https://github.com/selcom-developers/selcom-spec). If this client and the spec disagree, the client is wrong, or the spec needs a fix that every client then picks up: open the spec change first. +- **Clean room.** Write your own code. Do not copy from Selcom's official clients or from other Selcom libraries. Reading them to understand behaviour is fine. +- **No secrets and no real data.** Tests use made-up values only: phones `2557000000xx`, IDs like `ORD-1001` and `TXN-...`, keys like `test-key-0001`, or the sample values printed in Selcom's public documentation. Never commit credentials, customer data or details of any merchant's integration. +- **No automatic retry of payments or writes.** This is a hard rule. + +## Development + +Requires PHP 8.2 or later and Composer. + +``` +composer install +composer test # PHPUnit +composer analyse # PHPStan, max level +``` + +Both must pass on PHP 8.2 to 8.5 (CI runs the matrix). Keep the public API small and stable: the classes listed in the README's "Public API" section follow semantic versioning. + +## Spec vectors + +The tests run the shared vectors from a copy in `tests/vectors`. To move to another spec tag: + +``` +scripts/refresh-spec.sh v0.2.0 +``` + +This rewrites `tests/vectors` and `SPEC_VERSION`. Never edit the vectors by hand. + +## Pull requests + +- One concern per pull request. Add or update tests, and add a line under "Unreleased" in `CHANGELOG.md`. +- Describe the behaviour change and, where the language makes a spec rule awkward, how you handled it. +- Releases, tags and publishing are done by the maintainers. + +By contributing you agree that your work is licensed under the Apache License 2.0. diff --git a/README.md b/README.md index e44c86f..ba96f41 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,457 @@ # selcom-php -Framework-agnostic PHP client for the Selcom API gateway: signing, checkout, payouts, webhooks. Not affiliated with Selcom Paytech Ltd. + +Framework-agnostic PHP client for the Selcom API gateway: request signing, checkout, payouts and webhooks. + +> **Not affiliated with Selcom Paytech Ltd.** This is a community project, written from scratch under the Apache License 2.0. "Selcom" names the API it talks to. For API access, credentials, contracts and support, go to Selcom: . Where this README and Selcom's portal disagree about the API, the portal wins. + +Every layer is usable on its own and replaceable: the **signer** is a pure function, the **transport** is an interface, the **client** gives one typed method per operation, **results** carry both a typed status and the raw response, and the **webhook verifier** and **redactor** stand alone. + +The rules this client follows (signing, result codes, retries, webhooks) live in the shared spec: (this release is tested against `v0.2.1`, recorded in [`SPEC_VERSION`](SPEC_VERSION)). + +## Contents + +- [Install](#install) +- [IP whitelisting](#ip-whitelisting) +- [Quickstart](#quickstart) +- [Public API](#public-api) +- [Configuration](#configuration) +- [Operations](#operations) +- [Results and statuses](#results-and-statuses) +- [Error handling](#error-handling) +- [Idempotency, retries and reconciliation](#idempotency-retries-and-reconciliation) +- [Webhooks](#webhooks) +- [Transport](#transport) +- [Signing on its own](#signing-on-its-own) +- [Redacting logs](#redacting-logs) +- [Security](#security) +- [Testing](#testing) + +## Install + +Requires PHP 8.2 or later (CI runs 8.2, 8.3, 8.4 and 8.5). There is no framework dependency. + +``` +composer require selcom-developers/selcom-php +``` + +The HTTP layer is PSR-18, with PSR-17 factories found through [`php-http/discovery`](https://docs.php-http.org/en/latest/discovery.html). The default transport builds a [Guzzle](https://docs.guzzlephp.org/) client for each timeout profile, so the simplest setup is: + +``` +composer require guzzlehttp/guzzle +``` + +Any other PSR-18 client works too, but its timeouts are yours to set: pass a closure that builds one client per timeout profile, or pass the client with `clientManagesTimeouts: true` to confirm it applies them. A ready client without that flag is refused. See [Transport](#transport). + +## IP whitelisting + +Selcom's gateway accepts requests only from server IP addresses that Selcom has whitelisted (allowlisted) for your account. Sandbox and production are whitelisted separately. + +- Before your first call, send Selcom the public outbound (egress) IP address of every server that will call the API, for each environment you use. +- Hosts without a fixed outbound address (serverless functions, autoscaling containers, many platform defaults, home or office connections) need a static egress IP, for example through a NAT gateway or a proxy. +- When servers or hosting change, ask Selcom to update the list before you move traffic. +- A request from an address that is not whitelisted is rejected by the gateway, and Selcom does not document the exact response. If your first sandbox call fails, check the whitelisting first. Treat such a rejection as a configuration problem, never as a payment outcome, and never pay again because of it. + +## Quickstart + +```php +use SelcomDevelopers\Selcom\Client; +use SelcomDevelopers\Selcom\Config; +use SelcomDevelopers\Selcom\Credentials; +use SelcomDevelopers\Selcom\Environment; +use SelcomDevelopers\Selcom\Request\OrderStatusRequest; +use SelcomDevelopers\Selcom\Request\UtilityPaymentRequest; +use SelcomDevelopers\Selcom\Status; + +$config = new Config( + environment: Environment::Sandbox, // required: there is no default + credentials: new Credentials( + apiKey: getenv('SELCOM_API_KEY'), + secret: getenv('SELCOM_API_SECRET'), + vendor: getenv('SELCOM_VENDOR'), + pin: getenv('SELCOM_PIN'), // needed by payout operations only + ), +); + +$client = new Client($config); // default transport: a Guzzle client per timeout profile + +// Persist the transid BEFORE you call (see "Idempotency"), then: +$result = $client->utilityPayment(new UtilityPaymentRequest( + transid: 'TXN-UTL-0001', + utilityCode: 'LUKU', + utilityRef: '01234567891', + amount: 8000, // whole TZS +)); + +switch ($result->status) { + case Status::Success: /* paid; $result->receipt() may hold a token */ break; + case Status::Failed: /* it did not happen */ break; + case Status::Pending: + case Status::Ambiguous: /* unknown: query later, never resubmit */ break; + case Status::NotFound: /* only on queries */ break; +} +``` + +## Public API + +The public surface is small on purpose, so that a framework package can sit on top of it. Everything is in the `SelcomDevelopers\Selcom` namespace. + +| Piece | Classes | What it is | +|---|---|---| +| Config | `Config`, `Credentials`, `Environment`, `Transport\Timeouts`, `Transport\TimeoutProfile` | Validated at construction. `Config::fromArray()` builds one from a framework config array. | +| Signer | `Signing\RequestSigner`, `Signing\DigestSigner`, `Signing\Hs256DigestSigner`, `Signing\SignedRequest`, `Signing\Timestamp` | Pure signing: no I/O, no clock. The digest step is an interface, so RS256 can be added later. | +| Transport | `Transport\Transport`, `Transport\Psr18Transport`, `Transport\TransportRequest`, `Transport\TransportResponse`, `Transport\TransportFailure`, `Transport\FailureClassifier` | Replaceable HTTP layer, with one PSR-18 default. | +| Client | `Client` | One typed method per operation, plus `execute()`. | +| Requests | `Request\*Request`, `Request\Address`, `Request\PaymentMethod`, `Currency` | One typed request class per operation. | +| Results | `Result\Result` and subclasses, `Status`, `Result\ResponseClassifier` | Typed status plus code, text, HTTP status, decoded data and raw body. | +| Webhooks | `Webhook\WebhookVerifier`, `Webhook\WebhookVerdict`, `Webhook\WebhookPayload`, `Webhook\ReplayStore`, `Webhook\InMemoryReplayStore` | Verify a delivery, parse it. | +| Redactor | `Redaction\Redactor` | Safe-to-log copies of headers, bodies and query strings. | +| Errors | `Exception\*` (all implement `Exception\SelcomException`) | See [Error handling](#error-handling). | + +Semantic versioning applies to these classes from the first release. Classes marked `@internal` (`Request\Check`) are not part of the API. + +## Configuration + +```php +$config = new Config( + environment: Environment::Production, + credentials: new Credentials($apiKey, $secret, $vendor, pin: $pin), + checkoutCredentials: null, // optional second credential set for checkout operations + timeouts: new Timeouts(), // defaults below + timezone: new DateTimeZone('Africa/Dar_es_Salaam'), + maxNotSentRetries: 0, // opt-in, read-only operations only +); +``` + +- **The environment is required.** There is no default, and in particular no production default: `Config::fromArray()` without `environment` throws `ConfigurationException`. + + | Environment | Base URL | + |---|---| + | `Environment::Production` | `https://apigw.selcommobile.com` | + | `Environment::Sandbox` | `https://apigwtest.selcommobile.com` | + +- **A custom base URL** (a simulator or a proxy) is its own explicit step: `$config = $config->withBaseUrl('http://localhost:8080')`. It never replaces a preset silently. +- **Credentials.** The API key, the secret and the vendor (till) ID are required and checked at construction, not on the first request. The float PIN is needed by payout operations only; a payout without one fails with `ValidationException` before anything is sent. A merchant may use separate credentials for checkout: pass `checkoutCredentials`, and checkout operations use them. +- **Secrets stay out of output.** `var_dump`, `print_r`, `var_export`, array casts, serialisation and exception messages show none of the secret, the PIN, `Authorization` or `Digest`; the API key shows only its last 4 characters. Secret parameters are marked `#[\SensitiveParameter]`, so they are also left out of stack traces. +- **Timeouts** are per profile, and no request runs without one: + + | Profile | Used by | Connect | Read | + |---|---|---|---| + | query | status queries, order status, everything that moves no money | 10 s | 10 s | + | payment | money-moving operations | 15 s | 180 s | + + The long read timeout on payments is deliberate. Timing out early does not stop the payment; it turns a known answer into an unknown one. Change them with `new Timeouts(new TimeoutProfile(10, 10), new TimeoutProfile(15, 180))`. See [Transport](#transport) for how they reach the HTTP client. +- **Timestamps** are generated from the clock you give the client (a PSR-20 `ClockInterface`; the default is the system clock) in the `Africa/Dar_es_Salaam` zone (`+03:00`), in the colon form `2026-11-21T10:30:46+03:00`. The gateway rejects requests whose time is too far from its own clock, so keep the server clock synchronised. +- **Settings from an array**, as a framework config file would give them: + + ```php + Config::fromArray([ + 'environment' => 'sandbox', // required + 'api_key' => '...', 'secret' => '...', 'vendor' => '...', 'pin' => '...', + 'checkout' => ['api_key' => '...', 'secret' => '...'], // optional + 'base_url' => null, 'timezone' => 'Africa/Dar_es_Salaam', + 'max_not_sent_retries' => 0, + 'timeouts' => ['query_connect' => 10, 'query_read' => 10, 'payment_connect' => 15, 'payment_read' => 180], + ]); + ``` + +## Operations + +One method per operation. Submitting and querying are separate methods: nothing hides a query inside a submit. Amounts are whole units. Request classes accept an `int`, a string of digits or an integral float, and refuse anything else (a fraction, a negative, zero, more than 9007199254740991) with a `ValidationException`; nothing is rounded or truncated. The signer applies the same rule to raw parameters. + +### Checkout + +| Method | Request | Returns | Notes | +|---|---|---|---| +| `createOrder` | `CreateOrderRequest` | `CreateOrderResult` | Any enabled method, cards included. Send the full `Address` billing group for any order that may be paid by card. URLs are given in plain form and base64-encoded for you. | +| `createOrderMinimal` | `CreateOrderMinimalRequest` | `CreateOrderResult` | Non-card orders: first step of a USSD push. | +| `walletPayment` | `WalletPaymentRequest` | `Result` | Push a USSD prompt for an order. **Money-moving.** Normally `PENDING`. | +| `cardPayment` | `CardPaymentRequest` | `Result` | Charge a stored card. **Money-moving.** Normally `PENDING`. | +| `orderStatus` | `OrderStatusRequest` | `OrderStatusResult` | The source of truth for checkout. | +| `cancelOrder` | `CancelOrderRequest` | `Result` | A successful cancel proves the order was never paid. | +| `listOrders` | `ListOrdersRequest` | `ListOrdersResult` | Orders in a date range, for reconciliation. | +| `storedCards` | `StoredCardsRequest` | `StoredCardsResult` | Card tokens are sensitive: never log them. | +| `deleteCard` | `DeleteCardRequest` | `Result` | | + +```php +$order = $client->createOrderMinimal(new CreateOrderMinimalRequest( + orderId: 'ORD-1001', + buyerEmail: 'buyer@example.com', + buyerName: 'Test Buyer', + buyerPhone: '255700000001', + amount: 8000, + currency: Currency::TZS, // always explicit + noOfItems: 1, + webhookUrl: 'https://shop.example.com/selcom/webhook/', +)); + +$created = $order->order(); // CreatedOrder|null: paymentToken, qr, paymentGatewayUrl (decoded) ... + +$push = $client->walletPayment(new WalletPaymentRequest('TXN-WLT-0001', 'ORD-1001', '255700000001')); +// If this fails outright (a not-sent error or FAILED), cancel the order on a best-effort basis so it +// cannot be paid later by surprise: $client->cancelOrder(new CancelOrderRequest('ORD-1001')). + +$status = $client->orderStatus(new OrderStatusRequest('ORD-1001')); +$status->status; // the verdict on the ORDER (from payment_status) +$status->order()?->amount; // whole TZS, strictly parsed +``` + +`paymentGatewayUrl` is decoded from the gateway's base64 for you; the raw value stays in `paymentGatewayUrlRaw`. + +### Payouts + +Payouts spend from the merchant's float account and are authorised with the vendor and the float PIN. + +| Method | Request | Returns | Notes | +|---|---|---|---| +| `utilityPayment` | `UtilityPaymentRequest` | `PayoutResult` | Bills and prepaid services. **Money-moving.** | +| `utilityLookup` | `UtilityLookupRequest` | `LookupResult` | Check a reference before paying. | +| `utilityQuery` | `UtilityQueryRequest` | `PayoutResult` | Verdict on an earlier payment, by `transid`. | +| `walletCashin` | `WalletCashinRequest` | `PayoutResult` | Credit a mobile wallet. **Money-moving.** | +| `walletNameLookup` | `WalletNameLookupRequest` | `LookupResult` | Registered name on a wallet. | +| `walletCashinQuery` | `WalletCashinQueryRequest` | `PayoutResult` | Verdict on an earlier cash-in, by `transid`. | +| `vendorBalance` | `VendorBalanceRequest` | `BalanceResult` | Moves no money; `balance()` is whole TZS. | + +Payouts are TZS only and carry no currency field. + +`$client->execute($request)` is the generic entry point the typed methods use: it takes any `OperationRequest` and returns the matching `Result`. + +## Results and statuses + +Every operation returns a `Result` with: + +| Field | Content | +|---|---| +| `status` | `Status::Success`, `Pending`, `Ambiguous`, `Failed` or `NotFound` (backed by `SUCCESS`, `PENDING`, `AMBIGUOUS`, `FAILED`, `NOT_FOUND`) | +| `resultCode` | The normalised code, or `null` when there was no verdict | +| `result`, `message` | The gateway's text, unchanged | +| `reference` | The gateway's reference, when present | +| `transid`, `orderId` | The ID this result is about | +| `httpStatus` | The HTTP status code. It does not decide the verdict | +| `data` | The decoded `data` array, raw values kept. Typed accessors on the subclasses | +| `raw` | The body exactly as received. Redact before logging | + +`isFinal()` is true for `SUCCESS`, `FAILED` and `NOT_FOUND`. + +The status comes from `resultcode` only (`000` success; `111` and `927` in progress; `999` ambiguous; `404` on a status query is `NOT_FOUND`; anything else failed). The text fields are for people. For `orderStatus` the verdict is the order's `payment_status`, not the query's code. The full table and the edge cases are in the spec's [results.md](https://github.com/selcom-developers/selcom-spec/blob/v0.2.1/docs/results.md). + +| Status | Meaning | What you may do | +|---|---|---| +| `SUCCESS` | It happened | Fulfil (after confirming a webhook with `orderStatus`) | +| `PENDING` | Accepted, still processing | Wait for the webhook, or query after 3 minutes or more | +| `AMBIGUOUS` | Nobody knows yet | Query after 3 minutes or more. **Never resubmit** | +| `FAILED` | It did not happen | Report it. A new attempt is a new transaction with a new ID, and your decision | +| `NOT_FOUND` | The gateway has no record of the ID | The only case in which the same ID may be submitted again | + +A response that arrives without a verdict (an HTML error page from a proxy, an empty body) is `AMBIGUOUS` for payments and queries, because the money may have moved, and raises `InvalidResponseException` for operations that move no money. + +`ResponseClassifier::classify($kind, $httpStatus, $rawBody)` is the same logic as a pure function, if you want to classify a response yourself. + +## Error handling + +All exceptions implement `Exception\SelcomException`. + +| Exception | When | Was anything sent? | +|---|---|---| +| `ConfigurationException` | Missing or invalid configuration, at construction | No | +| `ValidationException` | A request object was built with a bad field, or a payout has no PIN | No | +| `SigningException` | The request cannot be signed (`->errorCode`: `EMPTY_SECRET`, `INVALID_TIMESTAMP`, `NON_INTEGER_NUMBER`, ...) | No | +| `TransportException` | No HTTP response arrived | See `->failure` | +| `InvalidResponseException` | A response with no verdict, on an operation that moves no money | Yes | + +**Fail closed.** If signing fails, nothing is sent. The client never sends a request with an empty or missing `Digest`. + +**Transport errors say what they mean.** `TransportException::$failure` is a `TransportFailure`: + +- `NotSent`: DNS failure, connection refused, connect timeout, TLS handshake failure. The request provably never reached the gateway; sending it again with the same ID is safe. +- `UnknownOutcome`: anything after the request may have been written (read timeout, reset, truncated response). The gateway may have acted. **Treat it exactly like `AMBIGUOUS`: query, never resend.** When the HTTP library cannot tell which case it is, the answer is `UnknownOutcome`. + +A transport error is never turned into `FAILED`. + +## Idempotency, retries and reconciliation + +The client is stateless between calls: it does not lock, queue or deduplicate. Staying safe is your side of the contract. + +**The ID is the idempotency key.** `transid` identifies a payout or a payment attempt; `order_id` identifies a checkout order. The gateway refuses a second transaction with an ID it has seen. The maximum length and characters are not published, so keep IDs to 30 characters or fewer using `A-Z a-z 0-9 -`. + +**What the client retries.** Nothing, by default. It **never** retries a payment or a write (create order, cancel, delete card), not after a timeout and not with the same ID. For read-only operations (queries, lookups, balance, list, stored cards) you may opt in with `maxNotSentRetries`, which repeats a request only after a `NotSent` error, with the same parameters and a fresh timestamp. + +**Before you call a money-moving method:** + +1. Generate the ID deterministically from your own records (for example the payout row's primary key with a prefix), so that a crash and restart produces the same ID. +2. Persist the ID, with a "submitting" state, **before** calling the gateway. After a crash, reconcile anything left in that state by querying. +3. Put a unique constraint on the ID, so that a retried job cannot create a second transaction. + +**After the call:** + +- `SUCCESS` or `FAILED` is final. +- `PENDING`, `AMBIGUOUS` or a `TransportException` with `UnknownOutcome`: wait at least 3 minutes, then query with the same ID (`utilityQuery` or `walletCashinQuery` by `transid`; `orderStatus` by `order_id`). If it is still unsettled, query again every 3 minutes for a bounded window you choose. If it never settles, hand it to a person to raise with Selcom support, with the `transid` and `reference`. +- **Never mint a new ID while an outcome is unknown.** A new ID is a new transaction. +- **Resubmit the same ID only after `NOT_FOUND`**, or after a `NotSent` error. If the original did arrive in the meantime, the gateway refuses the duplicate. +- Apply results under a row lock or a compare-and-set (`UPDATE ... WHERE status NOT IN (final states)`), so that a webhook and a poll arriving together cannot both win, and never let a later result change a final state. +- To close a checkout order as failed for good, cancel it: a completed order cannot be cancelled, so a successful `cancelOrder` proves it was never paid. A `FAILED` order status alone is not enough, because an unexpired order can still be paid by a later attempt. + +## Webhooks + +A webhook is a **hint, not proof**. Never fulfil an order because a webhook said so: confirm with `orderStatus` first, every time, and take the amount from there. + +```php +use SelcomDevelopers\Selcom\Webhook\WebhookPayload; +use SelcomDevelopers\Selcom\Webhook\WebhookVerdict; +use SelcomDevelopers\Selcom\Webhook\WebhookVerifier; + +$verifier = new WebhookVerifier( + secret: $secret, + replayStore: $sharedReplayStore, // a ReplayStore over APCu or Redis; the default is per-process + windowSeconds: 300, +); + +$raw = file_get_contents('php://input'); // the raw body, before anything parses it +$verdict = $verifier->verify(getallheaders(), $raw); + +if ($verdict->shouldProcess()) { // VALID or UNSIGNED + $payload = WebhookPayload::fromRawBody($raw); // orderId, transid, paymentStatus, amountTzs, ... + // 1. verify (done) 2. deduplicate on $payload->dedupeKey() and STORE the delivery (redacted); + // if storing fails, answer 5xx so the gateway delivers again + // 3. acknowledge with 200 + // 4. later, outside the request: orderStatus($payload->orderId), then act on THAT +} +http_response_code($verdict->httpStatus()); // 200 for VALID, UNSIGNED, REPLAY; 401 for INVALID, STALE +``` + +| Verdict | Respond | Process? | +|---|---|---| +| `VALID` | 200 | Yes, then confirm with `orderStatus` | +| `UNSIGNED` (no `Digest` header) | 200 | Yes, then confirm with `orderStatus` | +| `REPLAY` | 200 | No: already handled | +| `INVALID` | 401 | No. Log it, redacted | +| `STALE` | 401 | No. Log it, redacted | + +- `verify(headers, rawBody)` never throws on bad input: bad input is `INVALID`. Header names are matched case-insensitively. The digest is compared in constant time. The timestamp window defaults to 300 seconds and is configurable. +- `VALID` covers the fields named in `Signed-Fields`, which must include `order_id` and `transid` and may not contain `&`. Take the status and the amount from `orderStatus`, not from the delivery. +- Verification is bounded: oversized input, numbers that are not whole numbers within 2^53 - 1, and anything unparseable are `INVALID`, never an exception. The one exception is `ReplayStoreException`, raised when your replay store itself fails: answer 5xx so the gateway delivers again. +- `WebhookPayload::$amountTzs` parses text such as `"10,000"` strictly into whole shillings, or `null`. +- The replay store keeps each digest until max(now, signed time) + window (`ReplayStore::seen($digest, $keepUntil)`; an entry is live through `$keepUntil`). In PHP-FPM each request is a new process, so give the verifier a shared `ReplayStore` (APCu, Redis); `InMemoryReplayStore` is for tests and long-running workers. Your own deduplication on `(order_id, transid)` is the durable guard. +- **Open question in the spec:** it is not confirmed which key Selcom signs webhooks with. The samples assume your API secret. Until you have confirmed it in the sandbox, run in report-only mode: log the verdict and process anyway, relying on `orderStatus`. Default to rejecting `INVALID` once you have confirmed. +- Acknowledge fast (200 as soon as the delivery is stored) and do the `orderStatus` call and fulfilment afterwards. Poll `orderStatus` as the fallback for orders with no final status: webhooks can be lost. + +Use an HTTPS URL with an unguessable token in the path, and send it on every order, in base64 (the request classes do the encoding). + +## Transport + +The `Transport` interface is the whole HTTP layer: + +```php +interface Transport +{ + public function send(TransportRequest $request): TransportResponse; // throws TransportException +} +``` + +`TransportRequest` carries the method, the full URL, the signed headers, the body and the `TimeoutProfile` to use. Implement the interface for a custom client, a proxy, request logging or a test fake, and pass it to `new Client($config, $transport)`. The contract: return a `TransportResponse` for **every** HTTP response whatever its status; throw `TransportException` only when no response arrived, classified `NotSent` only when the request provably never left; apply the timeouts; never retry. + +`Psr18Transport` is the default. It takes PSR-17 factories (found by discovery when you pass none) and one of three ways to get a client with the right timeouts: + +```php +new Psr18Transport(); // a Guzzle client per timeout profile (needs guzzlehttp/guzzle) +new Psr18Transport(fn (TimeoutProfile $p) => new GuzzleHttp\Client(Psr18Transport::guzzleOptions($p))); +new Psr18Transport($myPsr18Client, clientManagesTimeouts: true); // a ready client: you confirm it applies the timeouts +``` + +`Psr18Transport::guzzleOptions($profile)` returns what the default route uses. Written out, a per-profile Guzzle client looks like this: + +```php +new Psr18Transport(fn (TimeoutProfile $p) => new GuzzleHttp\Client([ + 'connect_timeout' => $p->connectSeconds, + 'timeout' => $p->connectSeconds + $p->readSeconds, + 'allow_redirects' => false, + 'http_errors' => false, + // payments only: a new connection every time, not kept for reuse + 'curl' => $p->freshConnection ? [CURLOPT_FRESH_CONNECT => true, CURLOPT_FORBID_REUSE => true] : [], +])); +``` + +**Timeouts and PSR-18.** PSR-18 has no way to pass a timeout with a request, so the timeouts live in the client, and no request runs without them. `Psr18Transport` therefore needs one of three things: nothing (it builds a Guzzle client per profile, so Guzzle must be installed), a closure that builds one client per `TimeoutProfile`, or a ready client together with `clientManagesTimeouts: true`, by which you confirm that the client applies the connect and read timeouts itself. A ready client without the flag is refused with a `ConfigurationException`. + +**Fresh connections for payments and writes.** The payment and write profiles have `freshConnection = true`: each such request uses a new connection and does not leave it open for reuse (`CURLOPT_FRESH_CONNECT` and `CURLOPT_FORBID_REUSE` on cURL). The default Guzzle route does this for you. With a custom client, disable connection reuse for the payment and write profiles yourself. + +**No hidden resends.** Whatever client you plug in must not retry requests on its own (no retry middleware, no automatic resend of a POST): a repeated POST is a second payment attempt. Retries are the caller's decision, see above. + +**What is kept from a failed send.** `TransportException` carries a short summary as its cause (exception classes and the cURL error number), not the client's own exception, whose message and request hold request data. + +## Signing on its own + +The signer is a pure function: the timestamp is an argument, and nothing is sent or read. + +```php +use SelcomDevelopers\Selcom\Signing\Hs256DigestSigner; +use SelcomDevelopers\Selcom\Signing\RequestSigner; + +$signed = RequestSigner::sign( + 'POST', // GET, POST or DELETE + ['vendor' => 'TILL123', 'order_id' => 'ORD-1001', 'amount' => 8000, 'billing' => ['firstname' => 'John']], + '2026-11-21T10:30:46+03:00', // also accepted: +0300 + $apiKey, + new Hs256DigestSigner($secret), +); + +$signed->signedFields; // vendor,order_id,amount,billing.firstname +$signed->signingString; // timestamp=...&vendor=TILL123&... +$signed->headers(); // Authorization, Digest-Method, Digest, Timestamp, Signed-Fields +$signed->query; // GET/DELETE: percent-encoded query string (null on POST) +$signed->body; // POST: compact JSON with flat keys (null on GET/DELETE) +``` + +Nested arrays are flattened in place to dotted keys; the order is the order you give. Values are signed and sent as the same text; `null` becomes an empty string; fractional numbers, integers beyond 2^53 - 1, lists and empty objects are rejected with a `SigningException`. The behaviour is fixed by the shared vectors, so any change that breaks them fails the tests. Implement `DigestSigner` to add another digest method (RS256 is not implemented: Selcom has not confirmed the padding or the key registration). + +## Redacting logs + +Do not log secrets or personal data. Pass anything you store or log through the redactor: + +```php +use SelcomDevelopers\Selcom\Redaction\Redactor; + +$redactor = new Redactor(); +$redactor->redactHeaders($request->headers); // Authorization, Digest -> [REDACTED] +$redactor->redactParams($params); // flat or nested arrays +$redactor->redactQuery($queryString); +$redactor->redactJson($result->raw); // non-JSON bodies are replaced by a placeholder +``` + +| Data | Fields (also as `billing.x`, `shipping.x`) | Becomes | +|---|---|---| +| Secrets | `pin`, `secret`, `api_secret`, `api_key`, `Authorization`, `Digest`, `card_token` | `[REDACTED]` | +| Phone numbers | `msisdn`, `phone`, `buyer_phone`, and `utilityref` on wallet cash-in | `********0001` (all but the last 4) | +| E-mail | `buyer_email`, `email` | `t***@example.com` | +| Names | `buyer_name`, `firstname`, `lastname`, `name` | `T***` | + +`TransportRequest::redactedHeaders()` is a shortcut for the headers. The client does no logging of its own. + +## Security + +- Keep the API secret, the float PIN and card tokens out of source control, logs, error trackers and chat. Read them from the environment or a secret store. +- Redact before you log (above). Dumps of `Config`, `Credentials` and `Hs256DigestSigner` are already safe, and the secret is never in an exception message. +- Fail closed: the client never sends an unsigned or empty-digest request. +- Treat webhooks as hints (above), over HTTPS, with a replay store. +- Report vulnerabilities privately: see [SECURITY.md](SECURITY.md). + +## Testing + +``` +composer install +composer test # PHPUnit: the shared spec vectors, unit tests, no network +composer analyse # PHPStan at the max level, with the strict rules +``` + +`scripts/check-spec.sh` (run in CI) checks that the copy is byte-identical to selcom-spec at `SPEC_VERSION`. The tests run every case and every reject in `signing.json`, every response scenario and every webhook sample from the shared spec, from a copy kept in `tests/vectors`. The spec version is recorded in `SPEC_VERSION`; refresh the copy with `scripts/refresh-spec.sh [tag]`. + +No test calls the network. An opt-in sandbox test (`tests/Sandbox`) is skipped unless `SELCOM_SANDBOX_API_KEY`, `SELCOM_SANDBOX_API_SECRET` and `SELCOM_SANDBOX_VENDOR` are set; it makes one read-only call and never runs in CI. + +For your own tests, pass a fake `Transport` and a fixed `ClockInterface` to `Client`. + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). Changes are listed in [CHANGELOG.md](CHANGELOG.md). + +## License + +[Apache License 2.0](LICENSE). Not affiliated with Selcom Paytech Ltd. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..7ec538e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,25 @@ +# Security policy + +This is a community project, **not affiliated with Selcom Paytech Ltd.** + +## Reporting a vulnerability in this library + +Please report it privately through GitHub: open the repository's **Security** tab and choose **Report a vulnerability** (private vulnerability reporting). Do not open a public issue for a security problem. + +Include what you found, how to reproduce it, and the version. Use made-up data only: never send real credentials, PINs, card tokens or customer data. + +We aim to acknowledge a report within a few days and to fix confirmed problems before disclosing them. + +## Supported versions + +Until a stable release exists, only the latest commit on `main` is supported. + +## Out of scope + +Problems with Selcom's gateway, its API, your credentials or your contract are for Selcom: . + +## Handling credentials safely + +- Never commit the API secret, the float PIN or card tokens. Read them from the environment or a secret store. +- Redact logs with the `Redactor` class. The client never logs anything itself. +- Treat webhooks as hints and confirm with `orderStatus` before fulfilling. diff --git a/SPEC_VERSION b/SPEC_VERSION new file mode 100644 index 0000000..c0df4fb --- /dev/null +++ b/SPEC_VERSION @@ -0,0 +1,2 @@ +v0.2.1 +8af27b402d2530c55e543b588ba2c2ef0dbfa866 diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..cba2bc7 --- /dev/null +++ b/composer.json @@ -0,0 +1,72 @@ +{ + "name": "selcom-developers/selcom-php", + "description": "Framework-agnostic PHP client for the Selcom API gateway: signing, checkout, payouts, webhooks. Not affiliated with Selcom Paytech Ltd.", + "type": "library", + "license": "Apache-2.0", + "keywords": [ + "selcom", + "tanzania", + "payments", + "psr-18", + "mobile-money" + ], + "homepage": "https://github.com/selcom-developers/selcom-php", + "authors": [ + { + "name": "Selcom Developers community", + "homepage": "https://github.com/selcom-developers" + } + ], + "support": { + "issues": "https://github.com/selcom-developers/selcom-php/issues", + "source": "https://github.com/selcom-developers/selcom-php" + }, + "require": { + "php": "^8.2", + "ext-hash": "*", + "ext-json": "*", + "php-http/discovery": "^1.20", + "psr/clock": "^1.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.9", + "phpstan/phpstan": "^2.1", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^11.5 || ^12.0" + }, + "autoload": { + "psr-4": { + "SelcomDevelopers\\Selcom\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "SelcomDevelopers\\Selcom\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "analyse": "phpstan analyse --memory-limit=1G", + "check": [ + "@composer validate --strict", + "@analyse", + "@test" + ] + }, + "config": { + "sort-packages": true, + "optimize-autoloader": false, + "classmap-authoritative": false, + "allow-plugins": { + "php-http/discovery": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true, + "suggest": { + "guzzlehttp/guzzle": "The default transport builds a Guzzle client per timeout profile (connect and read timeouts, a fresh connection for payments)" + } +} diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..b1c7e98 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,9 @@ +includes: + - vendor/phpstan/phpstan-strict-rules/rules.neon + +parameters: + level: max + paths: + - src + - tests + treatPhpDocTypesAsCertain: false diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..273f870 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,20 @@ + + + + + tests + + + + + src + + + diff --git a/scripts/check-spec.sh b/scripts/check-spec.sh new file mode 100644 index 0000000..79563bc --- /dev/null +++ b/scripts/check-spec.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Check that tests/vectors is byte-identical to selcom-spec at the tag and commit in SPEC_VERSION. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +tag="$(sed -n 1p "$root/SPEC_VERSION")" +want="$(sed -n 2p "$root/SPEC_VERSION")" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +git clone --quiet --depth 1 --branch "$tag" https://github.com/selcom-developers/selcom-spec.git "$work/spec" +got="$(git -C "$work/spec" rev-parse HEAD)" +if [ "$got" != "$want" ]; then + echo "SPEC_VERSION says $want but tag $tag is $got" >&2 + exit 1 +fi + +diff -r "$work/spec/vectors" "$root/tests/vectors" +echo "tests/vectors matches selcom-spec $tag ($got)" diff --git a/scripts/refresh-spec.sh b/scripts/refresh-spec.sh new file mode 100644 index 0000000..d334a33 --- /dev/null +++ b/scripts/refresh-spec.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Refresh the copy of the shared test vectors in tests/vectors from selcom-developers/selcom-spec. +# +# scripts/refresh-spec.sh # use the tag recorded in SPEC_VERSION +# scripts/refresh-spec.sh v0.2.0 # move to another tag +# +# The tag and the commit it points to are written back to SPEC_VERSION. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +tag="${1:-$(head -n 1 "$root/SPEC_VERSION")}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +git clone --quiet --depth 1 --branch "$tag" https://github.com/selcom-developers/selcom-spec.git "$work/spec" +sha="$(git -C "$work/spec" rev-parse HEAD)" + +rm -rf "$root/tests/vectors" +mkdir -p "$root/tests/vectors" +cp "$work/spec/vectors/signing.json" "$root/tests/vectors/signing.json" +cp -r "$work/spec/vectors/responses" "$root/tests/vectors/responses" +printf '%s\n%s\n' "$tag" "$sha" > "$root/SPEC_VERSION" + +echo "tests/vectors refreshed from selcom-spec $tag ($sha)" diff --git a/src/Amounts.php b/src/Amounts.php new file mode 100644 index 0000000..c02296c --- /dev/null +++ b/src/Amounts.php @@ -0,0 +1,46 @@ += 0 ? $value : null; + } + if (!is_string($value)) { + return null; + } + $text = trim($value); + if (preg_match(self::PATTERN, $text) !== 1) { + return null; + } + $digits = str_replace(',', '', explode('.', $text, 2)[0]); + // Stay well inside the PHP int range: more than 18 significant digits is not a real amount. + if (strlen(ltrim($digits, '0')) > 18) { + return null; + } + + return (int) $digits; + } + + /** + * @throws \InvalidArgumentException when the value is not a whole amount + */ + public static function parse(mixed $value): int + { + return self::tryParse($value) ?? throw new \InvalidArgumentException('Not a whole-unit amount.'); + } +} diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..3e18e9a --- /dev/null +++ b/src/Client.php @@ -0,0 +1,245 @@ +transport = $transport ?? Psr18Transport::discover(); + $this->clock = $clock ?? new SystemClock(); + $this->digestSignerFactory = $digestSignerFactory + ?? static fn (Credentials $c): DigestSigner => new Hs256DigestSigner($c->secret()); + } + + /** @return array */ + public function __debugInfo(): array + { + return ['version' => self::VERSION, 'config' => $this->config]; + } + + // ---- Checkout --------------------------------------------------------------------------- + + public function createOrder(CreateOrderRequest $request): CreateOrderResult + { + return $this->run($request, CreateOrderResult::class); + } + + public function createOrderMinimal(CreateOrderMinimalRequest $request): CreateOrderResult + { + return $this->run($request, CreateOrderResult::class); + } + + /** Money-moving: never retried. */ + public function walletPayment(WalletPaymentRequest $request): Result + { + return $this->execute($request); + } + + /** Money-moving: never retried. */ + public function cardPayment(CardPaymentRequest $request): Result + { + return $this->execute($request); + } + + public function orderStatus(OrderStatusRequest $request): OrderStatusResult + { + return $this->run($request, OrderStatusResult::class); + } + + public function cancelOrder(CancelOrderRequest $request): Result + { + return $this->execute($request); + } + + public function listOrders(ListOrdersRequest $request): ListOrdersResult + { + return $this->run($request, ListOrdersResult::class); + } + + public function storedCards(StoredCardsRequest $request): StoredCardsResult + { + return $this->run($request, StoredCardsResult::class); + } + + public function deleteCard(DeleteCardRequest $request): Result + { + return $this->execute($request); + } + + // ---- Payouts ---------------------------------------------------------------------------- + + /** Money-moving: never retried. */ + public function utilityPayment(UtilityPaymentRequest $request): PayoutResult + { + return $this->run($request, PayoutResult::class); + } + + public function utilityLookup(UtilityLookupRequest $request): LookupResult + { + return $this->run($request, LookupResult::class); + } + + public function utilityQuery(UtilityQueryRequest $request): PayoutResult + { + return $this->run($request, PayoutResult::class); + } + + /** Money-moving: never retried. */ + public function walletCashin(WalletCashinRequest $request): PayoutResult + { + return $this->run($request, PayoutResult::class); + } + + public function walletNameLookup(WalletNameLookupRequest $request): LookupResult + { + return $this->run($request, LookupResult::class); + } + + public function walletCashinQuery(WalletCashinQueryRequest $request): PayoutResult + { + return $this->run($request, PayoutResult::class); + } + + public function vendorBalance(VendorBalanceRequest $request): BalanceResult + { + return $this->run($request, BalanceResult::class); + } + + // ---- Generic ---------------------------------------------------------------------------- + + /** + * Sign, send once (or repeat after NOT_SENT when opted in and allowed) and classify. + * + * @throws ValidationException when the PIN is needed and missing + * @throws SigningException when the request cannot be signed: nothing is sent + * @throws TransportException when no response arrived + * @throws InvalidResponseException when an operation that moves no money got no verdict + */ + public function execute(OperationRequest $request): Result + { + $operation = $request->operation(); + $credentials = $this->config->credentialsFor($operation); + $params = $request->params($credentials); + + $attempts = 1 + ($operation->isRetryableWhenNotSent() ? $this->config->maxNotSentRetries : 0); + for ($attempt = 1;; $attempt++) { + // A fresh timestamp for every send, including a repeat after NOT_SENT. + $signed = RequestSigner::sign( + $operation->method(), + $params, + Timestamp::format($this->clock->now(), $this->config->timezone), + $credentials->apiKey(), + ($this->digestSignerFactory)($credentials), + ); + + $headers = $signed->headers() + [ + 'Accept' => 'application/json', + 'User-Agent' => 'selcom-php/' . self::VERSION, + ]; + $url = $this->config->baseUrl() . $operation->path(); + if ($signed->body !== null) { + $headers['Content-Type'] = 'application/json'; + } else { + $url .= '?' . $signed->query; + } + + try { + $response = $this->transport->send(new TransportRequest( + $operation->method(), + $url, + $headers, + $signed->body, + $this->config->timeouts->forOperation($operation), + )); + } catch (TransportException $e) { + if ($e->isNotSent() && $attempt < $attempts) { + continue; + } + throw $e; + } + + return ResultFactory::create($operation, $response->status, $response->body, $params); + } + } + + /** + * @template T of Result + * @param class-string $class + * @return T + */ + private function run(OperationRequest $request, string $class): Result + { + $result = $this->execute($request); + if (!$result instanceof $class) { + throw new \LogicException('Unexpected result type for ' . $request->operation()->value . '.'); + } + + return $result; + } +} diff --git a/src/Config.php b/src/Config.php new file mode 100644 index 0000000..59ca44f --- /dev/null +++ b/src/Config.php @@ -0,0 +1,179 @@ + 5) { + throw new ConfigurationException('maxNotSentRetries must be between 0 and 5.'); + } + } + + /** + * Build from a plain array, as a framework config file would provide. + * + * Keys: environment (required), api_key, secret, vendor (all required), pin, checkout + * (array with api_key, secret, vendor), base_url, timezone, max_not_sent_retries, timeouts + * (array: query_connect, query_read, payment_connect, payment_read, in seconds). + * + * @param array $config + */ + public static function fromArray(#[\SensitiveParameter] array $config): self + { + $environment = Environment::fromName(self::optionalString($config, 'environment')); + $credentials = new Credentials( + self::optionalString($config, 'api_key') ?? '', + self::optionalString($config, 'secret') ?? '', + self::optionalString($config, 'vendor') ?? '', + self::optionalString($config, 'pin'), + ); + + $checkout = null; + if (isset($config['checkout'])) { + if (!is_array($config['checkout'])) { + throw new ConfigurationException('"checkout" must be an array.'); + } + /** @var array $c */ + $c = $config['checkout']; + $checkout = new Credentials( + self::optionalString($c, 'api_key') ?? '', + self::optionalString($c, 'secret') ?? '', + self::optionalString($c, 'vendor') ?? $credentials->vendor(), + ); + } + + $timeouts = new Timeouts(); + if (isset($config['timeouts'])) { + if (!is_array($config['timeouts'])) { + throw new ConfigurationException('"timeouts" must be an array.'); + } + /** @var array $t */ + $t = $config['timeouts']; + $timeouts = new Timeouts( + new TimeoutProfile( + self::seconds($t, 'query_connect', $timeouts->query->connectSeconds), + self::seconds($t, 'query_read', $timeouts->query->readSeconds), + ), + new TimeoutProfile( + self::seconds($t, 'payment_connect', $timeouts->payment->connectSeconds), + self::seconds($t, 'payment_read', $timeouts->payment->readSeconds), + ), + ); + } + + try { + $zone = new \DateTimeZone(self::optionalString($config, 'timezone') ?? self::DEFAULT_TIMEZONE); + } catch (\Exception) { + throw new ConfigurationException('Unknown timezone.'); + } + + $retries = $config['max_not_sent_retries'] ?? 0; + if (!is_int($retries)) { + throw new ConfigurationException('"max_not_sent_retries" must be an integer.'); + } + + $instance = new self($environment, $credentials, $checkout, $timeouts, $zone, $retries); + $baseUrl = self::optionalString($config, 'base_url'); + + return $baseUrl === null ? $instance : $instance->withBaseUrl($baseUrl); + } + + /** + * Point the client at a simulator or proxy instead of the environment's preset URL. + */ + public function withBaseUrl(string $baseUrl): self + { + $parts = parse_url($baseUrl); + if ($parts === false || !isset($parts['scheme'], $parts['host']) + || !in_array(strtolower($parts['scheme']), ['http', 'https'], true) + || isset($parts['query']) || isset($parts['fragment']) + ) { + throw new ConfigurationException('The base URL must be an http(s) URL without query or fragment.'); + } + $copy = clone $this; + $copy->customBaseUrl = rtrim($baseUrl, '/'); + + return $copy; + } + + public function baseUrl(): string + { + return $this->customBaseUrl ?? $this->environment->baseUrl(); + } + + /** The credential set for an operation: checkout operations use the checkout set when there is one. */ + public function credentialsFor(Operation $operation): Credentials + { + return $operation->isCheckout() ? ($this->checkoutCredentials ?? $this->credentials) : $this->credentials; + } + + /** @return array */ + public function __debugInfo(): array + { + return [ + 'environment' => $this->environment->value, + 'baseUrl' => $this->baseUrl(), + 'credentials' => $this->credentials, + 'checkoutCredentials' => $this->checkoutCredentials, + ]; + } + + /** + * @param array $config + */ + private static function optionalString(array $config, string $key): ?string + { + $value = $config[$key] ?? null; + if ($value === null) { + return null; + } + if (!is_string($value)) { + throw new ConfigurationException('"' . $key . '" must be a string.'); + } + + return $value; + } + + /** + * @param array $config + */ + private static function seconds(array $config, string $key, float $default): float + { + $value = $config[$key] ?? $default; + if (!is_int($value) && !is_float($value)) { + throw new ConfigurationException('"timeouts.' . $key . '" must be a number of seconds.'); + } + + return (float) $value; + } +} diff --git a/src/Credentials.php b/src/Credentials.php new file mode 100644 index 0000000..5d04ade --- /dev/null +++ b/src/Credentials.php @@ -0,0 +1,105 @@ + $apiKey, 'secret' => $secret, 'vendor' => $vendor] as $name => $value) { + if (trim($value) === '') { + throw new ConfigurationException('The ' . $name . ' is required and must not be empty.'); + } + } + if ($pin !== null && trim($pin) === '') { + throw new ConfigurationException('The pin must be omitted or non-empty.'); + } + $this->vendor = $vendor; + $this->keyHint = self::mask($apiKey); + $this->pinSet = $pin !== null; + SecretVault::put($this, ['apiKey' => $apiKey, 'secret' => $secret, 'pin' => $pin]); + } + + private function __clone() + { + } + + public function apiKey(): string + { + return SecretVault::get($this, 'apiKey') ?? ''; + } + + public function secret(): string + { + return SecretVault::get($this, 'secret') ?? ''; + } + + public function vendor(): string + { + return $this->vendor; + } + + public function hasPin(): bool + { + return $this->pinSet; + } + + /** + * @throws ValidationException when no PIN is configured (payout operations need one) + */ + public function pin(): string + { + return SecretVault::get($this, 'pin') ?? throw new ValidationException( + 'This operation spends from the float account and needs the float PIN, but none is configured.' + ); + } + + /** The API key reduced to its last 4 characters, for logs and dumps. */ + public function maskedApiKey(): string + { + return $this->keyHint; + } + + /** @return array */ + public function __debugInfo(): array + { + return [ + 'apiKey' => $this->keyHint, + 'secret' => '[REDACTED]', + 'vendor' => $this->vendor, + 'pin' => $this->pinSet ? '[REDACTED]' : 'none', + ]; + } + + public function __serialize(): array + { + throw new \LogicException('Credentials hold secrets and cannot be serialised.'); + } + + private static function mask(string $apiKey): string + { + return '****' . substr($apiKey, -4); + } +} diff --git a/src/Currency.php b/src/Currency.php new file mode 100644 index 0000000..66404a3 --- /dev/null +++ b/src/Currency.php @@ -0,0 +1,14 @@ + 'https://apigwtest.selcommobile.com', + self::Production => 'https://apigw.selcommobile.com', + }; + } + + public static function fromName(?string $name): self + { + if ($name === null || trim($name) === '') { + throw new ConfigurationException( + 'The environment is required: choose "sandbox" or "production". There is no default.' + ); + } + + return self::tryFrom(strtolower(trim($name))) ?? throw new ConfigurationException( + 'Unknown environment "' . $name . '": choose "sandbox" or "production".' + ); + } +} diff --git a/src/Exception/ConfigurationException.php b/src/Exception/ConfigurationException.php new file mode 100644 index 0000000..808a1cd --- /dev/null +++ b/src/Exception/ConfigurationException.php @@ -0,0 +1,13 @@ + $rawBody]); + } + + /** The body as received, for diagnosis. It may hold personal data: redact before logging. */ + public function rawBody(): string + { + return SecretVault::get($this, 'rawBody') ?? ''; + } + + public function errorCode(): string + { + return self::CODE; + } +} diff --git a/src/Exception/ReplayStoreException.php b/src/Exception/ReplayStoreException.php new file mode 100644 index 0000000..84ee6f7 --- /dev/null +++ b/src/Exception/ReplayStoreException.php @@ -0,0 +1,14 @@ +failure === TransportFailure::NotSent; + } +} diff --git a/src/Exception/ValidationException.php b/src/Exception/ValidationException.php new file mode 100644 index 0000000..d08b6c9 --- /dev/null +++ b/src/Exception/ValidationException.php @@ -0,0 +1,12 @@ + 'POST', + self::CheckoutCancelOrder, + self::CheckoutDeleteCard => 'DELETE', + self::CheckoutOrderStatus, + self::CheckoutListOrders, + self::CheckoutStoredCards, + self::UtilityPaymentLookup, + self::UtilityPaymentQuery, + self::WalletCashinNameLookup, + self::WalletCashinQuery => 'GET', + }; + } + + public function path(): string + { + return '/v1/' . str_replace('.', '/', $this->value); + } + + public function kind(): OperationKind + { + return match ($this) { + self::CheckoutWalletPayment, + self::CheckoutCardPayment, + self::UtilityPaymentProcess, + self::WalletCashinProcess => OperationKind::Payment, + self::UtilityPaymentQuery, + self::WalletCashinQuery => OperationKind::StatusQuery, + self::CheckoutOrderStatus => OperationKind::OrderStatus, + default => OperationKind::Other, + }; + } + + /** + * Creates, cancels and deletes: no money moves, but they are not idempotent, + * so the client never retries them. + */ + public function isWrite(): bool + { + return match ($this) { + self::CheckoutCreateOrder, + self::CheckoutCreateOrderMinimal, + self::CheckoutCancelOrder, + self::CheckoutDeleteCard => true, + default => false, + }; + } + + /** + * Whether the client may repeat the request itself after a NOT_SENT error, + * when the caller opted in. Never for payments or writes. + */ + public function isRetryableWhenNotSent(): bool + { + return $this->kind() !== OperationKind::Payment && !$this->isWrite(); + } + + /** Checkout operations may use a second credential set. */ + public function isCheckout(): bool + { + return str_starts_with($this->value, 'checkout.'); + } +} diff --git a/src/OperationKind.php b/src/OperationKind.php new file mode 100644 index 0000000..6034a2b --- /dev/null +++ b/src/OperationKind.php @@ -0,0 +1,17 @@ +> $headers + * @return array> + */ + public function redactHeaders(array $headers): array + { + $out = []; + foreach ($headers as $name => $value) { + if (in_array(strtolower($name), self::SECRET_KEYS, true)) { + $out[$name] = is_array($value) ? array_fill(0, count($value), self::REDACTED) : self::REDACTED; + } else { + $out[$name] = $value; + } + } + + return $out; + } + + /** + * Redact a flat or nested parameter or body array. + * + * @param array $data + * @param string|null $path The request path, if known: `utilityref` is masked as a phone number + * on every `/v1/walletcashin/` path + * @return array + */ + public function redactParams(array $data, ?string $path = null): array + { + $isCashin = self::isCashinPath($path) || $this->isCashin($data); + $out = []; + foreach ($data as $key => $value) { + if (is_array($value)) { + $out[$key] = $this->redactParams($value, $path); + continue; + } + $out[$key] = $this->redactValue((string) $key, $value, $isCashin); + } + + return $out; + } + + /** + * Redact a query string, keeping its order and encoding of the other fields. + */ + public function redactQuery(string $query, ?string $path = null): string + { + $pairs = []; + $isCashin = self::isCashinPath($path); + foreach (explode('&', $query) as $part) { + if ($part === '') { + continue; + } + $kv = explode('=', $part, 2); + $pairs[] = [rawurldecode(str_replace('+', '%20', $kv[0])), rawurldecode(str_replace('+', '%20', $kv[1] ?? ''))]; + if (strtolower(end($pairs)[0]) === 'utilitycode' && self::isCashinCode(end($pairs)[1])) { + $isCashin = true; + } + } + $out = []; + foreach ($pairs as [$key, $value]) { + $redacted = $this->redactValue($key, $value, $isCashin); + $out[] = rawurlencode($key) . '=' . rawurlencode(is_string($redacted) ? $redacted : ''); + } + + return implode('&', $out); + } + + /** + * Redact a JSON body (request or response). Returns the redacted JSON, or the placeholder + * "[UNPARSEABLE BODY OMITTED]" when the text is not JSON, so nothing sensitive leaks through. + */ + public function redactJson(string $json, ?string $path = null): string + { + $decoded = json_decode($json, true); + if (!is_array($decoded)) { + return '[UNPARSEABLE BODY OMITTED]'; + } + + $encoded = json_encode($this->redactParams($decoded, $path), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR); + + return $encoded === false ? '{}' : $encoded; + } + + private function redactValue(string $key, mixed $value, bool $isCashin): mixed + { + $name = strtolower($key); + $dot = strrpos($name, '.'); + if ($dot !== false) { + $name = substr($name, $dot + 1); + } + + if ($value === null) { + return null; + } + if (in_array($name, self::SECRET_KEYS, true)) { + return self::REDACTED; + } + if (!is_scalar($value)) { + return $value; + } + $text = (string) $value; + if (in_array($name, self::PHONE_KEYS, true) || ($isCashin && $name === 'utilityref')) { + return self::phone($text); + } + if (in_array($name, self::EMAIL_KEYS, true)) { + return self::email($text); + } + if (in_array($name, self::NAME_KEYS, true)) { + return self::name($text); + } + + return $value; + } + + /** + * @param array $data + */ + private function isCashin(array $data): bool + { + foreach ($data as $key => $value) { + if (strtolower((string) $key) === 'utilitycode' && is_string($value) && self::isCashinCode($value)) { + return true; + } + } + + return false; + } + + private static function isCashinPath(?string $path): bool + { + return $path !== null && str_contains($path, '/v1/walletcashin/'); + } + + private static function isCashinCode(string $code): bool + { + return str_ends_with(strtoupper(trim($code)), 'CASHIN'); + } + + private static function phone(string $text): string + { + $chars = self::chars($text); + $count = count($chars); + if ($count <= 4) { + return str_repeat('*', $count); + } + + return str_repeat('*', $count - 4) . implode('', array_slice($chars, -4)); + } + + private static function email(string $text): string + { + $at = strrpos($text, '@'); + if ($at === false || $at === 0) { + return self::REDACTED; + } + + return (self::chars($text)[0] ?? '') . '***' . substr($text, $at); + } + + private static function name(string $text): string + { + $chars = self::chars($text); + + return $chars === [] ? '' : $chars[0] . '***'; + } + + /** @return list */ + private static function chars(string $text): array + { + $chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); + + return $chars === false ? str_split($text) : $chars; + } +} diff --git a/src/Request/Address.php b/src/Request/Address.php new file mode 100644 index 0000000..85fcbee --- /dev/null +++ b/src/Request/Address.php @@ -0,0 +1,68 @@ +firstname = Check::required('firstname', $firstname); + $this->lastname = Check::required('lastname', $lastname); + $this->address1 = Check::required('address_1', $address1); + $this->address2 = Check::optional('address_2', $address2); + $this->city = Check::required('city', $city); + $this->stateOrRegion = Check::required('state_or_region', $stateOrRegion); + $this->postcodeOrPobox = Check::required('postcode_or_pobox', $postcodeOrPobox); + $this->country = Check::required('country', $country); + $this->phone = Check::required('phone', $phone); + } + + /** @return array */ + public function toParams(): array + { + $params = [ + 'firstname' => $this->firstname, + 'lastname' => $this->lastname, + 'address_1' => $this->address1, + ]; + if ($this->address2 !== null) { + $params['address_2'] = $this->address2; + } + + return $params + [ + 'city' => $this->city, + 'state_or_region' => $this->stateOrRegion, + 'postcode_or_pobox' => $this->postcodeOrPobox, + 'country' => $this->country, + 'phone' => $this->phone, + ]; + } +} diff --git a/src/Request/CancelOrderRequest.php b/src/Request/CancelOrderRequest.php new file mode 100644 index 0000000..7e55e0f --- /dev/null +++ b/src/Request/CancelOrderRequest.php @@ -0,0 +1,33 @@ +orderId = Check::required('order_id', $orderId); + } + + public function operation(): Operation + { + return Operation::CheckoutCancelOrder; + } + + public function params(Credentials $credentials): array + { + return ['order_id' => $this->orderId]; + } +} diff --git a/src/Request/CardPaymentRequest.php b/src/Request/CardPaymentRequest.php new file mode 100644 index 0000000..3a47c77 --- /dev/null +++ b/src/Request/CardPaymentRequest.php @@ -0,0 +1,58 @@ +transid = Check::required('transid', $transid); + $this->orderId = Check::required('order_id', $orderId); + $this->cardToken = Check::required('card_token', $cardToken); + $this->buyerUserId = Check::required('buyer_userid', $buyerUserId); + $this->gatewayBuyerUuid = Check::required('gateway_buyer_uuid', $gatewayBuyerUuid); + } + + public function operation(): Operation + { + return Operation::CheckoutCardPayment; + } + + public function params(Credentials $credentials): array + { + return [ + 'transid' => $this->transid, + 'vendor' => $credentials->vendor(), + 'order_id' => $this->orderId, + 'card_token' => $this->cardToken, + 'buyer_userid' => $this->buyerUserId, + 'gateway_buyer_uuid' => $this->gatewayBuyerUuid, + ]; + } + + /** @return array */ + public function __debugInfo(): array + { + return ['transid' => $this->transid, 'orderId' => $this->orderId, 'cardToken' => '[REDACTED]']; + } +} diff --git a/src/Request/Check.php b/src/Request/Check.php new file mode 100644 index 0000000..82f0b54 --- /dev/null +++ b/src/Request/Check.php @@ -0,0 +1,106 @@ + 9007199254740991) { + throw new ValidationException($field . ' is too large: at most 9007199254740991.'); + } + + return $whole; + } + + public static function date(string $field, string $value): string + { + $parsed = \DateTimeImmutable::createFromFormat('!Y-m-d', $value); + if ($parsed === false || $parsed->format('Y-m-d') !== $value) { + throw new ValidationException($field . ' must be a date as YYYY-MM-DD.'); + } + + return $value; + } + + /** + * Set a key only when the value is not null, keeping the order of the calls. + * + * @param array $params + */ + public static function put(array &$params, string $key, string|int|null $value): void + { + if ($value !== null) { + $params[$key] = $value; + } + } + + public static function url(string $field, ?string $url): ?string + { + if ($url === null) { + return null; + } + $parts = parse_url($url); + if ($parts === false || !isset($parts['scheme'], $parts['host']) + || !in_array(strtolower($parts['scheme']), ['http', 'https'], true) + ) { + throw new ValidationException($field . ' must be an http(s) URL.'); + } + + // The signature covers the base64 text that is sent, so encode before signing. + return base64_encode($url); + } +} diff --git a/src/Request/CreateOrderMinimalRequest.php b/src/Request/CreateOrderMinimalRequest.php new file mode 100644 index 0000000..092e170 --- /dev/null +++ b/src/Request/CreateOrderMinimalRequest.php @@ -0,0 +1,101 @@ +orderId = Check::required('order_id', $orderId); + $this->buyerEmail = Check::required('buyer_email', $buyerEmail); + $this->buyerName = Check::required('buyer_name', $buyerName); + $this->buyerPhone = Check::required('buyer_phone', $buyerPhone); + $this->amount = Check::amount('amount', $amount); + $this->noOfItems = Check::amount('no_of_items', $noOfItems); + $this->redirectUrl = Check::url('redirect_url', $redirectUrl); + $this->cancelUrl = Check::url('cancel_url', $cancelUrl); + $this->webhookUrl = Check::url('webhook', $webhookUrl); + $this->buyerRemarks = Check::optional('buyer_remarks', $buyerRemarks); + $this->merchantRemarks = Check::optional('merchant_remarks', $merchantRemarks); + $this->headerColour = Check::optional('header_colour', $headerColour); + $this->linkColour = Check::optional('link_colour', $linkColour); + $this->buttonColour = Check::optional('button_colour', $buttonColour); + $this->expiryMinutes = $expiryMinutes === null ? null : Check::amount('expiry', $expiryMinutes); + } + + public function operation(): Operation + { + return Operation::CheckoutCreateOrderMinimal; + } + + public function params(Credentials $credentials): array + { + $params = [ + 'vendor' => $credentials->vendor(), + 'order_id' => $this->orderId, + 'buyer_email' => $this->buyerEmail, + 'buyer_name' => $this->buyerName, + 'buyer_phone' => $this->buyerPhone, + 'amount' => $this->amount, + 'currency' => $this->currency->value, + ]; + Check::put($params, 'redirect_url', $this->redirectUrl); + Check::put($params, 'cancel_url', $this->cancelUrl); + Check::put($params, 'webhook', $this->webhookUrl); + Check::put($params, 'buyer_remarks', $this->buyerRemarks); + Check::put($params, 'merchant_remarks', $this->merchantRemarks); + $params['no_of_items'] = $this->noOfItems; + Check::put($params, 'header_colour', $this->headerColour); + Check::put($params, 'link_colour', $this->linkColour); + Check::put($params, 'button_colour', $this->buttonColour); + Check::put($params, 'expiry', $this->expiryMinutes); + + return $params; + } +} diff --git a/src/Request/CreateOrderRequest.php b/src/Request/CreateOrderRequest.php new file mode 100644 index 0000000..a17ada4 --- /dev/null +++ b/src/Request/CreateOrderRequest.php @@ -0,0 +1,125 @@ + */ + public readonly array $paymentMethods; + public readonly int $noOfItems; + public readonly ?string $buyerUserId; + public readonly ?string $gatewayBuyerUuid; + public readonly ?string $redirectUrl; + public readonly ?string $cancelUrl; + public readonly ?string $webhookUrl; + public readonly ?string $buyerRemarks; + public readonly ?string $merchantRemarks; + public readonly ?string $headerColour; + public readonly ?string $linkColour; + public readonly ?string $buttonColour; + public readonly ?int $expiryMinutes; + + /** + * @param mixed $amount An int, a string of digits or an integral float Whole units of $currency; a fraction is an error, never rounded + * @param string $buyerPhone MSISDN in international form, 255... + * @param list $paymentMethods At least one + * @param string|null $buyerUserId The buyer's ID in your system; null for guest checkout + * @param string|null $gatewayBuyerUuid Returned on the buyer's first order; send it on later orders + */ + public function __construct( + string $orderId, + string $buyerEmail, + string $buyerName, + string $buyerPhone, + mixed $amount, + public readonly Currency $currency, + array $paymentMethods, + public readonly Address $billing, + int $noOfItems, + ?string $buyerUserId = null, + ?string $gatewayBuyerUuid = null, + ?string $redirectUrl = null, + ?string $cancelUrl = null, + ?string $webhookUrl = null, + public readonly ?Address $shipping = null, + ?string $buyerRemarks = null, + ?string $merchantRemarks = null, + ?string $headerColour = null, + ?string $linkColour = null, + ?string $buttonColour = null, + ?int $expiryMinutes = null, + ) { + $this->orderId = Check::required('order_id', $orderId); + $this->buyerEmail = Check::required('buyer_email', $buyerEmail); + $this->buyerName = Check::required('buyer_name', $buyerName); + $this->buyerPhone = Check::required('buyer_phone', $buyerPhone); + $this->amount = Check::amount('amount', $amount); + if ($paymentMethods === []) { + throw new ValidationException('payment_methods needs at least one method.'); + } + $this->paymentMethods = array_values($paymentMethods); + $this->noOfItems = Check::amount('no_of_items', $noOfItems); + $this->buyerUserId = Check::optional('buyer_userid', $buyerUserId); + $this->gatewayBuyerUuid = Check::optional('gateway_buyer_uuid', $gatewayBuyerUuid); + $this->redirectUrl = Check::url('redirect_url', $redirectUrl); + $this->cancelUrl = Check::url('cancel_url', $cancelUrl); + $this->webhookUrl = Check::url('webhook', $webhookUrl); + $this->buyerRemarks = Check::optional('buyer_remarks', $buyerRemarks); + $this->merchantRemarks = Check::optional('merchant_remarks', $merchantRemarks); + $this->headerColour = Check::optional('header_colour', $headerColour); + $this->linkColour = Check::optional('link_colour', $linkColour); + $this->buttonColour = Check::optional('button_colour', $buttonColour); + $this->expiryMinutes = $expiryMinutes === null ? null : Check::amount('expiry', $expiryMinutes); + } + + public function operation(): Operation + { + return Operation::CheckoutCreateOrder; + } + + public function params(Credentials $credentials): array + { + $params = ['vendor' => $credentials->vendor(), 'order_id' => $this->orderId]; + $params['buyer_email'] = $this->buyerEmail; + $params['buyer_name'] = $this->buyerName; + Check::put($params, 'buyer_userid', $this->buyerUserId); + $params['buyer_phone'] = $this->buyerPhone; + Check::put($params, 'gateway_buyer_uuid', $this->gatewayBuyerUuid); + $params['amount'] = $this->amount; + $params['currency'] = $this->currency->value; + $params['payment_methods'] = implode(',', array_map(static fn (PaymentMethod $m): string => $m->value, $this->paymentMethods)); + Check::put($params, 'redirect_url', $this->redirectUrl); + Check::put($params, 'cancel_url', $this->cancelUrl); + Check::put($params, 'webhook', $this->webhookUrl); + $params['billing'] = $this->billing->toParams(); + if ($this->shipping !== null) { + $params['shipping'] = $this->shipping->toParams(); + } + Check::put($params, 'buyer_remarks', $this->buyerRemarks); + Check::put($params, 'merchant_remarks', $this->merchantRemarks); + $params['no_of_items'] = $this->noOfItems; + Check::put($params, 'header_colour', $this->headerColour); + Check::put($params, 'link_colour', $this->linkColour); + Check::put($params, 'button_colour', $this->buttonColour); + Check::put($params, 'expiry', $this->expiryMinutes); + + return $params; + } +} diff --git a/src/Request/DeleteCardRequest.php b/src/Request/DeleteCardRequest.php new file mode 100644 index 0000000..b054743 --- /dev/null +++ b/src/Request/DeleteCardRequest.php @@ -0,0 +1,36 @@ +id = Check::required('id', (string) $id); + $this->gatewayBuyerUuid = Check::required('gateway_buyer_uuid', $gatewayBuyerUuid); + } + + public function operation(): Operation + { + return Operation::CheckoutDeleteCard; + } + + public function params(Credentials $credentials): array + { + return ['id' => $this->id, 'gateway_buyer_uuid' => $this->gatewayBuyerUuid]; + } +} diff --git a/src/Request/ListOrdersRequest.php b/src/Request/ListOrdersRequest.php new file mode 100644 index 0000000..f4c2cb6 --- /dev/null +++ b/src/Request/ListOrdersRequest.php @@ -0,0 +1,37 @@ +fromDate = Check::date('fromdate', $fromDate); + $this->toDate = Check::date('todate', $toDate); + } + + public function operation(): Operation + { + return Operation::CheckoutListOrders; + } + + public function params(Credentials $credentials): array + { + return ['fromdate' => $this->fromDate, 'todate' => $this->toDate]; + } +} diff --git a/src/Request/OperationRequest.php b/src/Request/OperationRequest.php new file mode 100644 index 0000000..ef84054 --- /dev/null +++ b/src/Request/OperationRequest.php @@ -0,0 +1,28 @@ + + * + * @throws ValidationException when the PIN is needed and not configured + */ + public function params(Credentials $credentials): array; +} diff --git a/src/Request/OrderStatusRequest.php b/src/Request/OrderStatusRequest.php new file mode 100644 index 0000000..fb0a891 --- /dev/null +++ b/src/Request/OrderStatusRequest.php @@ -0,0 +1,31 @@ +orderId = Check::required('order_id', $orderId); + } + + public function operation(): Operation + { + return Operation::CheckoutOrderStatus; + } + + public function params(Credentials $credentials): array + { + return ['order_id' => $this->orderId]; + } +} diff --git a/src/Request/PaymentMethod.php b/src/Request/PaymentMethod.php new file mode 100644 index 0000000..1d5c2d0 --- /dev/null +++ b/src/Request/PaymentMethod.php @@ -0,0 +1,16 @@ +gatewayBuyerUuid = Check::required('gateway_buyer_uuid', $gatewayBuyerUuid); + $this->buyerUserId = Check::required('buyer_userid', $buyerUserId); + } + + public function operation(): Operation + { + return Operation::CheckoutStoredCards; + } + + public function params(Credentials $credentials): array + { + return ['gateway_buyer_uuid' => $this->gatewayBuyerUuid, 'buyer_userid' => $this->buyerUserId]; + } +} diff --git a/src/Request/UtilityLookupRequest.php b/src/Request/UtilityLookupRequest.php new file mode 100644 index 0000000..ef7046c --- /dev/null +++ b/src/Request/UtilityLookupRequest.php @@ -0,0 +1,36 @@ +utilityCode = Check::required('utilitycode', $utilityCode); + $this->utilityRef = Check::required('utilityref', $utilityRef); + $this->transid = Check::required('transid', $transid); + } + + public function operation(): Operation + { + return Operation::UtilityPaymentLookup; + } + + public function params(Credentials $credentials): array + { + return ['utilitycode' => $this->utilityCode, 'utilityref' => $this->utilityRef, 'transid' => $this->transid]; + } +} diff --git a/src/Request/UtilityPaymentRequest.php b/src/Request/UtilityPaymentRequest.php new file mode 100644 index 0000000..a2088df --- /dev/null +++ b/src/Request/UtilityPaymentRequest.php @@ -0,0 +1,57 @@ +transid = Check::required('transid', $transid); + $this->utilityCode = Check::required('utilitycode', $utilityCode); + $this->utilityRef = Check::required('utilityref', $utilityRef); + $this->amount = Check::amount('amount', $amount); + $this->msisdn = Check::optional('msisdn', $msisdn); + } + + public function operation(): Operation + { + return Operation::UtilityPaymentProcess; + } + + public function params(Credentials $credentials): array + { + $params = [ + 'transid' => $this->transid, + 'utilitycode' => $this->utilityCode, + 'utilityref' => $this->utilityRef, + 'amount' => $this->amount, + 'vendor' => $credentials->vendor(), + 'pin' => $credentials->pin(), + ]; + Check::put($params, 'msisdn', $this->msisdn); + + return $params; + } +} diff --git a/src/Request/UtilityQueryRequest.php b/src/Request/UtilityQueryRequest.php new file mode 100644 index 0000000..a2ae1c5 --- /dev/null +++ b/src/Request/UtilityQueryRequest.php @@ -0,0 +1,33 @@ +transid = Check::required('transid', $transid); + } + + public function operation(): Operation + { + return Operation::UtilityPaymentQuery; + } + + public function params(Credentials $credentials): array + { + return ['transid' => $this->transid]; + } +} diff --git a/src/Request/VendorBalanceRequest.php b/src/Request/VendorBalanceRequest.php new file mode 100644 index 0000000..73f3cfa --- /dev/null +++ b/src/Request/VendorBalanceRequest.php @@ -0,0 +1,34 @@ +transid = Check::required('transid', $transid); + } + + public function operation(): Operation + { + return Operation::VendorBalance; + } + + public function params(Credentials $credentials): array + { + return ['vendor' => $credentials->vendor(), 'pin' => $credentials->pin(), 'transid' => $this->transid]; + } +} diff --git a/src/Request/WalletCashinQueryRequest.php b/src/Request/WalletCashinQueryRequest.php new file mode 100644 index 0000000..33c499d --- /dev/null +++ b/src/Request/WalletCashinQueryRequest.php @@ -0,0 +1,32 @@ +transid = Check::required('transid', $transid); + } + + public function operation(): Operation + { + return Operation::WalletCashinQuery; + } + + public function params(Credentials $credentials): array + { + return ['transid' => $this->transid]; + } +} diff --git a/src/Request/WalletCashinRequest.php b/src/Request/WalletCashinRequest.php new file mode 100644 index 0000000..5dca7e8 --- /dev/null +++ b/src/Request/WalletCashinRequest.php @@ -0,0 +1,58 @@ +transid = Check::required('transid', $transid); + $this->utilityCode = Check::required('utilitycode', $utilityCode); + $this->utilityRef = Check::required('utilityref', $utilityRef); + $this->amount = Check::amount('amount', $amount); + $this->msisdn = Check::optional('msisdn', $msisdn); + } + + public function operation(): Operation + { + return Operation::WalletCashinProcess; + } + + public function params(Credentials $credentials): array + { + $params = [ + 'transid' => $this->transid, + 'utilitycode' => $this->utilityCode, + 'utilityref' => $this->utilityRef, + 'amount' => $this->amount, + 'vendor' => $credentials->vendor(), + 'pin' => $credentials->pin(), + ]; + Check::put($params, 'msisdn', $this->msisdn); + + return $params; + } +} diff --git a/src/Request/WalletNameLookupRequest.php b/src/Request/WalletNameLookupRequest.php new file mode 100644 index 0000000..0f77b12 --- /dev/null +++ b/src/Request/WalletNameLookupRequest.php @@ -0,0 +1,36 @@ +utilityCode = Check::required('utilitycode', $utilityCode); + $this->utilityRef = Check::required('utilityref', $utilityRef); + $this->transid = Check::required('transid', $transid); + } + + public function operation(): Operation + { + return Operation::WalletCashinNameLookup; + } + + public function params(Credentials $credentials): array + { + return ['utilitycode' => $this->utilityCode, 'utilityref' => $this->utilityRef, 'transid' => $this->transid]; + } +} diff --git a/src/Request/WalletPaymentRequest.php b/src/Request/WalletPaymentRequest.php new file mode 100644 index 0000000..bd86629 --- /dev/null +++ b/src/Request/WalletPaymentRequest.php @@ -0,0 +1,40 @@ +transid = Check::required('transid', $transid); + $this->orderId = Check::required('order_id', $orderId); + $this->msisdn = Check::required('msisdn', $msisdn); + } + + public function operation(): Operation + { + return Operation::CheckoutWalletPayment; + } + + public function params(Credentials $credentials): array + { + return ['transid' => $this->transid, 'order_id' => $this->orderId, 'msisdn' => $this->msisdn]; + } +} diff --git a/src/Result/BalanceResult.php b/src/Result/BalanceResult.php new file mode 100644 index 0000000..c9c3150 --- /dev/null +++ b/src/Result/BalanceResult.php @@ -0,0 +1,19 @@ +entry()['balance'] ?? null); + } +} diff --git a/src/Result/CreateOrderResult.php b/src/Result/CreateOrderResult.php new file mode 100644 index 0000000..8fa7791 --- /dev/null +++ b/src/Result/CreateOrderResult.php @@ -0,0 +1,17 @@ +data === [] ? null : CreatedOrder::fromEntry($this->entry()); + } +} diff --git a/src/Result/CreatedOrder.php b/src/Result/CreatedOrder.php new file mode 100644 index 0000000..de5c99d --- /dev/null +++ b/src/Result/CreatedOrder.php @@ -0,0 +1,40 @@ + $entry + */ + public static function fromEntry(array $entry): self + { + $str = static fn (string $key): ?string => isset($entry[$key]) && is_scalar($entry[$key]) ? (string) $entry[$key] : null; + $raw = $str('payment_gateway_url'); + $decoded = $raw === null ? false : base64_decode($raw, true); + + return new self( + $str('gateway_buyer_uuid'), + $str('payment_token'), + $str('qr'), + $decoded === false ? null : $decoded, + $raw, + ); + } +} diff --git a/src/Result/ListOrdersResult.php b/src/Result/ListOrdersResult.php new file mode 100644 index 0000000..0aed92c --- /dev/null +++ b/src/Result/ListOrdersResult.php @@ -0,0 +1,17 @@ + */ + public function orders(): array + { + return array_map(static fn (array $entry): OrderSummary => OrderSummary::fromEntry($entry), $this->data); + } +} diff --git a/src/Result/LookupResult.php b/src/Result/LookupResult.php new file mode 100644 index 0000000..3c61814 --- /dev/null +++ b/src/Result/LookupResult.php @@ -0,0 +1,25 @@ +entryString('name'); + } + + /** The amount due on a bill lookup, in whole TZS, when present. */ + public function amountDue(): ?int + { + return Amounts::tryParse($this->entry()['amount'] ?? null); + } +} diff --git a/src/Result/OrderStatusResult.php b/src/Result/OrderStatusResult.php new file mode 100644 index 0000000..8546340 --- /dev/null +++ b/src/Result/OrderStatusResult.php @@ -0,0 +1,22 @@ +data === [] ? null : OrderSummary::fromEntry($this->entry()); + } +} diff --git a/src/Result/OrderSummary.php b/src/Result/OrderSummary.php new file mode 100644 index 0000000..1994057 --- /dev/null +++ b/src/Result/OrderSummary.php @@ -0,0 +1,52 @@ + $entry + */ + public static function fromEntry(array $entry): self + { + $str = static fn (string $key): ?string => isset($entry[$key]) && is_scalar($entry[$key]) ? (string) $entry[$key] : null; + $paymentStatus = $str('payment_status'); + + return new self( + $str('order_id'), + $str('creation_date'), + Amounts::tryParse($entry['amount'] ?? null), + $paymentStatus, + ResponseClassifier::paymentStatus($paymentStatus), + $str('transid'), + $str('channel'), + $str('reference'), + $str('msisdn') ?? $str('phone'), + ); + } +} diff --git a/src/Result/PayoutResult.php b/src/Result/PayoutResult.php new file mode 100644 index 0000000..41b6f38 --- /dev/null +++ b/src/Result/PayoutResult.php @@ -0,0 +1,21 @@ +entryString('receipt'); + } +} diff --git a/src/Result/ResponseClassifier.php b/src/Result/ResponseClassifier.php new file mode 100644 index 0000000..bd88c03 --- /dev/null +++ b/src/Result/ResponseClassifier.php @@ -0,0 +1,156 @@ + Status::Success, + 'COMPLETE' => Status::Success, + 'PENDING' => Status::Pending, + 'INPROGRESS' => Status::Pending, + 'CANCELLED' => Status::Failed, + 'CANCELED' => Status::Failed, + 'CANCEL' => Status::Failed, + 'USERCANCELLED' => Status::Failed, + 'USERCANCELED' => Status::Failed, + 'REJECTED' => Status::Failed, + 'FAILED' => Status::Failed, + ]; + + /** + * @return array{0: Status, 1: string|null, 2: array|null} status, normalised resultcode, decoded body + * + * @throws InvalidResponseException when there is no verdict and the operation moves no money + */ + public static function classify(OperationKind $kind, int $httpStatus, #[\SensitiveParameter] string $rawBody): array + { + $body = self::decode($rawBody); + $code = $body === null ? null : self::normaliseResultCode($body['resultcode'] ?? null); + + if ($body === null || $code === null) { + if ($kind === OperationKind::Other) { + throw new InvalidResponseException($httpStatus, $rawBody); + } + + // Something answered, but not with a verdict: the money may have moved. + return [Status::Ambiguous, $code, $body]; + } + + return [self::statusFor($kind, $code, $body, self::dataIsList($rawBody)), $code, $body]; + } + + /** Trim; a JSON number becomes three digits (0 becomes "000"); anything else is no code. */ + public static function normaliseResultCode(mixed $value): ?string + { + if (is_int($value)) { + return $value >= 0 ? sprintf('%03d', $value) : null; + } + if (is_string($value)) { + $trimmed = trim($value); + + return $trimmed === '' ? null : $trimmed; + } + + return null; + } + + /** + * @param array $body + */ + private static function statusFor(OperationKind $kind, string $code, array $body, bool $dataIsList): Status + { + if ($code === '000') { + return $kind === OperationKind::OrderStatus ? self::orderStatus($body, $dataIsList) : Status::Success; + } + if ($code === '111' || $code === '927') { + return Status::Pending; + } + if ($code === '999') { + return Status::Ambiguous; + } + if ($code === '404' && ($kind === OperationKind::StatusQuery || $kind === OperationKind::OrderStatus)) { + return Status::NotFound; + } + if ($kind === OperationKind::OrderStatus) { + // The query failed, which says nothing about the order. + return Status::Ambiguous; + } + + return Status::Failed; + } + + /** + * @param array $body + */ + private static function orderStatus(array $body, bool $dataIsList): Status + { + $data = $body['data'] ?? null; + // A JSON object (even an empty one) is not a list: only `[]` means "no such order". + if (!is_array($data) || !$dataIsList) { + return Status::Ambiguous; + } + if ($data === []) { + return Status::NotFound; + } + $entry = $data[0]; + $status = is_array($entry) ? ($entry['payment_status'] ?? null) : null; + + return self::paymentStatus(is_string($status) ? $status : null); + } + + /** + * The typed verdict for an order's `payment_status` text (case-insensitive, trimmed). + * Unknown or missing values are AMBIGUOUS. + */ + public static function paymentStatus(?string $paymentStatus): Status + { + if ($paymentStatus === null) { + return Status::Ambiguous; + } + + return self::PAYMENT_STATUS[strtoupper(trim($paymentStatus))] ?? Status::Ambiguous; + } + + /** + * Whether `data` is a JSON array, as opposed to an object or something else. PHP decodes `{}` + * and `[]` to the same empty array, so this looks at the decoded objects form. + */ + private static function dataIsList(#[\SensitiveParameter] string $rawBody): bool + { + $tree = json_decode($rawBody); + + return is_object($tree) && property_exists($tree, 'data') && is_array($tree->data); + } + + /** + * @return array|null + */ + private static function decode(#[\SensitiveParameter] string $rawBody): ?array + { + $tree = json_decode($rawBody); + if (!is_object($tree)) { + return null; + } + $decoded = json_decode($rawBody, true); + if (!is_array($decoded)) { + return null; + } + + /** @var array $decoded */ + return $decoded; + } +} diff --git a/src/Result/Result.php b/src/Result/Result.php new file mode 100644 index 0000000..1ba6049 --- /dev/null +++ b/src/Result/Result.php @@ -0,0 +1,89 @@ +> $data The decoded `data` array, raw values kept + */ + final public function __construct( + public readonly Operation $operation, + public readonly Status $status, + public readonly ?string $resultCode, + public readonly ?string $result, + public readonly ?string $message, + public readonly ?string $reference, + public readonly ?string $transid, + public readonly ?string $orderId, + public readonly int $httpStatus, + #[\SensitiveParameter] public readonly array $data, + #[\SensitiveParameter] public readonly string $raw, + ) { + } + + /** SUCCESS, FAILED or NOT_FOUND. */ + public function isFinal(): bool + { + return $this->status->isFinal(); + } + + public function isSuccess(): bool + { + return $this->status === Status::Success; + } + + /** + * The first `data` entry, or an empty array. + * + * @return array + */ + public function entry(): array + { + return $this->data[0] ?? []; + } + + /** + * Printing a result shows the body with secrets and personal data masked. + * + * @return array + */ + public function __debugInfo(): array + { + $redactor = new Redactor(); + + return [ + 'operation' => $this->operation->value, + 'status' => $this->status->value, + 'resultCode' => $this->resultCode, + 'result' => $this->result, + 'message' => $this->message, + 'reference' => $this->reference, + 'transid' => $this->transid, + 'orderId' => $this->orderId, + 'httpStatus' => $this->httpStatus, + 'data' => array_map(static fn (array $entry): array => $redactor->redactParams($entry), $this->data), + 'raw' => $redactor->redactJson($this->raw), + ]; + } + + protected function entryString(string $key): ?string + { + $value = $this->entry()[$key] ?? null; + + return is_string($value) ? $value : (is_int($value) ? (string) $value : null); + } +} diff --git a/src/Result/ResultFactory.php b/src/Result/ResultFactory.php new file mode 100644 index 0000000..2373cff --- /dev/null +++ b/src/Result/ResultFactory.php @@ -0,0 +1,62 @@ + $sentParams The parameters that were sent, to fill in the transid or order_id + * + * @throws InvalidResponseException when there is no verdict and the operation moves no money + */ + public static function create(Operation $operation, int $httpStatus, #[\SensitiveParameter] string $rawBody, #[\SensitiveParameter] array $sentParams = []): Result + { + [$status, $code, $body] = ResponseClassifier::classify($operation->kind(), $httpStatus, $rawBody); + $body ??= []; + + $str = static fn (mixed $v): ?string => is_string($v) ? $v : (is_int($v) ? (string) $v : null); + $data = []; + if (isset($body['data']) && is_array($body['data']) && array_is_list($body['data'])) { + foreach ($body['data'] as $entry) { + if (is_array($entry)) { + /** @var array $entry */ + $data[] = $entry; + } + } + } + + $class = match ($operation) { + Operation::CheckoutCreateOrder, Operation::CheckoutCreateOrderMinimal => CreateOrderResult::class, + Operation::CheckoutOrderStatus => OrderStatusResult::class, + Operation::CheckoutListOrders => ListOrdersResult::class, + Operation::CheckoutStoredCards => StoredCardsResult::class, + Operation::UtilityPaymentLookup, Operation::WalletCashinNameLookup => LookupResult::class, + Operation::UtilityPaymentProcess, Operation::UtilityPaymentQuery, + Operation::WalletCashinProcess, Operation::WalletCashinQuery => PayoutResult::class, + Operation::VendorBalance => BalanceResult::class, + default => Result::class, + }; + + return new $class( + $operation, + $status, + $code, + $str($body['result'] ?? null), + $str($body['message'] ?? null), + $str($body['reference'] ?? null), + $str($body['transid'] ?? null) ?? $str($sentParams['transid'] ?? null), + $str($body['order_id'] ?? null) ?? $str($sentParams['order_id'] ?? null), + $httpStatus, + $data, + $rawBody, + ); + } +} diff --git a/src/Result/StoredCard.php b/src/Result/StoredCard.php new file mode 100644 index 0000000..24b28e8 --- /dev/null +++ b/src/Result/StoredCard.php @@ -0,0 +1,55 @@ + $entry + */ + public static function fromEntry(array $entry): self + { + $str = static fn (string $key): ?string => isset($entry[$key]) && is_scalar($entry[$key]) ? (string) $entry[$key] : null; + + return new self( + $str('id'), + $str('masked_card'), + $str('creation_date'), + $str('name'), + $str('card_type'), + $str('card_token'), + ); + } + + /** @return array */ + public function __debugInfo(): array + { + return [ + 'id' => $this->id, + 'maskedCard' => $this->maskedCard, + 'creationDate' => $this->creationDate, + 'name' => $this->name === null ? null : '[REDACTED]', + 'cardType' => $this->cardType, + 'cardToken' => $this->cardToken === null ? null : '[REDACTED]', + ]; + } +} diff --git a/src/Result/StoredCardsResult.php b/src/Result/StoredCardsResult.php new file mode 100644 index 0000000..a7749e8 --- /dev/null +++ b/src/Result/StoredCardsResult.php @@ -0,0 +1,17 @@ + */ + public function cards(): array + { + return array_map(static fn (array $entry): StoredCard => StoredCard::fromEntry($entry), $this->data); + } +} diff --git a/src/SecretVault.php b/src/SecretVault.php new file mode 100644 index 0000000..ebb5c69 --- /dev/null +++ b/src/SecretVault.php @@ -0,0 +1,31 @@ +>|null */ + private static ?\WeakMap $store = null; + + /** + * @param array $values + */ + public static function put(object $owner, #[\SensitiveParameter] array $values): void + { + self::$store ??= new \WeakMap(); + self::$store[$owner] = $values; + } + + public static function get(object $owner, string $key): ?string + { + return self::$store[$owner][$key] ?? null; + } +} diff --git a/src/Signing/DigestSigner.php b/src/Signing/DigestSigner.php new file mode 100644 index 0000000..fd0f5a1 --- /dev/null +++ b/src/Signing/DigestSigner.php @@ -0,0 +1,17 @@ + $secret]); + } + + private function __clone() + { + } + + public function method(): string + { + return 'HS256'; + } + + public function sign(#[\SensitiveParameter] string $signingString): string + { + return base64_encode(hash_hmac('sha256', $signingString, SecretVault::get($this, 'secret') ?? '', true)); + } + + /** @return array */ + public function __debugInfo(): array + { + return ['method' => 'HS256', 'secret' => '[REDACTED]']; + } + + public function __serialize(): array + { + throw new \LogicException('Hs256DigestSigner holds a secret and cannot be serialised.'); + } +} diff --git a/src/Signing/RequestSigner.php b/src/Signing/RequestSigner.php new file mode 100644 index 0000000..14b1c96 --- /dev/null +++ b/src/Signing/RequestSigner.php @@ -0,0 +1,214 @@ + $params Parameters in send order; nested arrays flatten to dotted keys + * @param string $timestamp Used for the header and the signing string, character for character + * + * @throws SigningException + */ + public static function sign( + string $method, + #[\SensitiveParameter] array $params, + string $timestamp, + #[\SensitiveParameter] string $apiKey, + DigestSigner $digestSigner, + ): SignedRequest { + $method = strtoupper($method); + if (!in_array($method, self::METHODS, true)) { + throw new SigningException('UNSUPPORTED_METHOD', $method); + } + if ($apiKey === '') { + throw new SigningException('EMPTY_API_KEY', 'refusing to build Authorization from an empty key'); + } + Timestamp::assertValid($timestamp); + + $flat = self::flatten($params); + $signedFields = implode(',', array_map(static fn (array $pair): string => $pair[0], $flat)); + $signingString = self::signingString($timestamp, $flat); + $digest = $digestSigner->sign($signingString); + if ($digest === '') { + throw new SigningException('EMPTY_DIGEST', 'refusing to send an empty Digest'); + } + + return new SignedRequest( + flattened: $flat, + signedFields: $signedFields, + signingString: $signingString, + authorization: 'SELCOM ' . base64_encode($apiKey), + digestMethod: $digestSigner->method(), + digest: $digest, + timestamp: $timestamp, + query: $method === 'POST' ? null : self::encodeQuery($flat), + body: $method === 'POST' ? self::encodeBody($flat) : null, + ); + } + + /** + * Flatten nested arrays to dotted keys in place, keeping order, and normalise every value. + * + * @param array $params + * @return list + * + * @throws SigningException + */ + public static function flatten(#[\SensitiveParameter] array $params): array + { + $flat = []; + $seen = []; + self::walk('', $params, $flat, $seen); + if ($flat === []) { + throw new SigningException('EMPTY_PARAMS', 'there is nothing to sign'); + } + + return $flat; + } + + /** + * The text of one normalised value inside the signing string. + */ + public static function valueText(#[\SensitiveParameter] bool|int|string $value): string + { + return match (true) { + is_bool($value) => $value ? 'true' : 'false', + is_int($value) => (string) $value, + default => $value, + }; + } + + /** + * @param array $object + * @param list $flat + * @param array $seen + */ + private static function walk(string $prefix, #[\SensitiveParameter] array $object, array &$flat, array &$seen): void + { + if ($prefix !== '' && $object === []) { + throw new SigningException('EMPTY_OBJECT', $prefix . ' is an empty object; omit it'); + } + if ($prefix !== '' && array_is_list($object)) { + throw new SigningException('UNSUPPORTED_TYPE', $prefix . ': arrays cannot be signed (there is no flat form)'); + } + foreach ($object as $rawKey => $value) { + $rawKey = (string) $rawKey; + if ($rawKey === '') { + throw new SigningException('INVALID_KEY', 'empty key under ' . ($prefix === '' ? 'root' : $prefix)); + } + $key = $prefix === '' ? $rawKey : $prefix . '.' . $rawKey; + if (preg_match(self::KEY_PATTERN, $key) !== 1) { + throw new SigningException('INVALID_KEY', '"' . $key . '" has characters outside [A-Za-z0-9_.-]'); + } + if (is_array($value)) { + if ($value !== [] && array_is_list($value)) { + throw new SigningException('UNSUPPORTED_TYPE', $key . ': arrays cannot be signed (there is no flat form)'); + } + self::walk($key, $value, $flat, $seen); + continue; + } + if (isset($seen[$key])) { + throw new SigningException('DUPLICATE_KEY', $key . ' appears twice after flattening'); + } + $seen[$key] = true; + $flat[] = [$key, self::normalise($key, $value)]; + } + } + + /** + * Normalise one scalar: the value that is both signed and sent. + * + * @throws SigningException + */ + public static function normalise(string $key, #[\SensitiveParameter] mixed $value): bool|int|string + { + if ($value === null) { + return ''; + } + if (is_bool($value) || is_string($value)) { + return $value; + } + if (is_int($value)) { + if (abs($value) > self::MAX_SAFE_INTEGER) { + throw new SigningException('NUMBER_OUT_OF_RANGE', $key . ': send integers above 2^53-1 as strings'); + } + + return $value; + } + if (is_float($value)) { + if (!is_finite($value) || floor($value) !== $value) { + throw new SigningException('NON_INTEGER_NUMBER', $key . ': ' . var_export($value, true) . ' has a fractional part'); + } + if (abs($value) > (float) self::MAX_SAFE_INTEGER) { + throw new SigningException('NUMBER_OUT_OF_RANGE', $key . ': send integers above 2^53-1 as strings'); + } + + return (int) $value; + } + + throw new SigningException('UNSUPPORTED_TYPE', $key . ': ' . get_debug_type($value) . ' values cannot be signed'); + } + + /** + * @param list $flat + */ + public static function signingString(string $timestamp, #[\SensitiveParameter] array $flat): string + { + $out = 'timestamp=' . $timestamp; + foreach ($flat as [$key, $value]) { + $out .= '&' . $key . '=' . self::valueText($value); + } + + return $out; + } + + /** + * @param list $flat + */ + private static function encodeQuery(#[\SensitiveParameter] array $flat): string + { + $parts = []; + foreach ($flat as [$key, $value]) { + // rawurlencode is RFC 3986: only A-Z a-z 0-9 - . _ ~ stay as they are. + $parts[] = rawurlencode($key) . '=' . rawurlencode(self::valueText($value)); + } + + return implode('&', $parts); + } + + /** + * Built by hand: a PHP array would turn a key such as "0" into a list index. + * + * @param list $flat + */ + private static function encodeBody(#[\SensitiveParameter] array $flat): string + { + $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR; + $parts = []; + foreach ($flat as [$key, $value]) { + try { + $parts[] = json_encode($key, $flags) . ':' . json_encode($value, $flags); + } catch (\JsonException $e) { + throw new SigningException('INVALID_STRING', $key . ' is not valid UTF-8'); + } + } + + return '{' . implode(',', $parts) . '}'; + } +} diff --git a/src/Signing/SignedRequest.php b/src/Signing/SignedRequest.php new file mode 100644 index 0000000..b3927ce --- /dev/null +++ b/src/Signing/SignedRequest.php @@ -0,0 +1,56 @@ + $flattened Ordered (key, normalised value) pairs + * @param string|null $query Percent-encoded query string for GET and DELETE + * @param string|null $body Compact JSON object with flat keys for POST + */ + public function __construct( + public readonly array $flattened, + public readonly string $signedFields, + public readonly string $signingString, + public readonly string $authorization, + public readonly string $digestMethod, + public readonly string $digest, + public readonly string $timestamp, + public readonly ?string $query, + public readonly ?string $body, + ) { + } + + /** + * The signing headers. Add Accept and, on POST, Content-Type yourself (the client does). + * + * @return array + */ + public function headers(): array + { + return [ + 'Authorization' => $this->authorization, + 'Digest-Method' => $this->digestMethod, + 'Digest' => $this->digest, + 'Timestamp' => $this->timestamp, + 'Signed-Fields' => $this->signedFields, + ]; + } + + /** @return array */ + public function __debugInfo(): array + { + return [ + 'signedFields' => $this->signedFields, + 'timestamp' => $this->timestamp, + 'digest' => '[REDACTED]', + 'authorization' => '[REDACTED]', + ]; + } +} diff --git a/src/Signing/Timestamp.php b/src/Signing/Timestamp.php new file mode 100644 index 0000000..82a8d77 --- /dev/null +++ b/src/Signing/Timestamp.php @@ -0,0 +1,60 @@ +setTimezone($zone); + + return $moment->format('Y-m-d\TH:i:sP'); + } + + public static function isValid(string $timestamp): bool + { + return self::parse($timestamp) !== null; + } + + /** + * @throws SigningException INVALID_TIMESTAMP + */ + public static function assertValid(string $timestamp): void + { + if (!self::isValid($timestamp)) { + throw new SigningException( + 'INVALID_TIMESTAMP', + '"' . $timestamp . '" is not yyyy-MM-ddTHH:mm:ss+HH:MM or +HHMM' + ); + } + } + + /** The instant a valid timestamp denotes, or null when it is malformed or impossible. */ + public static function parse(string $timestamp): ?\DateTimeImmutable + { + if (preg_match(self::PATTERN, $timestamp) !== 1) { + return null; + } + $format = str_contains(substr($timestamp, 19), ':') ? 'Y-m-d\TH:i:sP' : 'Y-m-d\TH:i:sO'; + $moment = \DateTimeImmutable::createFromFormat($format, $timestamp); + if ($moment === false) { + return null; + } + // createFromFormat rolls impossible dates over (month 13, 31 February): reject them. + if ($moment->format('Y-m-d\TH:i:s') !== substr($timestamp, 0, 19)) { + return null; + } + + return $moment; + } +} diff --git a/src/Status.php b/src/Status.php new file mode 100644 index 0000000..f976dc8 --- /dev/null +++ b/src/Status.php @@ -0,0 +1,30 @@ + true, + self::Pending, self::Ambiguous => false, + }; + } +} diff --git a/src/SystemClock.php b/src/SystemClock.php new file mode 100644 index 0000000..2cdcf87 --- /dev/null +++ b/src/SystemClock.php @@ -0,0 +1,18 @@ +getPrevious()) { + $context = self::handlerContext($e); + if ($context !== null) { + $verdict = self::fromCurlContext($context); + if ($verdict !== null) { + return $verdict; + } + } + $message = $e->getMessage(); + if (preg_match('/cURL error (\d+)/', $message, $m) === 1 + && in_array((int) $m[1], self::CURL_CONNECT_PHASE, true) + ) { + return TransportFailure::NotSent; + } + if (preg_match(self::CONNECT_MESSAGE, $message) === 1 + && preg_match('/timed? ?out|reset|aborted|broken pipe|empty reply|bad record|decrypt/i', $message) !== 1 + ) { + return TransportFailure::NotSent; + } + } + + return TransportFailure::UnknownOutcome; + } + + /** + * A short description of the failure that is safe to keep: the exception classes and the cURL + * error number, never the message or the request. + */ + public static function summary(\Throwable $error): \RuntimeException + { + $classes = []; + $errno = null; + for ($e = $error; $e !== null; $e = $e->getPrevious()) { + $classes[] = $e::class; + $context = self::handlerContext($e); + if ($errno === null && $context !== null && is_int($context['errno'] ?? null)) { + $errno = $context['errno']; + } + if ($errno === null && preg_match('/cURL error (\d+)/', $e->getMessage(), $m) === 1) { + $errno = (int) $m[1]; + } + } + + return new \RuntimeException( + 'Underlying error: ' . implode(' <- ', $classes) . ($errno === null ? '' : ', cURL errno ' . $errno) + ); + } + + /** + * Guzzle (and compatible clients) expose cURL details through getHandlerContext(). + * + * @return array|null + */ + private static function handlerContext(\Throwable $e): ?array + { + if (!method_exists($e, 'getHandlerContext')) { + return null; + } + $context = $e->getHandlerContext(); + + return is_array($context) ? $context : null; + } + + /** + * @param array $context + */ + private static function fromCurlContext(array $context): ?TransportFailure + { + $errno = $context['errno'] ?? null; + if (!is_int($errno)) { + return null; + } + if (self::sentSomething($context)) { + return TransportFailure::UnknownOutcome; + } + if (in_array($errno, self::CURL_CONNECT_PHASE, true)) { + return TransportFailure::NotSent; + } + if ($errno === self::CURL_TIMEOUT) { + // A timeout is a connect timeout only when cURL reports that no request bytes were + // written: both counters are present and zero. Missing counters prove nothing. + if (self::reportsNothingSent($context)) { + return TransportFailure::NotSent; + } + } + + return TransportFailure::UnknownOutcome; + } + + /** + * @param array $context + */ + private static function sentSomething(array $context): bool + { + foreach (self::SENT_KEYS as $key) { + $value = $context[$key] ?? null; + if ((is_float($value) || is_int($value)) && (float) $value > 0.0) { + return true; + } + } + + return false; + } + + /** + * @param array $context + */ + private static function reportsNothingSent(array $context): bool + { + foreach (self::SENT_KEYS as $key) { + $value = $context[$key] ?? null; + if (!(is_float($value) || is_int($value)) || (float) $value !== 0.0) { + return false; + } + } + + return true; + } +} diff --git a/src/Transport/Psr18Transport.php b/src/Transport/Psr18Transport.php new file mode 100644 index 0000000..5c59efd --- /dev/null +++ b/src/Transport/Psr18Transport.php @@ -0,0 +1,152 @@ + ...)`: you build one client + * per profile, applying `$p->connectSeconds`, `$p->readSeconds` and, when `$p->freshConnection` + * is true (the payment profile), a new connection per request with no reuse. + * 3. `new Psr18Transport($client, clientManagesTimeouts: true)`: a ready client whose own timeouts + * and connection handling you have configured. The flag is required, so this is always a choice. + * + * The client you supply must not retry requests on its own (no retry middleware): a repeated POST + * is a second payment attempt. + * + * Responses of any HTTP status are returned, never thrown. A failed send is thrown as + * TransportException, classified by FailureClassifier, with a short summary as its cause: the + * client's own exception is not chained, because its message and request carry request data. + */ +final class Psr18Transport implements Transport +{ + /** @var ClientInterface|\Closure(TimeoutProfile): ClientInterface */ + private ClientInterface|\Closure $client; + + /** @var array */ + private array $built = []; + + private readonly RequestFactoryInterface $requests; + private readonly StreamFactoryInterface $streams; + + /** + * @param ClientInterface|\Closure(TimeoutProfile): ClientInterface|null $client Null: a Guzzle client per profile + * @param bool $clientManagesTimeouts Required `true` when `$client` is a ready client + * + * @throws ConfigurationException when no timeout-aware client can be set up + */ + public function __construct( + ClientInterface|\Closure|null $client = null, + ?RequestFactoryInterface $requestFactory = null, + ?StreamFactoryInterface $streamFactory = null, + bool $clientManagesTimeouts = false, + ) { + if ($client instanceof ClientInterface && !$clientManagesTimeouts) { + throw new ConfigurationException( + 'A ready PSR-18 client cannot be given the required timeouts. Pass a closure that builds a client ' + . 'per TimeoutProfile, or pass clientManagesTimeouts: true to confirm that the client applies ' + . 'the connect and read timeouts (and a fresh connection for payments) itself.' + ); + } + if ($client === null) { + if (!class_exists(\GuzzleHttp\Client::class)) { + throw new ConfigurationException( + 'No client was given and Guzzle is not installed. Install guzzlehttp/guzzle, or pass a closure ' + . 'that builds a PSR-18 client per TimeoutProfile.' + ); + } + $client = static fn (TimeoutProfile $p): ClientInterface => new \GuzzleHttp\Client(self::guzzleOptions($p)); + } + $this->client = $client; + $this->requests = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory(); + $this->streams = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory(); + } + + /** Guzzle through the default route; see the class comment. */ + public static function discover(): self + { + return new self(); + } + + /** + * Options of the default Guzzle client for a profile. Guzzle's `timeout` is a total limit, so + * the read allowance is added to the connect one. Payment requests use a new connection each + * time and do not leave it open for reuse. + * + * @return array + */ + public static function guzzleOptions(TimeoutProfile $timeouts): array + { + $options = [ + 'connect_timeout' => $timeouts->connectSeconds, + 'timeout' => $timeouts->connectSeconds + $timeouts->readSeconds, + 'allow_redirects' => false, + 'http_errors' => false, + ]; + if ($timeouts->freshConnection && defined('CURLOPT_FRESH_CONNECT') && defined('CURLOPT_FORBID_REUSE')) { + $options['curl'] = [CURLOPT_FRESH_CONNECT => true, CURLOPT_FORBID_REUSE => true]; + } + + return $options; + } + + public function send(#[\SensitiveParameter] TransportRequest $request): TransportResponse + { + try { + $psrRequest = $this->requests->createRequest($request->method, $request->url); + foreach ($request->headers as $name => $value) { + $psrRequest = $psrRequest->withHeader($name, $value); + } + if ($request->body !== null) { + $psrRequest = $psrRequest->withBody($this->streams->createStream($request->body)); + } + $response = $this->clientFor($request->timeouts)->sendRequest($psrRequest); + $body = (string) $response->getBody(); + } catch (ClientExceptionInterface $e) { + throw new TransportException( + FailureClassifier::classify($e), + 'The HTTP client failed before a response arrived: ' . $e::class, + FailureClassifier::summary($e), + ); + } catch (\Throwable $e) { + // Anything else after the request may have been written: the outcome is unknown. + throw new TransportException( + TransportFailure::UnknownOutcome, + 'The HTTP exchange failed: ' . $e::class, + FailureClassifier::summary($e), + ); + } + + $headers = []; + foreach ($response->getHeaders() as $name => $values) { + $headers[(string) $name] = implode(', ', $values); + } + + return new TransportResponse($response->getStatusCode(), $body, $headers); + } + + private function clientFor(TimeoutProfile $timeouts): ClientInterface + { + if ($this->client instanceof ClientInterface) { + return $this->client; + } + $key = $timeouts->connectSeconds . '/' . $timeouts->readSeconds . '/' . ($timeouts->freshConnection ? 'fresh' : 'reuse'); + + return $this->built[$key] ??= ($this->client)($timeouts); + } +} diff --git a/src/Transport/TimeoutProfile.php b/src/Transport/TimeoutProfile.php new file mode 100644 index 0000000..1141cc0 --- /dev/null +++ b/src/Transport/TimeoutProfile.php @@ -0,0 +1,27 @@ + 0.0) || !($readSeconds > 0.0)) { + throw new ConfigurationException('Timeouts must be greater than zero.'); + } + } +} diff --git a/src/Transport/Timeouts.php b/src/Transport/Timeouts.php new file mode 100644 index 0000000..92da7a0 --- /dev/null +++ b/src/Transport/Timeouts.php @@ -0,0 +1,50 @@ +query = $query ?? new TimeoutProfile(10.0, 10.0); + $this->payment = $payment === null + ? new TimeoutProfile(15.0, 180.0, true) + : new TimeoutProfile($payment->connectSeconds, $payment->readSeconds, true); + } + + public function forKind(OperationKind $kind): TimeoutProfile + { + return $kind === OperationKind::Payment ? $this->payment : $this->query; + } + + /** + * The profile for an operation. Payments use the payment profile. Writes (create, cancel, + * delete) keep the query timeouts but use a fresh connection, like payments, because they + * are never repeated. + */ + public function forOperation(Operation $operation): TimeoutProfile + { + $profile = $this->forKind($operation->kind()); + if ($operation->isWrite() && !$profile->freshConnection) { + return new TimeoutProfile($profile->connectSeconds, $profile->readSeconds, true); + } + + return $profile; + } +} diff --git a/src/Transport/Transport.php b/src/Transport/Transport.php new file mode 100644 index 0000000..d5baddf --- /dev/null +++ b/src/Transport/Transport.php @@ -0,0 +1,24 @@ +timeouts`. Never retry. + */ +interface Transport +{ + /** + * @throws TransportException + */ + public function send(TransportRequest $request): TransportResponse; +} diff --git a/src/Transport/TransportFailure.php b/src/Transport/TransportFailure.php new file mode 100644 index 0000000..6e41d0b --- /dev/null +++ b/src/Transport/TransportFailure.php @@ -0,0 +1,24 @@ + $headers + */ + public function __construct( + public readonly string $method, + public readonly string $url, + #[\SensitiveParameter] public readonly array $headers, + #[\SensitiveParameter] public readonly ?string $body, + public readonly TimeoutProfile $timeouts, + ) { + } + + /** + * Headers safe to log: Authorization and Digest are replaced. + * + * @return array + */ + public function redactedHeaders(): array + { + $out = []; + foreach ($this->headers as $name => $value) { + $out[$name] = in_array(strtolower($name), ['authorization', 'digest'], true) ? Redactor::REDACTED : $value; + } + + return $out; + } + + /** The body safe to log: secrets and personal data masked. Null when there is no body. */ + public function redactedBody(): ?string + { + return $this->body === null ? null : (new Redactor())->redactJson($this->body, $this->path()); + } + + /** The URL safe to log: the query string is masked. */ + public function redactedUrl(): string + { + $parts = explode('?', $this->url, 2); + + return isset($parts[1]) ? $parts[0] . '?' . (new Redactor())->redactQuery($parts[1], $this->path()) : $this->url; + } + + /** @return array */ + public function __debugInfo(): array + { + return [ + 'method' => $this->method, + 'url' => $this->redactedUrl(), + 'headers' => $this->redactedHeaders(), + 'body' => $this->redactedBody(), + 'timeouts' => $this->timeouts, + ]; + } + + private function path(): string + { + $path = parse_url($this->url, PHP_URL_PATH); + + return is_string($path) ? $path : ''; + } +} diff --git a/src/Transport/TransportResponse.php b/src/Transport/TransportResponse.php new file mode 100644 index 0000000..efb3e1e --- /dev/null +++ b/src/Transport/TransportResponse.php @@ -0,0 +1,21 @@ + $headers + */ + public function __construct( + public readonly int $status, + #[\SensitiveParameter] public readonly string $body, + public readonly array $headers = [], + ) { + } +} diff --git a/src/Webhook/InMemoryReplayStore.php b/src/Webhook/InMemoryReplayStore.php new file mode 100644 index 0000000..ab0e2a8 --- /dev/null +++ b/src/Webhook/InMemoryReplayStore.php @@ -0,0 +1,41 @@ + digest => last second the entry is live (unix time) */ + private array $liveThrough = []; + + private readonly ClockInterface $clock; + + public function __construct(?ClockInterface $clock = null) + { + $this->clock = $clock ?? new SystemClock(); + } + + public function seen(string $digest, int $keepUntil): bool + { + $now = $this->clock->now()->getTimestamp(); + foreach ($this->liveThrough as $key => $last) { + if ($last < $now) { + unset($this->liveThrough[$key]); + } + } + if (isset($this->liveThrough[$digest])) { + return true; + } + $this->liveThrough[$digest] = $keepUntil; + + return false; + } +} diff --git a/src/Webhook/ReplayStore.php b/src/Webhook/ReplayStore.php new file mode 100644 index 0000000..014b717 --- /dev/null +++ b/src/Webhook/ReplayStore.php @@ -0,0 +1,23 @@ + $fields The whole decoded body + */ + public function __construct( + public readonly ?string $orderId, + public readonly ?string $transid, + public readonly ?string $reference, + public readonly ?string $result, + public readonly ?string $resultCode, + public readonly ?string $paymentStatus, + public readonly ?string $channel, + /** Whole TZS, parsed strictly from text such as "10,000"; null when absent or not a whole amount. */ + public readonly ?int $amountTzs, + #[\SensitiveParameter] public readonly ?string $phone, + #[\SensitiveParameter] public readonly array $fields, + ) { + } + + /** + * @throws ValidationException when the body is not a JSON object + */ + public static function fromRawBody(string $rawBody): self + { + $body = json_decode($rawBody, true); + if (!is_array($body) || ($body !== [] && array_is_list($body))) { + throw new ValidationException('The webhook body is not a JSON object.'); + } + /** @var array $body */ + $str = static fn (string $key): ?string => isset($body[$key]) && is_scalar($body[$key]) ? (string) $body[$key] : null; + + return new self( + $str('order_id'), + $str('transid'), + $str('reference'), + $str('result'), + ResponseClassifier::normaliseResultCode($body['resultcode'] ?? null), + $str('payment_status'), + $str('channel'), + Amounts::tryParse($body['amount'] ?? null), + $str('phone') ?? $str('msisdn'), + $body, + ); + } + + /** + * Printing a payload shows masked data only. + * + * @return array + */ + public function __debugInfo(): array + { + return [ + 'orderId' => $this->orderId, + 'transid' => $this->transid, + 'reference' => $this->reference, + 'result' => $this->result, + 'resultCode' => $this->resultCode, + 'paymentStatus' => $this->paymentStatus, + 'channel' => $this->channel, + 'amountTzs' => $this->amountTzs, + 'fields' => (new Redactor())->redactParams($this->fields), + ]; + } + + /** The delivery's key for deduplication: (order_id, transid). Null when either is missing. */ + public function dedupeKey(): ?string + { + return $this->orderId === null || $this->transid === null ? null : $this->orderId . '|' . $this->transid; + } +} diff --git a/src/Webhook/WebhookVerdict.php b/src/Webhook/WebhookVerdict.php new file mode 100644 index 0000000..d10a754 --- /dev/null +++ b/src/Webhook/WebhookVerdict.php @@ -0,0 +1,35 @@ + 200, + self::Invalid, self::Stale => 401, + }; + } + + /** Whether to process the delivery (then confirm with orderStatus). REPLAY was already handled. */ + public function shouldProcess(): bool + { + return $this === self::Valid || $this === self::Unsigned; + } +} diff --git a/src/Webhook/WebhookVerifier.php b/src/Webhook/WebhookVerifier.php new file mode 100644 index 0000000..0c4fb62 --- /dev/null +++ b/src/Webhook/WebhookVerifier.php @@ -0,0 +1,224 @@ +signer = new Hs256DigestSigner($secret); + $this->clock = $clock ?? new SystemClock(); + $this->replayStore = $replayStore ?? new InMemoryReplayStore($this->clock); + } + + /** + * @param array> $headers Header names are matched case-insensitively + * + * @throws ReplayStoreException when the replay store fails (answer 5xx) + */ + public function verify(#[\SensitiveParameter] array $headers, #[\SensitiveParameter] string $rawBody): WebhookVerdict + { + try { + return $this->decide($headers, $rawBody); + } catch (ReplayStoreException $e) { + throw $e; + } catch (\Throwable) { + return WebhookVerdict::Invalid; + } + } + + /** @return array */ + public function __debugInfo(): array + { + return ['windowSeconds' => $this->windowSeconds]; + } + + /** + * @param array> $headers + */ + private function decide(array $headers, string $rawBody): WebhookVerdict + { + // 1. No Digest header: nothing to check. + $digest = self::header($headers, 'Digest'); + if ($digest === null) { + return WebhookVerdict::Unsigned; + } + // 2. Empty digest, or a method this verifier is not configured for. + if ($digest === '' || self::header($headers, 'Digest-Method') !== $this->signer->method()) { + return WebhookVerdict::Invalid; + } + + // 3. Timestamp format, body shape, Signed-Fields present. + $timestamp = self::header($headers, 'Timestamp') ?? ''; + $signedFields = self::header($headers, 'Signed-Fields') ?? ''; + $moment = Timestamp::parse($timestamp); + if ($moment === null || $signedFields === '' || strlen($rawBody) > self::MAX_BODY_BYTES) { + return WebhookVerdict::Invalid; + } + $body = json_decode($rawBody, true); + if (!is_array($body) || ($body !== [] && array_is_list($body))) { + return WebhookVerdict::Invalid; + } + + // 4. order_id and transid must always be signed. + $names = explode(',', $signedFields); + if (count($names) > self::MAX_SIGNED_FIELDS) { + return WebhookVerdict::Invalid; + } + foreach (self::REQUIRED_FIELDS as $required) { + if (!in_array($required, $names, true)) { + return WebhookVerdict::Invalid; + } + } + + // 5 and 6. Values come from the body; normalisation is cheap and bounded, and runs + // before the digest check. Names and values may not contain "&". + $flat = []; + foreach ($names as $field) { + [$found, $value] = self::lookup($body, $field); + if (!$found || str_contains($field, '&')) { + return WebhookVerdict::Invalid; + } + $normalised = self::normalise($value); + if ($normalised === null || str_contains(RequestSigner::valueText($normalised), '&')) { + return WebhookVerdict::Invalid; + } + $flat[] = [$field, $normalised]; + } + + // 7. Constant-time digest comparison. + $expected = $this->signer->sign(RequestSigner::signingString($timestamp, $flat)); + if (!hash_equals($expected, $digest)) { + return WebhookVerdict::Invalid; + } + + // 8. Window, in either direction. + $now = $this->clock->now()->getTimestamp(); + $signedAt = $moment->getTimestamp(); + if (abs($now - $signedAt) > $this->windowSeconds) { + return WebhookVerdict::Stale; + } + + // 9. Replay: keep the digest until max(now, signed time) + window. + try { + $replayed = $this->replayStore->seen($digest, max($now, $signedAt) + $this->windowSeconds); + } catch (\Throwable $e) { + throw new ReplayStoreException('The replay store failed: ' . $e::class); + } + if ($replayed) { + return WebhookVerdict::Replay; + } + + return WebhookVerdict::Valid; + } + + /** + * The scalar that is signed, or null when the value cannot be used. Numbers must be whole + * and within 2^53 - 1; this is decided on the decoded value, without expanding anything. + */ + private static function normalise(mixed $value): bool|int|string|null + { + if ($value === null) { + return ''; + } + if (is_string($value) || is_bool($value)) { + return $value; + } + if (is_int($value)) { + return abs($value) > RequestSigner::MAX_SAFE_INTEGER ? null : $value; + } + if (is_float($value)) { + // Zero is refused too: a float zero may be a number that underflowed while decoding. + if (!is_finite($value) || $value === 0.0 || floor($value) !== $value + || abs($value) > (float) RequestSigner::MAX_SAFE_INTEGER + ) { + return null; + } + + return (int) $value; + } + + return null; + } + + /** + * @param array> $headers + */ + private static function header(array $headers, string $name): ?string + { + foreach ($headers as $key => $value) { + if (strcasecmp((string) $key, $name) === 0) { + if (is_array($value)) { + return $value[0] ?? ''; + } + + return $value; + } + } + + return null; + } + + /** + * A name is looked up flat first, then (for dotted names) by walking nested objects. + * + * @param array $body + * @return array{0: bool, 1: mixed} + */ + private static function lookup(array $body, string $field): array + { + if (array_key_exists($field, $body)) { + return [true, $body[$field]]; + } + $node = $body; + foreach (explode('.', $field) as $part) { + if (!is_array($node) || !array_key_exists($part, $node)) { + return [false, null]; + } + $node = $node[$part]; + } + + return [true, $node]; + } +} diff --git a/tests/ClientTest.php b/tests/ClientTest.php new file mode 100644 index 0000000..b225dfd --- /dev/null +++ b/tests/ClientTest.php @@ -0,0 +1,211 @@ +queue(new TransportResponse(200, self::SUCCESS)); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T07:30:46+00:00')); + + $result = $client->utilityPayment(new UtilityPaymentRequest('TXN-UTL-0001', 'LUKU', '01234567891', 8000)); + + self::assertSame(Status::Success, $result->status); + self::assertSame('RCPT-1', $result->receipt()); + self::assertSame('TXN-UTL-0001', $result->transid); + + $sent = $transport->sent[0]; + self::assertSame('POST', $sent->method); + self::assertSame('https://apigwtest.selcommobile.com/v1/utilitypayment/process', $sent->url); + self::assertSame( + '{"transid":"TXN-UTL-0001","utilitycode":"LUKU","utilityref":"01234567891","amount":8000,"vendor":"TILL123","pin":"0000"}', + $sent->body, + ); + // The clock said 07:30:46 UTC; the timestamp is generated in Dar es Salaam time, colon form. + self::assertSame('2026-11-21T10:30:46+03:00', $sent->headers['Timestamp']); + self::assertSame('transid,utilitycode,utilityref,amount,vendor,pin', $sent->headers['Signed-Fields']); + self::assertSame('HS256', $sent->headers['Digest-Method']); + self::assertSame('application/json', $sent->headers['Content-Type']); + self::assertSame('selcom-php/0.1.0', $sent->headers['User-Agent']); + self::assertSame(180.0, $sent->timeouts->readSeconds); + self::assertSame(15.0, $sent->timeouts->connectSeconds); + self::assertSame('[REDACTED]', $sent->redactedHeaders()['Digest']); + } + + public function testGetGoesInTheQueryStringWithQueryTimeouts(): void + { + $transport = (new FakeTransport())->queue(new TransportResponse(200, self::SUCCESS)); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + $client->utilityQuery(new UtilityQueryRequest('TXN-UTL-0001')); + + $sent = $transport->sent[0]; + self::assertSame('GET', $sent->method); + self::assertSame('https://apigwtest.selcommobile.com/v1/utilitypayment/query?transid=TXN-UTL-0001', $sent->url); + self::assertNull($sent->body); + self::assertArrayNotHasKey('Content-Type', $sent->headers); + self::assertSame(10.0, $sent->timeouts->readSeconds); + } + + public function testPaymentsAreNeverRetriedEvenWhenNotSentAndRetriesAreOn(): void + { + $config = new Config(Environment::Sandbox, Fixtures::credentials(), maxNotSentRetries: 3); + $transport = (new FakeTransport()) + ->queue(new TransportException(TransportFailure::NotSent, 'dns')) + ->queue(new TransportResponse(200, self::SUCCESS)); + $client = new Client($config, $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + try { + $client->walletCashin(new WalletCashinRequest('TXN-CSH-0001', 'CASHIN', '255700000002', 2500)); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + self::assertSame(TransportFailure::NotSent, $e->failure); + } + self::assertCount(1, $transport->sent); + } + + public function testWritesAreNeverRetried(): void + { + $config = new Config(Environment::Sandbox, Fixtures::credentials(), maxNotSentRetries: 3); + foreach ([Operation::CheckoutCancelOrder, Operation::CheckoutDeleteCard, Operation::CheckoutCreateOrderMinimal] as $op) { + $transport = (new FakeTransport()) + ->queue(new TransportException(TransportFailure::NotSent, 'refused')) + ->queue(new TransportResponse(200, self::SUCCESS)); + $client = new Client($config, $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + try { + $client->execute(Fixtures::request($op)); + self::fail('expected a TransportException'); + } catch (TransportException) { + self::assertCount(1, $transport->sent, $op->value); + } + } + } + + public function testUnknownOutcomeIsNeverRetried(): void + { + $config = new Config(Environment::Sandbox, Fixtures::credentials(), maxNotSentRetries: 3); + $transport = (new FakeTransport()) + ->queue(new TransportException(TransportFailure::UnknownOutcome, 'read timeout')) + ->queue(new TransportResponse(200, self::SUCCESS)); + $client = new Client($config, $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + $this->expectException(TransportException::class); + try { + $client->orderStatus(new OrderStatusRequest('ORD-1001')); + } finally { + self::assertCount(1, $transport->sent); + } + } + + public function testReadOnlyOperationRepeatsAfterNotSentOnlyWhenOptedInWithAFreshTimestamp(): void + { + $clock = FixedClock::at('2026-11-21T10:30:46+03:00'); + $body = '{"resultcode":"000","data":[{"order_id":"ORD-1001","payment_status":"COMPLETED","amount":"10,000","phone":"255700000001"}]}'; + + // Opted out (the default): the error is raised after one send. + $off = (new FakeTransport())->queue(new TransportException(TransportFailure::NotSent, 'dns')); + try { + (new Client(Fixtures::config(), $off, $clock))->orderStatus(new OrderStatusRequest('ORD-1001')); + self::fail('expected a TransportException'); + } catch (TransportException) { + self::assertCount(1, $off->sent); + } + + // Opted in: one repeat, with a new timestamp. + $on = (new FakeTransport()) + ->queue(new TransportException(TransportFailure::NotSent, 'dns')) + ->queue(new TransportResponse(200, $body)); + $config = new Config(Environment::Sandbox, Fixtures::credentials(), maxNotSentRetries: 1); + $on->afterSend = static fn () => $clock->advance(1); + $client2 = new Client($config, $on, $clock); + + $result = $client2->orderStatus(new OrderStatusRequest('ORD-1001')); + self::assertSame(Status::Success, $result->status); + self::assertCount(2, $on->sent); + self::assertSame('2026-11-21T10:30:46+03:00', $on->sent[0]->headers['Timestamp']); + self::assertSame('2026-11-21T10:30:47+03:00', $on->sent[1]->headers['Timestamp']); + self::assertNotSame($on->sent[0]->headers['Digest'], $on->sent[1]->headers['Digest']); + + $order = $result->order(); + self::assertNotNull($order); + self::assertSame(10000, $order->amount); + self::assertSame('255700000001', $order->payerPhone); + self::assertSame(Status::Success, $order->status); + } + + public function testPayoutWithoutPinFailsBeforeAnythingIsSent(): void + { + $config = new Config(Environment::Sandbox, new Credentials('k', 's', 'TILL123')); + $transport = new FakeTransport(); + $client = new Client($config, $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + $this->expectException(ValidationException::class); + try { + $client->vendorBalance(new VendorBalanceRequest('TXN-BAL-0001')); + } finally { + self::assertSame([], $transport->sent); + } + } + + public function testCheckoutUsesTheCheckoutCredentialsWhenConfigured(): void + { + $config = new Config( + Environment::Production, + Fixtures::credentials(), + new Credentials('checkout-key', 'checkout-secret', 'CHECKOUTTILL'), + ); + $transport = (new FakeTransport())->queue(new TransportResponse(200, '{"resultcode":"000","data":[{"payment_status":"PENDING"}]}')); + $client = new Client($config, $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + $client->orderStatus(new OrderStatusRequest('ORD-1001')); + + self::assertSame('SELCOM ' . base64_encode('checkout-key'), $transport->sent[0]->headers['Authorization']); + self::assertStringStartsWith('https://apigw.selcommobile.com/', $transport->sent[0]->url); + } + + public function testTypedAccessors(): void + { + $transport = (new FakeTransport())->queue(new TransportResponse(200, '{"resultcode":"000","data":[{"balance":"1000000"}]}')); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + self::assertSame(1000000, $client->vendorBalance(new VendorBalanceRequest('TXN-BAL-0001'))->balance()); + + $transport = (new FakeTransport())->queue(new TransportResponse(200, '{"resultcode":"000","data":[{"gateway_buyer_uuid":"GBU-1","payment_token":"8","qr":"Q","payment_gateway_url":"aHR0cHM6Ly9jaGVja291dC5leGFtcGxlLmNvbS9wYXkvT1JELTEwMDU="}]}')); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + $order = $client->createOrder(Fixtures::createOrder())->order(); + self::assertNotNull($order); + self::assertSame('https://checkout.example.com/pay/ORD-1005', $order->paymentGatewayUrl); + self::assertSame('aHR0cHM6Ly9jaGVja291dC5leGFtcGxlLmNvbS9wYXkvT1JELTEwMDU=', $order->paymentGatewayUrlRaw); + + // The webhook URL travels as base64 text, and that text is what is signed. + $sentBody = $transport->sent[0]->body; + self::assertIsString($sentBody); + self::assertStringContainsString('"webhook":"' . base64_encode('https://shop.example.com/selcom/webhook/token') . '"', $sentBody); + self::assertStringContainsString('"billing.firstname":"Test"', $sentBody); + self::assertStringNotContainsString('"billing":{', $sentBody); + } +} diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php new file mode 100644 index 0000000..1742955 --- /dev/null +++ b/tests/ConfigTest.php @@ -0,0 +1,129 @@ +expectException(ConfigurationException::class); + $this->expectExceptionMessage('no default'); + Config::fromArray(['api_key' => 'k', 'secret' => 's', 'vendor' => 'TILL123']); + } + + public function testUnknownEnvironmentIsRejected(): void + { + $this->expectException(ConfigurationException::class); + Environment::fromName('staging'); + } + + public function testPresetUrls(): void + { + self::assertSame('https://apigw.selcommobile.com', Environment::Production->baseUrl()); + self::assertSame('https://apigwtest.selcommobile.com', Environment::Sandbox->baseUrl()); + self::assertSame('https://apigwtest.selcommobile.com', Fixtures::config()->baseUrl()); + } + + /** @return iterable}> */ + public static function incomplete(): iterable + { + yield 'no key' => [['environment' => 'sandbox', 'secret' => 's', 'vendor' => 'v']]; + yield 'no secret' => [['environment' => 'sandbox', 'api_key' => 'k', 'vendor' => 'v']]; + yield 'no vendor' => [['environment' => 'sandbox', 'api_key' => 'k', 'secret' => 's']]; + yield 'blank secret' => [['environment' => 'sandbox', 'api_key' => 'k', 'secret' => ' ', 'vendor' => 'v']]; + } + + /** + * @param array $config + */ + #[\PHPUnit\Framework\Attributes\DataProvider('incomplete')] + public function testMissingCredentialsFailAtConstruction(array $config): void + { + $this->expectException(ConfigurationException::class); + Config::fromArray($config); + } + + public function testFromArrayWithEverything(): void + { + $config = Config::fromArray([ + 'environment' => 'production', + 'api_key' => 'k', + 'secret' => 's', + 'vendor' => 'TILL123', + 'pin' => '0000', + 'checkout' => ['api_key' => 'ck', 'secret' => 'cs'], + 'timezone' => 'Africa/Nairobi', + 'max_not_sent_retries' => 2, + 'timeouts' => ['payment_read' => 240, 'query_connect' => 5], + ]); + + self::assertSame(Environment::Production, $config->environment); + self::assertSame('ck', $config->credentialsFor(Operation::CheckoutOrderStatus)->apiKey()); + self::assertSame('TILL123', $config->credentialsFor(Operation::CheckoutOrderStatus)->vendor()); + self::assertSame('k', $config->credentialsFor(Operation::UtilityPaymentQuery)->apiKey()); + self::assertSame(240.0, $config->timeouts->payment->readSeconds); + self::assertSame(15.0, $config->timeouts->payment->connectSeconds); + self::assertSame(5.0, $config->timeouts->query->connectSeconds); + self::assertSame(10.0, $config->timeouts->query->readSeconds); + self::assertSame(2, $config->maxNotSentRetries); + self::assertSame('Africa/Nairobi', $config->timezone->getName()); + } + + public function testDefaultTimeoutsMatchTheSpec(): void + { + $t = Fixtures::config()->timeouts; + self::assertSame([10.0, 10.0], [$t->query->connectSeconds, $t->query->readSeconds]); + self::assertSame([15.0, 180.0], [$t->payment->connectSeconds, $t->payment->readSeconds]); + } + + public function testBaseUrlOverrideIsExplicitAndValidated(): void + { + $custom = Fixtures::config()->withBaseUrl('http://localhost:8080/'); + self::assertSame('http://localhost:8080', $custom->baseUrl()); + self::assertSame('https://apigwtest.selcommobile.com', Fixtures::config()->baseUrl()); + + $this->expectException(ConfigurationException::class); + Fixtures::config()->withBaseUrl('ftp://example.com'); + } + + public function testTooManyRetriesAreRejected(): void + { + $this->expectException(ConfigurationException::class); + new Config(Environment::Sandbox, Fixtures::credentials(), maxNotSentRetries: 6); + } + + public function testSecretsAreMaskedInOutputAndNotSerialisable(): void + { + $config = Fixtures::config(); + $dump = print_r($config, true) . print_r($config->credentials, true); + ob_start(); + var_dump($config); + $dump .= (string) ob_get_clean(); + + foreach (['test-secret-0001', 'test-key-0001', '0000'] as $secret) { + self::assertStringNotContainsString($secret, $dump); + } + self::assertStringContainsString('[REDACTED]', $dump); + + $this->expectException(\LogicException::class); + serialize($config->credentials); + } + + public function testPinIsRequiredOnlyWhenAPayoutAsksForIt(): void + { + $credentials = new Credentials('k', 's', 'v'); + self::assertFalse($credentials->hasPin()); + $this->expectException(\SelcomDevelopers\Selcom\Exception\ValidationException::class); + $credentials->pin(); + } +} diff --git a/tests/InputAndOutputTest.php b/tests/InputAndOutputTest.php new file mode 100644 index 0000000..ad9066d --- /dev/null +++ b/tests/InputAndOutputTest.php @@ -0,0 +1,309 @@ + */ + public static function goodAmounts(): iterable + { + yield 'int' => [8000, 8000]; + yield 'digit string' => ['8000', 8000]; + yield 'integral string' => ['8000.00', 8000]; + yield 'integral float' => [8000.0, 8000]; + yield 'largest' => [9007199254740991, 9007199254740991]; + } + + #[DataProvider('goodAmounts')] + public function testWholeAmountsAreAccepted(mixed $given, int $expected): void + { + $request = new UtilityPaymentRequest('TXN-1', 'LUKU', 'ref', $given); + self::assertSame($expected, $request->amount); + } + + /** @return iterable */ + public static function badAmounts(): iterable + { + yield 'fractional float' => [8000.9]; + yield 'small fraction' => [0.5]; + yield 'fractional string' => ['8000.5']; + yield 'comma string' => ['8,000']; + yield 'exponent string' => ['8e3']; + yield 'text' => ['abc']; + yield 'empty' => ['']; + yield 'negative' => [-1]; + yield 'zero' => [0]; + yield 'bool' => [true]; + yield 'null' => [null]; + yield 'array' => [[8000]]; + yield 'infinite' => [INF]; + yield 'not a number' => [NAN]; + yield 'beyond 2^53-1 int' => [9007199254740992]; + yield 'beyond 2^53-1 float' => [1.0e16]; + yield 'beyond 2^53-1 string' => ['9007199254740992']; + yield 'long string' => ['99999999999999999999']; + } + + #[DataProvider('badAmounts')] + public function testOtherAmountsAreRefusedNeverTruncated(mixed $given): void + { + foreach ([ + static fn () => new UtilityPaymentRequest('TXN-1', 'LUKU', 'ref', $given), + static fn () => new WalletCashinRequest('TXN-1', 'CASHIN', '255700000002', $given), + static fn () => new CreateOrderMinimalRequest('O', 'e@example.com', 'n', '255700000001', $given, Currency::TZS, 1), + ] as $build) { + try { + $build(); + self::fail('the amount must be refused'); + } catch (ValidationException) { + self::addToAssertionCount(1); + } + } + } + + // ---- masked output ------------------------------------------------------------------- + + public function testObjectsShowNoSecretsInAnyPrintedForm(): void + { + $secrets = ['test-secret-0001', 'test-key-0001', '0000']; + $objects = [ + Fixtures::credentials(), + Fixtures::config(), + new Hs256DigestSigner('test-secret-0001'), + new WebhookVerifier('test-secret-0001'), + new Client(Fixtures::config(), new FakeTransport()), + ]; + foreach ($objects as $object) { + ob_start(); + var_dump($object); + $out = (string) ob_get_clean(); + $out .= print_r($object, true) . var_export($object, true) . print_r((array) $object, true); + foreach ($secrets as $secret) { + self::assertStringNotContainsString($secret, $out, $object::class); + } + } + self::assertSame('****0001', Fixtures::credentials()->maskedApiKey()); + } + + public function testExceptionsAndSignedRequestsShowNoSecrets(): void + { + $transport = (new FakeTransport())->queue(new TransportResponse(502, '255700000001 test-key-0001')); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + try { + $client->vendorBalance(new \SelcomDevelopers\Selcom\Request\VendorBalanceRequest('TXN-BAL-0001')); + self::fail('expected InvalidResponseException'); + } catch (InvalidResponseException $e) { + $text = print_r($e, true) . $e->getMessage(); + self::assertStringNotContainsString('255700000001', $text); + self::assertStringContainsString('255700000001', $e->rawBody()); + } + } + + public function testTransportRequestAndResultPrintMaskedData(): void + { + $request = new TransportRequest( + 'POST', + 'https://apigwtest.selcommobile.com/v1/walletcashin/process', + ['Authorization' => 'SELCOM abc', 'Digest' => 'xyz=', 'Accept' => 'application/json'], + '{"transid":"TXN-1","utilitycode":"CASHIN","utilityref":"255700000002","pin":"0000","msisdn":"255700000001"}', + new TimeoutProfile(15.0, 180.0, true), + ); + $out = print_r($request, true); + foreach (['SELCOM abc', 'xyz=', '"0000"', '255700000002', '255700000001'] as $value) { + self::assertStringNotContainsString($value, $out); + } + self::assertStringContainsString('********0002', (string) $request->redactedBody()); + self::assertStringContainsString('"pin":"[REDACTED]"', (string) $request->redactedBody()); + + $lookup = new TransportRequest( + 'GET', + 'https://apigwtest.selcommobile.com/v1/walletcashin/namelookup?utilitycode=VMCASHIN&utilityref=255700000002&transid=TXN-1', + [], + null, + new TimeoutProfile(10.0, 10.0), + ); + self::assertStringNotContainsString('255700000002', $lookup->redactedUrl()); + + $transport = (new FakeTransport())->queue(new TransportResponse(200, '{"resultcode":"000","data":[{"name":"Test Buyer","phone":"255700000001","card_token":"CARDTOKEN-TEST-0001"}]}')); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + $result = $client->execute(new \SelcomDevelopers\Selcom\Request\UtilityLookupRequest('LUKU', '01234567891', 'TXN-1')); + $printed = print_r($result, true); + foreach (['Test Buyer', '255700000001', 'CARDTOKEN-TEST-0001'] as $value) { + self::assertStringNotContainsString($value, $printed); + } + } + + public function testRedactorMasksUtilityRefOnAnyWalletCashinPath(): void + { + $r = new Redactor(); + self::assertSame('********0002', $r->redactParams(['utilityref' => '255700000002'], '/v1/walletcashin/query')['utilityref']); + self::assertSame('01234567891', $r->redactParams(['utilityref' => '01234567891'], '/v1/utilitypayment/lookup')['utilityref']); + self::assertStringContainsString('%2A%2A%2A%2A%2A%2A%2A%2A0002', $r->redactQuery('utilityref=255700000002', '/v1/walletcashin/namelookup')); + } + + public function testWebhookPayloadPrintsMaskedData(): void + { + $payload = WebhookPayload::fromRawBody('{"order_id":"ORD-1","transid":"TXN-1","amount":"10,000","phone":"255700000001"}'); + self::assertStringNotContainsString('255700000001', print_r($payload, true)); + self::assertSame(10000, $payload->amountTzs); + } + + public function testWebhookPayloadDoesNotThrowOnAnUnusableAmount(): void + { + foreach (['"amount":"ten"', '"amount":1e999', '"amount":[1]', '"amount":{"a":1}', '"amount":-5', '"amount":true'] as $field) { + $payload = WebhookPayload::fromRawBody('{"order_id":"ORD-1",' . $field . '}'); + self::assertNull($payload->amountTzs, $field); + } + } + + // ---- order status shape ---------------------------------------------------------------- + + public function testOrderStatusDataShape(): void + { + $kind = OperationKind::OrderStatus; + self::assertSame(Status::NotFound, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":[]}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":{}}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":null}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":"x"}')[0]); + self::assertSame(Status::Success, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":[{"payment_status":"COMPLETED"}]}')[0]); + } + + // ---- webhook robustness ---------------------------------------------------------------- + + /** + * @param array $fields + * @return array{array, string} + */ + private static function signedDelivery(array $fields, string $names = 'transid,order_id,reference', string $at = '2026-11-21T10:30:46+03:00'): array + { + $body = json_encode($fields, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION); + $flat = []; + foreach (explode(',', $names) as $name) { + $value = $fields[$name]; + $flat[] = [$name, is_float($value) ? (int) $value : $value]; + } + $digest = (new Hs256DigestSigner('test-secret-0001'))->sign(\SelcomDevelopers\Selcom\Signing\RequestSigner::signingString($at, $flat)); + + return [ + ['Digest' => $digest, 'Digest-Method' => 'HS256', 'Timestamp' => $at, 'Signed-Fields' => $names], + $body, + ]; + } + + public function testWebhookWithUnusableNumbersIsInvalidAndNeverThrows(): void + { + $verifier = new WebhookVerifier('test-secret-0001', FixedClock::at('2026-11-21T10:31:00+03:00')); + $headers = [ + 'Digest' => 'abc=', + 'Digest-Method' => 'HS256', + 'Timestamp' => '2026-11-21T10:30:46+03:00', + 'Signed-Fields' => 'transid,order_id,reference', + ]; + foreach (['1e100000000', '1e-999999999', '-1e100000000', '12345678901234567890123', '1.5', '0.0', '1e400'] as $number) { + $body = '{"transid":"T","order_id":"O","reference":' . $number . '}'; + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, $body), $number); + } + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, '{"transid":"T","order_id":"O","reference":' . str_repeat('9', 200000) . '}')); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, str_repeat('[', 100000))); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify(['Digest' => 'a', 'Digest-Method' => 'HS256', 'Timestamp' => '2026-11-21T10:30:46+03:00', 'Signed-Fields' => str_repeat('a,', 100000)], '{}')); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, str_repeat(' ', 2000000) . '{}')); + } + + public function testWebhookSignedFieldRules(): void + { + $clock = FixedClock::at('2026-11-21T10:31:00+03:00'); + $verifier = new WebhookVerifier('test-secret-0001', $clock); + + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-1', 'order_id' => 'ORD-1', 'reference' => 'REF-1']); + self::assertSame(WebhookVerdict::Valid, $verifier->verify($headers, $body)); + + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-2', 'order_id' => 'ORD-1', 'reference' => 'REF&1']); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, $body)); + + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-3', 'order_id' => 'ORD-1', 'reference' => 'REF-1'], 'transid,reference'); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, $body)); + + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-4', 'order_id' => 'ORD-1', 'reference' => 8000.0]); + self::assertSame(WebhookVerdict::Valid, $verifier->verify($headers, $body)); + } + + public function testReplayEntriesAreKeptUntilTheSignedTimePlusTheWindow(): void + { + // A delivery dated 200 s ahead of this server's clock: kept until its time + 300 s. + $clock = FixedClock::at('2026-11-21T10:31:00+03:00'); + $verifier = new WebhookVerifier('test-secret-0001', $clock, windowSeconds: 300); + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-1', 'order_id' => 'ORD-1'], 'transid,order_id', '2026-11-21T10:34:20+03:00'); + + $first = $verifier->verify($headers, $body); + $clock->advance(299); // 10:35:59, still inside the window of the signed time + $second = $verifier->verify($headers, $body); + $clock->advance(120); // 10:37:59: 10:34:20 + 300 s = 10:39:20 is not yet reached + $third = $verifier->verify($headers, $body); + $clock->advance(100); // 10:39:39: past the window, now stale + $fourth = $verifier->verify($headers, $body); + self::assertSame( + ['VALID', 'REPLAY', 'REPLAY', 'STALE'], + [$first->value, $second->value, $third->value, $fourth->value], + ); + } + + public function testReplayStoreFailureIsATypedErrorNotAVerdict(): void + { + $clock = FixedClock::at('2026-11-21T10:31:00+03:00'); + $broken = new class implements ReplayStore { + public function seen(string $digest, int $keepUntil): bool + { + throw new \RuntimeException('cache is down'); + } + }; + $verifier = new WebhookVerifier('test-secret-0001', $clock, $broken); + [$headers, $body] = self::signedDelivery(['transid' => 'TXN-1', 'order_id' => 'ORD-1'], 'transid,order_id'); + + $this->expectException(ReplayStoreException::class); + $verifier->verify($headers, $body); + } + + public function testReplayStoreBoundary(): void + { + $clock = FixedClock::at('2026-11-21T10:30:00+03:00'); + $store = new InMemoryReplayStore($clock); + $keepUntil = $clock->now()->getTimestamp() + 300; + + self::assertFalse($store->seen('d', $keepUntil)); + $clock->advance(300); // exactly at the keep-until time: still live + self::assertTrue($store->seen('d', $keepUntil)); + $clock->advance(1); // one second later: gone + self::assertFalse($store->seen('d', $keepUntil + 1)); + } +} diff --git a/tests/RedactorTest.php b/tests/RedactorTest.php new file mode 100644 index 0000000..27501cc --- /dev/null +++ b/tests/RedactorTest.php @@ -0,0 +1,85 @@ + '[REDACTED]', 'Digest' => '[REDACTED]', 'Timestamp' => 't', 'Digest-Method' => 'HS256'], + $r->redactHeaders(['Authorization' => 'SELCOM abc', 'Digest' => 'xyz', 'Timestamp' => 't', 'Digest-Method' => 'HS256']), + ); + + $out = $r->redactParams([ + 'vendor' => 'TILL123', + 'pin' => '0000', + 'card_token' => 'CARDTOKEN-TEST-0001', + 'msisdn' => '255700000001', + 'buyer_email' => 'test.buyer@example.com', + 'buyer_name' => 'Test Buyer', + 'amount' => 8000, + 'billing' => ['firstname' => 'Test', 'lastname' => 'Buyer', 'phone' => '255700000001', 'city' => 'Dar es Salaam'], + 'shipping.phone' => '255700000002', + ]); + self::assertSame('TILL123', $out['vendor']); + self::assertSame('[REDACTED]', $out['pin']); + self::assertSame('[REDACTED]', $out['card_token']); + self::assertSame('********0001', $out['msisdn']); + self::assertSame('t***@example.com', $out['buyer_email']); + self::assertSame('T***', $out['buyer_name']); + self::assertSame(8000, $out['amount']); + self::assertSame( + ['firstname' => 'T***', 'lastname' => 'B***', 'phone' => '********0001', 'city' => 'Dar es Salaam'], + $out['billing'], + ); + self::assertSame('********0002', $out['shipping.phone']); + } + + public function testUtilityRefIsAPhoneOnlyForWalletCashin(): void + { + $r = new Redactor(); + self::assertSame( + '********0002', + $r->redactParams(['utilitycode' => 'VMCASHIN', 'utilityref' => '255700000002'])['utilityref'], + ); + self::assertSame( + '01234567891', + $r->redactParams(['utilitycode' => 'LUKU', 'utilityref' => '01234567891'])['utilityref'], + ); + } + + public function testQueryStringAndJson(): void + { + $r = new Redactor(); + self::assertSame( + 'utilitycode=CASHIN&utilityref=%2A%2A%2A%2A%2A%2A%2A%2A0002&transid=TXN-1', + $r->redactQuery('utilitycode=CASHIN&utilityref=255700000002&transid=TXN-1'), + ); + self::assertSame( + 'gateway_buyer_uuid=GBU&buyer_userid=U1&pin=%5BREDACTED%5D', + $r->redactQuery('gateway_buyer_uuid=GBU&buyer_userid=U1&pin=1234'), + ); + self::assertSame( + '{"phone":"********0001","data":[{"card_token":"[REDACTED]"}]}', + $r->redactJson('{"phone":"255700000001","data":[{"card_token":"CARDTOKEN-TEST-0001"}]}'), + ); + self::assertSame('[UNPARSEABLE BODY OMITTED]', $r->redactJson('pin=1234')); + } + + public function testShortAndOddValues(): void + { + $r = new Redactor(); + self::assertSame('***', $r->redactParams(['phone' => '123'])['phone']); + self::assertSame('[REDACTED]', $r->redactParams(['email' => 'no-at-sign'])['email']); + self::assertSame('', $r->redactParams(['name' => ''])['name']); + self::assertSame('Ä***', $r->redactParams(['name' => 'Ärnold'])['name']); + } +} diff --git a/tests/ResponseVectorsTest.php b/tests/ResponseVectorsTest.php new file mode 100644 index 0000000..9432dcd --- /dev/null +++ b/tests/ResponseVectorsTest.php @@ -0,0 +1,113 @@ +}> */ + public static function scenarios(): iterable + { + foreach (Vectors::responseFiles() as $file) { + $fixture = Vectors::load($file); + if (!isset($fixture['scenarios']) || !is_array($fixture['scenarios'])) { + continue; // checkout.webhook.json holds deliveries: see WebhookVectorsTest + } + $operation = $fixture['operation']; + self::assertIsString($operation); + foreach ($fixture['scenarios'] as $scenario) { + self::assertIsArray($scenario); + $name = $scenario['name'] ?? null; + self::assertIsString($name); + /** @var array $scenario */ + yield $operation . ' / ' . $name => [$operation, $scenario]; + } + } + } + + public function testScenarioCount(): void + { + self::assertCount(120, iterator_to_array(self::scenarios())); + } + + /** + * @param array $scenario + */ + #[DataProvider('scenarios')] + public function testClassifier(string $operationName, array $scenario): void + { + $operation = Operation::from($operationName); + [$status, $body] = self::input($scenario); + self::assertIsInt($scenario['http_status']); + + if (isset($scenario['expected_error'])) { + self::assertSame('INVALID_RESPONSE', $scenario['expected_error']); + $this->expectException(InvalidResponseException::class); + ResponseClassifier::classify($operation->kind(), $scenario['http_status'], $body); + + return; + } + [$typed] = ResponseClassifier::classify($operation->kind(), $scenario['http_status'], $body); + self::assertSame($scenario['expected_status'], $typed->value); + self::assertSame($status, $scenario['http_status']); + } + + /** + * @param array $scenario + */ + #[DataProvider('scenarios')] + public function testThroughTheClient(string $operationName, array $scenario): void + { + $operation = Operation::from($operationName); + [, $body] = self::input($scenario); + self::assertIsInt($scenario['http_status']); + $transport = (new FakeTransport())->queue(new TransportResponse($scenario['http_status'], $body)); + $client = new Client(Fixtures::config(), $transport, FixedClock::at('2026-11-21T10:30:46+03:00')); + + if (isset($scenario['expected_error'])) { + $this->expectException(InvalidResponseException::class); + $client->execute(Fixtures::request($operation)); + + return; + } + + $result = $client->execute(Fixtures::request($operation)); + self::assertSame($scenario['expected_status'], $result->status->value); + self::assertSame($scenario['http_status'], $result->httpStatus); + self::assertSame($body, $result->raw); + self::assertSame($result->status->value !== 'PENDING' && $result->status->value !== 'AMBIGUOUS', $result->isFinal()); + } + + /** + * @param array $scenario + * @return array{int, string} + */ + private static function input(array $scenario): array + { + self::assertIsInt($scenario['http_status']); + if (isset($scenario['raw_body'])) { + self::assertIsString($scenario['raw_body']); + + return [$scenario['http_status'], $scenario['raw_body']]; + } + + return [$scenario['http_status'], json_encode($scenario['body'], JSON_THROW_ON_ERROR)]; + } +} diff --git a/tests/ResultAndRequestTest.php b/tests/ResultAndRequestTest.php new file mode 100644 index 0000000..f79c2da --- /dev/null +++ b/tests/ResultAndRequestTest.php @@ -0,0 +1,178 @@ +path()); + self::assertContains($op->method(), ['GET', 'POST', 'DELETE']); + // Every operation builds a request that signs cleanly. + $params = Fixtures::request($op)->params(Fixtures::credentials()); + RequestSigner::sign($op->method(), $params, '2026-11-21T10:30:46+03:00', 'k', new Hs256DigestSigner('s')); + } + self::assertSame('/v1/checkout/create-order-minimal', Operation::CheckoutCreateOrderMinimal->path()); + self::assertSame('/v1/walletcashin/namelookup', Operation::WalletCashinNameLookup->path()); + self::assertSame('/v1/vendor/balance', Operation::VendorBalance->path()); + self::assertSame('DELETE', Operation::CheckoutDeleteCard->method()); + } + + public function testKindsAndRetryRules(): void + { + self::assertSame(OperationKind::Payment, Operation::CheckoutWalletPayment->kind()); + self::assertSame(OperationKind::Payment, Operation::WalletCashinProcess->kind()); + self::assertSame(OperationKind::StatusQuery, Operation::UtilityPaymentQuery->kind()); + self::assertSame(OperationKind::OrderStatus, Operation::CheckoutOrderStatus->kind()); + self::assertSame(OperationKind::Other, Operation::VendorBalance->kind()); + + $retryable = array_filter(Operation::cases(), static fn (Operation $o): bool => $o->isRetryableWhenNotSent()); + self::assertEqualsCanonicalizing( + [ + 'checkout.order-status', 'checkout.list-orders', 'checkout.stored-cards', + 'utilitypayment.lookup', 'utilitypayment.query', 'walletcashin.namelookup', + 'walletcashin.query', 'vendor.balance', + ], + array_map(static fn (Operation $o): string => $o->value, array_values($retryable)), + ); + } + + public function testResultCodeNormalisationAndOrderStatusMapping(): void + { + self::assertSame('000', ResponseClassifier::normaliseResultCode(0)); + self::assertSame('111', ResponseClassifier::normaliseResultCode(' 111 ')); + self::assertNull(ResponseClassifier::normaliseResultCode(true)); + self::assertNull(ResponseClassifier::normaliseResultCode('')); + self::assertNull(ResponseClassifier::normaliseResultCode(-1)); + self::assertNull(ResponseClassifier::normaliseResultCode(0.0)); + + foreach (['COMPLETED', 'complete', ' Completed '] as $s) { + self::assertSame(Status::Success, ResponseClassifier::paymentStatus($s)); + } + foreach (['PENDING', 'inprogress'] as $s) { + self::assertSame(Status::Pending, ResponseClassifier::paymentStatus($s)); + } + foreach (['CANCELLED', 'CANCELED', 'CANCEL', 'USERCANCELLED', 'USERCANCELED', 'REJECTED', 'FAILED'] as $s) { + self::assertSame(Status::Failed, ResponseClassifier::paymentStatus($s)); + } + self::assertSame(Status::Ambiguous, ResponseClassifier::paymentStatus('WEIRD')); + self::assertSame(Status::Ambiguous, ResponseClassifier::paymentStatus(null)); + } + + public function testOrderStatusEdgeCases(): void + { + $kind = OperationKind::OrderStatus; + self::assertSame(Status::NotFound, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":[]}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 200, '{"resultcode":"000"}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 200, '{"resultcode":"000","data":{"payment_status":"COMPLETED"}}')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify($kind, 500, '{"resultcode":"400"}')[0]); + self::assertSame(Status::NotFound, ResponseClassifier::classify($kind, 404, '{"resultcode":"404"}')[0]); + // A 111 whose text says SUCCESS is still in progress; a 000 with an empty result is a success. + self::assertSame(Status::Pending, ResponseClassifier::classify(OperationKind::Payment, 200, '{"resultcode":"111","result":"SUCCESS"}')[0]); + self::assertSame(Status::Success, ResponseClassifier::classify(OperationKind::Payment, 200, '{"resultcode":"000","result":""}')[0]); + // No verdict on a payment is AMBIGUOUS, never FAILED. + self::assertSame(Status::Ambiguous, ResponseClassifier::classify(OperationKind::Payment, 200, '')[0]); + self::assertSame(Status::Ambiguous, ResponseClassifier::classify(OperationKind::StatusQuery, 200, '[]')[0]); + } + + public function testStatusFinality(): void + { + self::assertTrue(Status::Success->isFinal()); + self::assertTrue(Status::Failed->isFinal()); + self::assertTrue(Status::NotFound->isFinal()); + self::assertFalse(Status::Pending->isFinal()); + self::assertFalse(Status::Ambiguous->isFinal()); + } + + public function testAmountsAreParsedStrictly(): void + { + self::assertSame(10000, Amounts::parse('10,000')); + self::assertSame(10000, Amounts::parse('10000')); + self::assertSame(10000, Amounts::parse('10000.00')); + self::assertSame(0, Amounts::parse('0')); + self::assertSame(5, Amounts::parse(5)); + foreach (['10,00', '1,0000', '10.5', '-5', '1e3', ' ', '', 'abc', '10 000', '99999999999999999999'] as $bad) { + self::assertNull(Amounts::tryParse($bad), $bad); + } + self::assertNull(Amounts::tryParse(10.5)); + self::assertNull(Amounts::tryParse(null)); + $this->expectException(\InvalidArgumentException::class); + Amounts::parse('10.5'); + } + + public function testCreateOrderBuildsDottedBillingInOrderAndEncodesUrls(): void + { + $address = new Address('Test', 'Buyer', '1 Test Street', 'Dar es Salaam', 'Dar es Salaam', '11101', 'TZ', '255700000001', address2: 'Flat 2'); + $request = new CreateOrderRequest( + 'ORD-1001', + 'test.buyer@example.com', + 'Test Buyer', + '255700000001', + 8000, + Currency::TZS, + [PaymentMethod::Card, PaymentMethod::MobileMoneyPull], + $address, + 2, + redirectUrl: 'https://shop.example.com/done', + expiryMinutes: 30, + ); + $params = $request->params(Fixtures::credentials()); + $signed = RequestSigner::sign('POST', $params, '2026-11-21T10:30:46+03:00', 'k', new Hs256DigestSigner('s')); + + self::assertSame( + 'vendor,order_id,buyer_email,buyer_name,buyer_phone,amount,currency,payment_methods,redirect_url,' + . 'billing.firstname,billing.lastname,billing.address_1,billing.address_2,billing.city,' + . 'billing.state_or_region,billing.postcode_or_pobox,billing.country,billing.phone,no_of_items,expiry', + $signed->signedFields, + ); + self::assertStringContainsString('payment_methods=CARD,MOBILEMONEYPULL&', $signed->signingString); + self::assertStringContainsString('redirect_url=' . base64_encode('https://shop.example.com/done') . '&', $signed->signingString); + } + + /** @return iterable */ + public static function invalidRequests(): iterable + { + $address = static fn (): Address => new Address('T', 'B', 'a', 'c', 's', 'p', 'TZ', '255700000001'); + yield 'zero amount' => [static fn () => new UtilityPaymentRequest('TXN-1', 'LUKU', 'ref', 0)]; + yield 'negative amount' => [static fn () => new UtilityPaymentRequest('TXN-1', 'LUKU', 'ref', -5)]; + yield 'empty transid' => [static fn () => new UtilityPaymentRequest(' ', 'LUKU', 'ref', 100)]; + yield 'blank msisdn' => [static fn () => new UtilityPaymentRequest('TXN-1', 'LUKU', 'ref', 100, ' ')]; + yield 'no payment methods' => [static fn () => new CreateOrderRequest('O', 'e', 'n', 'p', 1, Currency::TZS, [], $address(), 1)]; + yield 'blank billing city' => [static fn () => new Address('T', 'B', 'a', '', 's', 'p', 'TZ', '1')]; + yield 'bad webhook url' => [static fn () => new CreateOrderMinimalRequest('O', 'e', 'n', 'p', 1, Currency::TZS, 1, webhookUrl: 'javascript:alert(1)')]; + yield 'bad date' => [static fn () => new ListOrdersRequest('2026-13-01', '2026-11-21')]; + yield 'date format' => [static fn () => new ListOrdersRequest('21/11/2026', '2026-11-21')]; + } + + /** + * @param \Closure(): object $build + */ + #[\PHPUnit\Framework\Attributes\DataProvider('invalidRequests')] + public function testInvalidRequestsAreRefusedBeforeAnythingIsBuilt(\Closure $build): void + { + $this->expectException(ValidationException::class); + $build(); + } +} diff --git a/tests/Sandbox/SandboxTest.php b/tests/Sandbox/SandboxTest.php new file mode 100644 index 0000000..6782f00 --- /dev/null +++ b/tests/Sandbox/SandboxTest.php @@ -0,0 +1,39 @@ +orderStatus(new OrderStatusRequest('ORD-DOES-NOT-EXIST-' . bin2hex(random_bytes(4)))); + + self::assertNotSame('', $result->raw); + self::assertGreaterThan(0, $result->httpStatus); + } +} diff --git a/tests/SigningVectorsTest.php b/tests/SigningVectorsTest.php new file mode 100644 index 0000000..5e50899 --- /dev/null +++ b/tests/SigningVectorsTest.php @@ -0,0 +1,155 @@ +}> */ + public static function cases(): iterable + { + $vectors = Vectors::load('signing.json'); + $cases = $vectors['cases']; + self::assertIsArray($cases); + foreach ($cases as $case) { + self::assertIsArray($case); + $id = $case['id'] ?? null; + self::assertIsString($id); + /** @var array $case */ + yield $id => [$case]; + } + } + + /** @return iterable}> */ + public static function rejects(): iterable + { + $vectors = Vectors::load('signing.json'); + $rejects = $vectors['rejects']; + self::assertIsArray($rejects); + foreach ($rejects as $reject) { + self::assertIsArray($reject); + $id = $reject['id'] ?? null; + self::assertIsString($id); + /** @var array $reject */ + yield $id => [$reject]; + } + } + + public function testVectorCounts(): void + { + self::assertCount(20, iterator_to_array(self::cases())); + self::assertCount(11, iterator_to_array(self::rejects())); + } + + /** + * @param array $case + */ + #[DataProvider('cases')] + public function testCase(array $case): void + { + $expected = $case['expected']; + self::assertIsArray($expected); + self::assertIsString($case['method']); + self::assertIsArray($case['params']); + self::assertIsString($case['timestamp']); + self::assertIsString($case['api_key']); + self::assertIsString($case['secret']); + + $signed = RequestSigner::sign( + $case['method'], + $case['params'], + $case['timestamp'], + $case['api_key'], + new Hs256DigestSigner($case['secret']), + ); + + self::assertSame($expected['flattened'], array_map(static fn (array $p): array => [$p[0], $p[1]], $signed->flattened)); + self::assertSame($expected['signed_fields'], $signed->signedFields); + self::assertSame($expected['signing_string'], $signed->signingString); + self::assertSame($expected['digest'], $signed->digest); + self::assertSame($expected['authorization'], $signed->authorization); + self::assertSame($expected['digest_method'], $signed->digestMethod); + self::assertSame($case['timestamp'], $signed->headers()['Timestamp']); + self::assertSame($expected['signed_fields'], $signed->headers()['Signed-Fields']); + + if (isset($expected['query'])) { + self::assertSame($expected['query'], $signed->query); + } + if (isset($expected['body'])) { + self::assertIsString($expected['body']); + self::assertNotNull($signed->body); + // Same keys in the same order with the same values and JSON types; bytes may differ. + $want = json_decode($expected['body'], true, 512, JSON_THROW_ON_ERROR); + $got = json_decode($signed->body, true, 512, JSON_THROW_ON_ERROR); + self::assertIsArray($want); + self::assertIsArray($got); + self::assertSame(array_keys($want), array_keys($got)); + self::assertSame($want, $got); + } + if ($case['method'] === 'POST') { + self::assertNull($signed->query); + } else { + self::assertNull($signed->body); + } + } + + /** + * @param array $reject + */ + #[DataProvider('rejects')] + public function testReject(array $reject): void + { + self::assertIsString($reject['method']); + self::assertIsArray($reject['params']); + self::assertIsString($reject['timestamp']); + self::assertIsString($reject['api_key']); + self::assertIsString($reject['secret']); + self::assertIsString($reject['error']); + + try { + RequestSigner::sign( + $reject['method'], + $reject['params'], + $reject['timestamp'], + $reject['api_key'], + new Hs256DigestSigner($reject['secret']), + ); + self::fail('The signer must refuse ' . get_debug_type($reject['id'])); + } catch (SigningException $e) { + self::assertSame($reject['error'], $e->errorCode); + } + } + + public function testBothOffsetFormsAreAcceptedAndColonFormIsGenerated(): void + { + $signer = new Hs256DigestSigner('s'); + $colon = RequestSigner::sign('GET', ['a' => '1'], '2026-11-21T10:30:46+03:00', 'k', $signer); + $basic = RequestSigner::sign('GET', ['a' => '1'], '2026-11-21T10:30:46+0300', 'k', $signer); + self::assertSame('timestamp=2026-11-21T10:30:46+03:00&a=1', $colon->signingString); + self::assertSame('timestamp=2026-11-21T10:30:46+0300&a=1', $basic->signingString); + } + + public function testImpossibleDateIsRejected(): void + { + $this->expectException(SigningException::class); + RequestSigner::sign('GET', ['a' => '1'], '2026-13-45T10:30:46+03:00', 'k', new Hs256DigestSigner('s')); + } + + public function testNumericLookingKeyKeepsItsPlaceInTheBody(): void + { + $signed = RequestSigner::sign('POST', ['23' => 'x', 'b' => 'y'], '2026-11-21T10:30:46+03:00', 'k', new Hs256DigestSigner('s')); + self::assertSame('{"23":"x","b":"y"}', $signed->body); + self::assertSame('23,b', $signed->signedFields); + } +} diff --git a/tests/Support/FakeTransport.php b/tests/Support/FakeTransport.php new file mode 100644 index 0000000..b878741 --- /dev/null +++ b/tests/Support/FakeTransport.php @@ -0,0 +1,49 @@ + */ + public array $sent = []; + + /** @var \Closure(): void|null Called after every send, for example to advance a fixed clock */ + public ?\Closure $afterSend = null; + + /** @var list */ + private array $queue = []; + + public function queue(TransportResponse|TransportException $next): self + { + $this->queue[] = $next; + + return $this; + } + + public function send(TransportRequest $request): TransportResponse + { + $this->sent[] = $request; + if ($this->afterSend !== null) { + ($this->afterSend)(); + } + $next = array_shift($this->queue); + if ($next === null) { + throw new \LogicException('FakeTransport has nothing queued.'); + } + if ($next instanceof TransportException) { + throw $next; + } + + return $next; + } +} diff --git a/tests/Support/FixedClock.php b/tests/Support/FixedClock.php new file mode 100644 index 0000000..0598ef9 --- /dev/null +++ b/tests/Support/FixedClock.php @@ -0,0 +1,29 @@ +now; + } + + public function advance(int $seconds): void + { + $this->now = $this->now->modify('+' . $seconds . ' seconds'); + } +} diff --git a/tests/Support/Fixtures.php b/tests/Support/Fixtures.php new file mode 100644 index 0000000..8c2624a --- /dev/null +++ b/tests/Support/Fixtures.php @@ -0,0 +1,92 @@ + self::createOrder(), + Operation::CheckoutCreateOrderMinimal => new CreateOrderMinimalRequest( + 'ORD-1002', + 'test.buyer@example.com', + 'Test Buyer', + '255700000001', + 8000, + Currency::TZS, + 1, + ), + Operation::CheckoutWalletPayment => new WalletPaymentRequest('TXN-WLT-0001', 'ORD-1002', '255700000001'), + Operation::CheckoutCardPayment => new CardPaymentRequest('TXN-CRD-0001', 'ORD-1001', 'CARDTOKEN-TEST-0001', 'USER-1', 'GBU-TEST-0001'), + Operation::CheckoutOrderStatus => new OrderStatusRequest('ORD-1001'), + Operation::CheckoutCancelOrder => new CancelOrderRequest('ORD-1001'), + Operation::CheckoutListOrders => new ListOrdersRequest('2026-11-01', '2026-11-21'), + Operation::CheckoutStoredCards => new StoredCardsRequest('GBU-TEST-0001', 'USER-1'), + Operation::CheckoutDeleteCard => new DeleteCardRequest(23, 'GBU-TEST-0001'), + Operation::UtilityPaymentProcess => new UtilityPaymentRequest('TXN-UTL-0001', 'LUKU', '01234567891', 8000), + Operation::UtilityPaymentLookup => new UtilityLookupRequest('LUKU', '01234567891', 'TXN-LKP-0001'), + Operation::UtilityPaymentQuery => new UtilityQueryRequest('TXN-UTL-0001'), + Operation::WalletCashinProcess => new WalletCashinRequest('TXN-CSH-0001', 'CASHIN', '255700000002', 2500), + Operation::WalletCashinNameLookup => new WalletNameLookupRequest('CASHIN', '255700000002', 'TXN-CSH-0002'), + Operation::WalletCashinQuery => new WalletCashinQueryRequest('TXN-CSH-0001'), + Operation::VendorBalance => new VendorBalanceRequest('TXN-BAL-0001'), + }; + } +} diff --git a/tests/Support/Vectors.php b/tests/Support/Vectors.php new file mode 100644 index 0000000..b4401a2 --- /dev/null +++ b/tests/Support/Vectors.php @@ -0,0 +1,40 @@ + + */ + public static function load(string $relativePath): array + { + $file = __DIR__ . '/../vectors/' . $relativePath; + $json = file_get_contents($file); + Assert::assertIsString($json, $file); + $decoded = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + Assert::assertIsArray($decoded); + + /** @var array $decoded */ + return $decoded; + } + + /** + * @return list the response fixture files, as paths relative to tests/vectors + */ + public static function responseFiles(): array + { + $files = glob(__DIR__ . '/../vectors/responses/*.json'); + Assert::assertIsArray($files); + sort($files); + + return array_map(static fn (string $f): string => 'responses/' . basename($f), $files); + } +} diff --git a/tests/TransportTest.php b/tests/TransportTest.php new file mode 100644 index 0000000..ca7fc3d --- /dev/null +++ b/tests/TransportTest.php @@ -0,0 +1,270 @@ + 'application/json', 'Content-Type' => 'application/json', 'Digest' => 'x'], + '{"vendor":"TILL123"}', + $profile ?? new TimeoutProfile(10.0, 10.0), + ); + } + + private function guzzle(MockHandler $mock): GuzzleClient + { + return new GuzzleClient(['handler' => HandlerStack::create($mock), 'http_errors' => false]); + } + + public function testAnyHttpStatusIsReturnedNotThrown(): void + { + $mock = new MockHandler([new Response(502, ['X-Test' => 'a'], 'Bad Gateway')]); + $factory = new HttpFactory(); + $transport = new Psr18Transport($this->guzzle($mock), $factory, $factory, clientManagesTimeouts: true); + + $response = $transport->send($this->request()); + + self::assertSame(502, $response->status); + self::assertSame('Bad Gateway', $response->body); + self::assertSame('a', $response->headers['X-Test']); + + $sent = $mock->getLastRequest(); + self::assertNotNull($sent); + self::assertSame('POST', $sent->getMethod()); + self::assertSame('{"vendor":"TILL123"}', (string) $sent->getBody()); + self::assertSame('application/json', $sent->getHeaderLine('Content-Type')); + } + + public function testTheClientIsBuiltPerTimeoutProfile(): void + { + $seen = []; + $factory = new HttpFactory(); + $transport = new Psr18Transport( + function (TimeoutProfile $p) use (&$seen): ClientInterface { + $seen[] = [$p->connectSeconds, $p->readSeconds, $p->freshConnection]; + + return $this->guzzle(new MockHandler([new Response(200, [], '{}'), new Response(200, [], '{}')])); + }, + $factory, + $factory, + ); + + $transport->send($this->request(new TimeoutProfile(15.0, 180.0, true))); + $transport->send($this->request(new TimeoutProfile(15.0, 180.0, true))); + $transport->send($this->request(new TimeoutProfile(10.0, 10.0))); + + self::assertSame([[15.0, 180.0, true], [10.0, 10.0, false]], $seen); + } + + /** @return iterable */ + public static function failures(): iterable + { + $req = new Request('GET', 'https://example.com'); + yield 'curl 6 resolve' => [new ConnectException('x', $req, null, ['errno' => 6]), TransportFailure::NotSent]; + yield 'curl 7 refused' => [new ConnectException('x', $req, null, ['errno' => 7]), TransportFailure::NotSent]; + yield 'curl 35 tls connect' => [new ConnectException('x', $req, null, ['errno' => 35]), TransportFailure::NotSent]; + // libcurl fills the pretransfer and start-transfer times even on failure: they prove nothing. + // Only the request-byte counters say whether any of the request was written. + $times = ['connect_time' => 0.0, 'pretransfer_time' => 0.0004, 'starttransfer_time' => 0.0004]; + yield 'connect timeout' => [new ConnectException('x', $req, null, ['errno' => 28, 'request_size' => 0, 'size_upload' => 0.0] + $times), TransportFailure::NotSent]; + yield 'refused with timings' => [new ConnectException('x', $req, null, ['errno' => 7, 'request_size' => 0, 'size_upload' => 0.0] + $times), TransportFailure::NotSent]; + yield 'dns with timings' => [new ConnectException('x', $req, null, ['errno' => 6, 'request_size' => 0, 'size_upload' => 0.0] + $times), TransportFailure::NotSent]; + yield 'read timeout on reused connection' => [new ConnectException('x', $req, null, ['errno' => 28, 'request_size' => 98, 'size_upload' => 20.0] + $times), TransportFailure::UnknownOutcome]; + yield 'timeout, request size only' => [new ConnectException('x', $req, null, ['errno' => 28, 'request_size' => 71, 'size_upload' => 0.0]), TransportFailure::UnknownOutcome]; + yield 'timeout, counters missing' => [new ConnectException('x', $req, null, ['errno' => 28, 'connect_time' => 0.0]), TransportFailure::UnknownOutcome]; + yield 'handshake error after bytes' => [new ConnectException('x', $req, null, ['errno' => 35, 'request_size' => 10]), TransportFailure::UnknownOutcome]; + yield 'record-level tls error' => [new \RuntimeException('cURL error 56: OpenSSL SSL_read: bad record mac'), TransportFailure::UnknownOutcome]; + yield 'unreachable' => [new \RuntimeException('Network is unreachable'), TransportFailure::UnknownOutcome]; + yield 'timeout without timings' => [new ConnectException('x', $req, null, ['errno' => 28]), TransportFailure::UnknownOutcome]; + yield 'curl 56 recv failure' => [new ConnectException('x', $req, null, ['errno' => 56]), TransportFailure::UnknownOutcome]; + yield 'curl 52 empty reply' => [new ConnectException('x', $req, null, ['errno' => 52]), TransportFailure::UnknownOutcome]; + yield 'message: cURL error 6' => [new \RuntimeException('cURL error 6: Could not resolve host: apigw.example'), TransportFailure::NotSent]; + yield 'message: refused' => [new \RuntimeException('Failed to connect: Connection refused'), TransportFailure::NotSent]; + yield 'message: reset' => [new \RuntimeException('Connection reset by peer'), TransportFailure::UnknownOutcome]; + yield 'message: read timeout' => [new \RuntimeException('Operation timed out after 180000 ms'), TransportFailure::UnknownOutcome]; + yield 'nothing known' => [new \RuntimeException('boom'), TransportFailure::UnknownOutcome]; + yield 'wrapped cause' => [new \RuntimeException('outer', 0, new ConnectException('x', $req, null, ['errno' => 7])), TransportFailure::NotSent]; + } + + #[DataProvider('failures')] + public function testFailureClassification(\Throwable $error, TransportFailure $expected): void + { + self::assertSame($expected, FailureClassifier::classify($error)); + } + + public function testNetworkFailuresBecomeTransportExceptionsWithTheCauseAttached(): void + { + $mock = new MockHandler([new ConnectException('cURL error 7: refused', new Request('POST', 'https://x'), null, ['errno' => 7])]); + $factory = new HttpFactory(); + $transport = new Psr18Transport($this->guzzle($mock), $factory, $factory, clientManagesTimeouts: true); + + try { + $transport->send($this->request()); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + self::assertSame(TransportFailure::NotSent, $e->failure); + self::assertTrue($e->isNotSent()); + self::assertNotInstanceOf(ConnectException::class, $e->getPrevious()); + self::assertStringContainsString('cURL errno 7', (string) $e->getPrevious()?->getMessage()); + } + } + + public function testAnUnclassifiableClientErrorIsUnknownOutcome(): void + { + $client = new class implements ClientInterface { + public function sendRequest(RequestInterface $request): ResponseInterface + { + throw new class ('socket closed') extends \RuntimeException implements NetworkExceptionInterface { + public function getRequest(): RequestInterface + { + return new Request('GET', 'https://x'); + } + }; + } + }; + $factory = new HttpFactory(); + $transport = new Psr18Transport($client, $factory, $factory, clientManagesTimeouts: true); + + try { + $transport->send($this->request()); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + self::assertSame(TransportFailure::UnknownOutcome, $e->failure); + } + + $throwing = new class implements ClientInterface { + public function sendRequest(RequestInterface $request): ResponseInterface + { + throw new \LogicException('not a PSR-18 exception'); + } + }; + try { + (new Psr18Transport($throwing, $factory, $factory, clientManagesTimeouts: true))->send($this->request()); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + self::assertSame(TransportFailure::UnknownOutcome, $e->failure); + } + } + + public function testErrorChainCarriesNoRequestData(): void + { + $request = new Request('POST', 'https://x/v1/walletcashin/process', ['Authorization' => 'SELCOM c2VjcmV0LWtleQ==', 'Digest' => 'abc=='], '{"msisdn":"255700000001","pin":"4321"}'); + $mock = new MockHandler([new ConnectException('cURL error 7: failed 255700000001 SELCOM c2VjcmV0LWtleQ== abc== 4321', $request, null, ['errno' => 7])]); + $factory = new HttpFactory(); + $transport = new Psr18Transport($this->guzzle($mock), $factory, $factory, clientManagesTimeouts: true); + + try { + $transport->send($this->request()); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + $text = ''; + for ($c = $e; $c !== null; $c = $c->getPrevious()) { + $text .= $c->getMessage() . " +"; + } + foreach (['255700000001', 'c2VjcmV0LWtleQ==', 'abc==', '4321'] as $value) { + self::assertStringNotContainsString($value, $text); + } + } + } + + public function testARefusedConnectionToARealClosedLocalPortIsNotSent(): void + { + $socket = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr); + self::assertNotFalse($socket); + $name = stream_socket_get_name($socket, false); + self::assertIsString($name); + fclose($socket); // the port is now closed + $port = (int) substr($name, (int) strrpos($name, ':') + 1); + + $transport = Psr18Transport::discover(); + $request = new TransportRequest( + 'POST', + 'http://127.0.0.1:' . $port . '/v1/vendor/balance', + ['Accept' => 'application/json'], + '{"vendor":"TILL123"}', + (new Timeouts())->payment, + ); + + try { + $transport->send($request); + self::fail('expected a TransportException'); + } catch (TransportException $e) { + self::assertSame(TransportFailure::NotSent, $e->failure); + } + } + + public function testAReadyClientNeedsAnExplicitChoiceAboutTimeouts(): void + { + $client = $this->guzzle(new MockHandler([])); + $this->expectException(ConfigurationException::class); + new Psr18Transport($client); + } + + public function testWritesUseAFreshConnectionWithQueryTimeouts(): void + { + $timeouts = new Timeouts(); + foreach ([Operation::CheckoutCreateOrder, Operation::CheckoutCreateOrderMinimal, Operation::CheckoutCancelOrder, Operation::CheckoutDeleteCard] as $op) { + $profile = $timeouts->forOperation($op); + self::assertTrue($profile->freshConnection, $op->value); + self::assertSame([10.0, 10.0], [$profile->connectSeconds, $profile->readSeconds]); + } + foreach ([Operation::CheckoutWalletPayment, Operation::UtilityPaymentProcess, Operation::WalletCashinProcess, Operation::CheckoutCardPayment] as $op) { + self::assertSame([15.0, 180.0, true], [$timeouts->forOperation($op)->connectSeconds, $timeouts->forOperation($op)->readSeconds, $timeouts->forOperation($op)->freshConnection]); + } + foreach ([Operation::CheckoutOrderStatus, Operation::UtilityPaymentQuery, Operation::VendorBalance, Operation::CheckoutListOrders] as $op) { + self::assertFalse($timeouts->forOperation($op)->freshConnection, $op->value); + } + } + + public function testPaymentProfileUsesAFreshConnection(): void + { + $payment = (new Timeouts())->payment; + self::assertTrue($payment->freshConnection); + $options = Psr18Transport::guzzleOptions($payment); + self::assertSame(195.0, $options['timeout']); + self::assertSame(15.0, $options['connect_timeout']); + if (defined('CURLOPT_FRESH_CONNECT')) { + self::assertSame([CURLOPT_FRESH_CONNECT => true, CURLOPT_FORBID_REUSE => true], $options['curl']); + } + self::assertArrayNotHasKey('curl', Psr18Transport::guzzleOptions((new Timeouts())->query)); + // A payment profile given without the flag still gets it. + self::assertTrue((new Timeouts(null, new TimeoutProfile(20.0, 200.0)))->payment->freshConnection); + } + + public function testDiscoveryFindsAClientAndFactories(): void + { + $transport = Psr18Transport::discover(); + // Only construction is exercised: no network call is made. + self::assertInstanceOf(Psr18Transport::class, $transport); + } +} diff --git a/tests/WebhookVectorsTest.php b/tests/WebhookVectorsTest.php new file mode 100644 index 0000000..64e87cc --- /dev/null +++ b/tests/WebhookVectorsTest.php @@ -0,0 +1,105 @@ + $headers */ + $headers = $sample['headers']; + + $verdict = $verifier->verify($headers, $sample['raw_body']); + self::assertSame($sample['expected_verification'], $verdict->value, $sample['name']); + + $payload = WebhookPayload::fromRawBody($sample['raw_body']); + self::assertSame($sample['expected_amount_tzs'], $payload->amountTzs, $sample['name']); + } + } + + public function testHeaderNamesAreCaseInsensitiveAndListsAreAccepted(): void + { + $fixture = Vectors::load('responses/checkout.webhook.json'); + $verification = $fixture['verification']; + $samples = $fixture['samples']; + self::assertIsArray($verification); + self::assertIsArray($samples); + $first = $samples[0]; + self::assertIsArray($first); + self::assertIsArray($first['headers']); + self::assertIsString($first['raw_body']); + self::assertIsString($verification['secret']); + self::assertIsString($verification['now']); + + $lower = []; + foreach ($first['headers'] as $name => $value) { + self::assertIsString($value); + $lower[strtolower((string) $name)] = [$value]; + } + $verifier = new WebhookVerifier($verification['secret'], FixedClock::at($verification['now'])); + self::assertSame(WebhookVerdict::Valid, $verifier->verify($lower, $first['raw_body'])); + } + + public function testVerdictResponseTable(): void + { + self::assertSame(200, WebhookVerdict::Valid->httpStatus()); + self::assertSame(200, WebhookVerdict::Unsigned->httpStatus()); + self::assertSame(200, WebhookVerdict::Replay->httpStatus()); + self::assertSame(401, WebhookVerdict::Invalid->httpStatus()); + self::assertSame(401, WebhookVerdict::Stale->httpStatus()); + self::assertTrue(WebhookVerdict::Valid->shouldProcess()); + self::assertTrue(WebhookVerdict::Unsigned->shouldProcess()); + self::assertFalse(WebhookVerdict::Replay->shouldProcess()); + self::assertFalse(WebhookVerdict::Invalid->shouldProcess()); + self::assertFalse(WebhookVerdict::Stale->shouldProcess()); + } + + public function testGarbageIsInvalidNotAnException(): void + { + $verifier = new WebhookVerifier('s', FixedClock::at('2026-11-21T10:31:00+03:00')); + $headers = [ + 'Digest' => 'abc', + 'Digest-Method' => 'HS256', + 'Timestamp' => '2026-11-21T10:30:46+03:00', + 'Signed-Fields' => 'a', + ]; + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, 'not json')); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, '[1,2]')); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, '{"a":[1]}')); + self::assertSame(WebhookVerdict::Invalid, $verifier->verify($headers, '{"a":1.5}')); + } +} diff --git a/tests/vectors/responses/checkout.cancel-order.json b/tests/vectors/responses/checkout.cancel-order.json new file mode 100644 index 0000000..84d69c3 --- /dev/null +++ b/tests/vectors/responses/checkout.cancel-order.json @@ -0,0 +1,81 @@ +{ + "operation": "checkout.cancel-order", + "method": "DELETE", + "path": "/v1/checkout/cancel-order", + "kind": "other", + "notes": "A failed cancel can mean the order was already paid. Check order-status before treating the order as unpaid.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order cancelled successfully", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Completed or expired orders cannot be cancelled (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.card-payment.json b/tests/vectors/responses/checkout.card-payment.json new file mode 100644 index 0000000..41fb4d9 --- /dev/null +++ b/tests/vectors/responses/checkout.card-payment.json @@ -0,0 +1,141 @@ +{ + "operation": "checkout.card-payment", + "method": "POST", + "path": "/v1/checkout/card-payment", + "kind": "payment", + "notes": "Money-moving. Never retried automatically, even after a timeout. Settle every non-final result with order-status.", + "scenarios": [ + { + "name": "accepted-111", + "description": "The usual answer: the charge is being processed. Wait for the webhook, then confirm with order-status.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "PENDING", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Payment completed (sample)", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Card token not valid for this buyer (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + }, + { + "name": "in-progress-927", + "description": "Result code 927 is also in progress.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "927", + "result": "INPROGRESS", + "message": "Transaction in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success-blank-result", + "description": "Result code 000 with an empty result text is still a success. Classify by resultcode only.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "", + "message": "Transaction successful", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "result-text-ignored", + "description": "The result text says SUCCESS but the code is 111. The code wins.", + "http_status": 200, + "body": { + "transid": "TXN-CRD-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "SUCCESS", + "message": "Request in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + } + ] +} diff --git a/tests/vectors/responses/checkout.create-order-minimal.json b/tests/vectors/responses/checkout.create-order-minimal.json new file mode 100644 index 0000000..b90da2b --- /dev/null +++ b/tests/vectors/responses/checkout.create-order-minimal.json @@ -0,0 +1,87 @@ +{ + "operation": "checkout.create-order-minimal", + "method": "POST", + "path": "/v1/checkout/create-order-minimal", + "kind": "other", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order created successfully", + "data": [ + { + "gateway_buyer_uuid": "GBU-TEST-0001", + "payment_token": "80000002", + "qr": "QR-PLACEHOLDER", + "payment_gateway_url": "aHR0cHM6Ly9jaGVja291dC5leGFtcGxlLmNvbS9wYXkvT1JELTEwMDM=" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Duplicate order_id (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.create-order.json b/tests/vectors/responses/checkout.create-order.json new file mode 100644 index 0000000..a34cbf5 --- /dev/null +++ b/tests/vectors/responses/checkout.create-order.json @@ -0,0 +1,88 @@ +{ + "operation": "checkout.create-order", + "method": "POST", + "path": "/v1/checkout/create-order", + "kind": "other", + "notes": "payment_gateway_url in data is base64-encoded. Decode it for the caller and keep the raw value.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order created successfully", + "data": [ + { + "gateway_buyer_uuid": "GBU-TEST-0001", + "payment_token": "80000001", + "qr": "QR-PLACEHOLDER", + "payment_gateway_url": "aHR0cHM6Ly9jaGVja291dC5leGFtcGxlLmNvbS9wYXkvT1JELTEwMDU=" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Duplicate order_id (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.delete-card.json b/tests/vectors/responses/checkout.delete-card.json new file mode 100644 index 0000000..16a3008 --- /dev/null +++ b/tests/vectors/responses/checkout.delete-card.json @@ -0,0 +1,80 @@ +{ + "operation": "checkout.delete-card", + "method": "DELETE", + "path": "/v1/checkout/delete-card", + "kind": "other", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Delete successful", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Card not found for this buyer (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.list-orders.json b/tests/vectors/responses/checkout.list-orders.json new file mode 100644 index 0000000..bb19c73 --- /dev/null +++ b/tests/vectors/responses/checkout.list-orders.json @@ -0,0 +1,94 @@ +{ + "operation": "checkout.list-orders", + "method": "GET", + "path": "/v1/checkout/list-orders", + "kind": "other", + "notes": "The status here describes the call. Per-order verdicts come from each entry's payment_status, mapped as for order-status.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "COMPLETED" + }, + { + "order_id": "ORD-1004", + "creation_date": "2026-11-21 10:40:00", + "amount": "1000", + "payment_status": "PENDING" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Invalid date range (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.order-status.json b/tests/vectors/responses/checkout.order-status.json new file mode 100644 index 0000000..0ba350b --- /dev/null +++ b/tests/vectors/responses/checkout.order-status.json @@ -0,0 +1,297 @@ +{ + "operation": "checkout.order-status", + "method": "GET", + "path": "/v1/checkout/order-status", + "kind": "order-status", + "notes": "The top-level resultcode only says whether the query worked. The payment verdict is data[0].payment_status.", + "scenarios": [ + { + "name": "completed", + "description": "payment_status COMPLETED: paid. Payment fields are filled only on completed orders.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "COMPLETED", + "transid": "TXN-WLT-0001", + "channel": "AIRTELMONEY", + "reference": "REF0000000201", + "phone": "255700000001" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "completed-lowercase", + "description": "payment_status is compared case-insensitively.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "completed", + "transid": "TXN-WLT-0001", + "channel": "AIRTELMONEY", + "reference": "REF0000000201", + "phone": "255700000001" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "pending", + "description": "payment_status PENDING: not paid yet.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "PENDING", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "PENDING" + }, + { + "name": "inprogress", + "description": "payment_status INPROGRESS: a payment attempt is under way.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "INPROGRESS", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "PENDING" + }, + { + "name": "cancelled", + "description": "payment_status CANCELLED.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "CANCELLED", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "FAILED" + }, + { + "name": "usercancelled", + "description": "payment_status USERCANCELLED: the buyer cancelled on the payment page.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "USERCANCELLED", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "FAILED" + }, + { + "name": "usercanceled-one-l", + "description": "Accept the one-L spelling too.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "USERCANCELED", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "FAILED" + }, + { + "name": "rejected", + "description": "payment_status REJECTED: the attempt was declined.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "REJECTED", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "FAILED" + }, + { + "name": "unknown-payment-status", + "description": "A payment_status this spec does not list. Not a verdict: AMBIGUOUS.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [ + { + "order_id": "ORD-1003", + "creation_date": "2026-11-21 10:30:00", + "amount": "5000", + "payment_status": "SETTLING", + "transid": null, + "channel": null, + "reference": null, + "phone": null + } + ] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "empty-data", + "description": "Result code 000 with no order in data: the order does not exist.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Order fetch successful", + "data": [] + }, + "expected_status": "NOT_FOUND" + }, + { + "name": "not-found-404", + "description": "Result code 404: the order does not exist.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Order not found (sample)", + "data": [] + }, + "expected_status": "NOT_FOUND" + }, + { + "name": "query-in-progress-111", + "description": "The query itself returned 111.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "query-ambiguous-999", + "description": "The query itself returned 999.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "query-rejected", + "description": "The query failed (here a made-up 403). That says nothing about the order: AMBIGUOUS, never FAILED.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "403", + "result": "FAIL", + "message": "Request rejected (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body. Not a verdict: AMBIGUOUS.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + } + ] +} diff --git a/tests/vectors/responses/checkout.stored-cards.json b/tests/vectors/responses/checkout.stored-cards.json new file mode 100644 index 0000000..3693dcd --- /dev/null +++ b/tests/vectors/responses/checkout.stored-cards.json @@ -0,0 +1,98 @@ +{ + "operation": "checkout.stored-cards", + "method": "GET", + "path": "/v1/checkout/stored-cards", + "kind": "other", + "notes": "card_type 001 is Visa and 002 is Mastercard. Card tokens are sensitive: never log them in full.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Card fetch successful", + "data": [ + { + "id": 23, + "masked_card": "4111-11XX-XXXX-1111", + "creation_date": "2026-11-01 09:00:00", + "card_token": "CARDTOKEN-TEST-0001", + "name": "TEST BUYER", + "card_type": "001" + }, + { + "id": 24, + "masked_card": "5555-55XX-XXXX-4444", + "creation_date": "2026-11-02 09:00:00", + "card_token": "CARDTOKEN-TEST-0002", + "name": "TEST BUYER", + "card_type": "002" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Unknown buyer (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/checkout.wallet-payment.json b/tests/vectors/responses/checkout.wallet-payment.json new file mode 100644 index 0000000..488b19e --- /dev/null +++ b/tests/vectors/responses/checkout.wallet-payment.json @@ -0,0 +1,141 @@ +{ + "operation": "checkout.wallet-payment", + "method": "POST", + "path": "/v1/checkout/wallet-payment", + "kind": "payment", + "notes": "Money-moving. Never retried automatically, even after a timeout. Settle every non-final result with order-status.", + "scenarios": [ + { + "name": "push-sent-111", + "description": "The usual answer: the USSD push was sent and the buyer has not approved yet. Wait for the webhook, then confirm with order-status.", + "http_status": 200, + "body": { + "reference": "REF0000000001", + "resultcode": "111", + "result": "PENDING", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Payment completed (sample)", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Invalid mobile number (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + }, + { + "name": "in-progress-927", + "description": "Result code 927 is also in progress.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "927", + "result": "INPROGRESS", + "message": "Transaction in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success-blank-result", + "description": "Result code 000 with an empty result text is still a success. Classify by resultcode only.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "", + "message": "Transaction successful", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "result-text-ignored", + "description": "The result text says SUCCESS but the code is 111. The code wins.", + "http_status": 200, + "body": { + "transid": "TXN-WLT-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "SUCCESS", + "message": "Request in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + } + ] +} diff --git a/tests/vectors/responses/checkout.webhook.json b/tests/vectors/responses/checkout.webhook.json new file mode 100644 index 0000000..d5cd242 --- /dev/null +++ b/tests/vectors/responses/checkout.webhook.json @@ -0,0 +1,231 @@ +{ + "operation": "checkout.webhook", + "notes": "Process the samples in order with one replay store. Verification uses the secret below (the sample secret printed in Selcom's public docs), 'now' as the current time and a 300-second window. Which key Selcom really signs webhooks with is an open question: see docs/webhooks.md.", + "verification": { + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "now": "2026-11-21T10:31:00+03:00", + "window_seconds": 300 + }, + "samples": [ + { + "name": "completed-signed", + "description": "A signed delivery for a completed payment. Verify, store, acknowledge, then confirm with order-status before fulfilling.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "u/h/Ix4sMp69scjQKUqYET/28BfOftik2YWhcX7IsDA=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2001\",\"transid\":\"TXN-WLT-2001\",\"reference\":\"REF0000002001\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "VALID", + "expected_amount_tzs": 10000 + }, + { + "name": "completed-signed-redelivered", + "description": "The same delivery again, byte for byte. Acknowledge with 200 and do nothing else.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "u/h/Ix4sMp69scjQKUqYET/28BfOftik2YWhcX7IsDA=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2001\",\"transid\":\"TXN-WLT-2001\",\"reference\":\"REF0000002001\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "REPLAY", + "expected_amount_tzs": 10000 + }, + { + "name": "amount-with-thousands-separator", + "description": "amount arrives as \"10,000\". Parse it as 10000 whole shillings.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "dkQLyJVajPB5Qpe4UmgS9d6pG4O47hWypqb/zSjr/gs=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2002\",\"transid\":\"TXN-WLT-2002\",\"reference\":\"REF0000002002\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10,000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "VALID", + "expected_amount_tzs": 10000 + }, + { + "name": "unsigned-field-changed", + "description": "amount is not in Signed-Fields, so changing it does not break the signature. VALID vouches only for signed fields; take the amount from order-status.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "zHjQ3w5Jqj9HtSm2CsvDC20asiq46yKdu1cBtsrenTI=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2003\",\"transid\":\"TXN-WLT-2003\",\"reference\":\"REF0000002003\",\"channel\":\"AIRTELMONEY\",\"amount\":\"1\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "VALID", + "expected_amount_tzs": 1 + }, + { + "name": "signed-field-tampered", + "description": "Signed as PENDING, delivered as COMPLETED. Reject.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "Txue+EM3UhvJEmn5KFsOj0hs6/WT9RcN+UjKWdX4YAk=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2004\",\"transid\":\"TXN-WLT-2004\",\"reference\":\"REF0000002004\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "wrong-secret", + "description": "Signed with a different secret. Reject.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "7FgKwMbpMZA0WNBexdyMPHoop/iNUAGlHxcPp8ZQ1yw=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2005\",\"transid\":\"TXN-WLT-2005\",\"reference\":\"REF0000002005\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "stale-timestamp", + "description": "Correctly signed an hour before now, outside the 300-second window. Reject.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "UVDTKxURYXbGXrHvjKcYk3uYqDTp1ePcemAXJKwG/yM=", + "Timestamp": "2026-11-21T09:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2006\",\"transid\":\"TXN-WLT-2006\",\"reference\":\"REF0000002006\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "STALE", + "expected_amount_tzs": 10000 + }, + { + "name": "signed-field-missing-from-body", + "description": "Signed-Fields names msisdn, which the body does not contain. Reject.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "tkrO0FLcz5ZAu0QDZILQRGn26gPfgbITb91GUUz8Tts=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status,msisdn" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2007\",\"transid\":\"TXN-WLT-2007\",\"reference\":\"REF0000002007\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "unsigned-delivery", + "description": "No Digest header. Nothing to verify: store it, acknowledge, and rely on order-status.", + "headers": { + "Content-Type": "application/json" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2008\",\"transid\":\"TXN-WLT-2008\",\"reference\":\"REF0000002008\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "UNSIGNED", + "expected_amount_tzs": 10000 + }, + { + "name": "failed-payment-signed", + "description": "A valid delivery reporting a failed payment. The docs say webhooks come only for successes, so be ready for this anyway. It must not overturn a recorded SUCCESS.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "mHCD+85lznsrDqbisDYqUsEyiPuNTfXsb7JDiyfpmnw=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"FAIL\",\"resultcode\":\"400\",\"order_id\":\"ORD-2009\",\"transid\":\"TXN-WLT-2009\",\"reference\":\"REF0000002009\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"CANCELLED\"}", + "expected_verification": "VALID", + "expected_amount_tzs": 10000 + }, + { + "name": "empty-digest-header", + "description": "Digest header present but empty. That is not an unsigned delivery: reject.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"order_id\":\"ORD-2010\",\"transid\":\"TXN-WLT-2010\",\"reference\":\"REF0000002010\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\",\"payment_status\":\"COMPLETED\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "signed-fields-missing-order-id", + "description": "Correctly signed, but Signed-Fields leaves out order_id. INVALID.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "iKI3U6Y7gX5xLUGHntHCUC2brSQRnNfLxxwzeNv/u78=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"transid\":\"TXN-WLT-2101\",\"order_id\":\"ORD-2101\",\"reference\":\"REF0000002101\",\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"payment_status\":\"COMPLETED\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "signed-fields-missing-transid", + "description": "Correctly signed, but Signed-Fields leaves out transid. INVALID.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "RaRn9auB8nJMMGnehk9TTnqa1lQjPESFAprOwE64yCY=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"transid\":\"TXN-WLT-2101\",\"order_id\":\"ORD-2101\",\"reference\":\"REF0000002101\",\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"payment_status\":\"COMPLETED\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "signed-value-with-ampersand", + "description": "Correctly signed, but a signed value contains '&'. INVALID.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "eP6DuS1sg6x/6Dz1+UDDRFj4GuS1vYahNrCyZ8j1MQo=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,reference,result,resultcode,payment_status" + }, + "raw_body": "{\"transid\":\"TXN-WLT-2101&x\",\"order_id\":\"ORD-2101\",\"reference\":\"REF0000002101\",\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"payment_status\":\"COMPLETED\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + }, + { + "name": "signed-field-name-with-ampersand", + "description": "Correctly signed, but a signed field name contains '&'. INVALID.", + "headers": { + "Content-Type": "application/json", + "Authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "Digest-Method": "HS256", + "Digest": "8sLwx+NeDcVWmNDtaU2r+KJTDU9v7ishJnh7NSwhCDo=", + "Timestamp": "2026-11-21T10:30:46+03:00", + "Signed-Fields": "transid,order_id,ref&x,result,resultcode,payment_status" + }, + "raw_body": "{\"transid\":\"TXN-WLT-2101\",\"order_id\":\"ORD-2101\",\"ref&x\":\"REF0000002101\",\"result\":\"SUCCESS\",\"resultcode\":\"000\",\"payment_status\":\"COMPLETED\",\"channel\":\"AIRTELMONEY\",\"amount\":\"10000\",\"phone\":\"255700000001\"}", + "expected_verification": "INVALID", + "expected_amount_tzs": 10000 + } + ] +} diff --git a/tests/vectors/responses/utilitypayment.lookup.json b/tests/vectors/responses/utilitypayment.lookup.json new file mode 100644 index 0000000..19412c5 --- /dev/null +++ b/tests/vectors/responses/utilitypayment.lookup.json @@ -0,0 +1,90 @@ +{ + "operation": "utilitypayment.lookup", + "method": "GET", + "path": "/v1/utilitypayment/lookup", + "kind": "other", + "notes": "A lookup moves no money. Its 404 is a failed lookup, not NOT_FOUND.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-LKP-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "LUKU confirmation (sample)", + "data": [ + { + "name": "TEST CUSTOMER" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-LKP-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-LKP-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-LKP-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Invalid meter number (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-LKP-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/utilitypayment.process.json b/tests/vectors/responses/utilitypayment.process.json new file mode 100644 index 0000000..dbe4424 --- /dev/null +++ b/tests/vectors/responses/utilitypayment.process.json @@ -0,0 +1,132 @@ +{ + "operation": "utilitypayment.process", + "method": "POST", + "path": "/v1/utilitypayment/process", + "kind": "payment", + "notes": "Money-moving. Never retried automatically. Settle PENDING and AMBIGUOUS with utilitypayment.query after 3 minutes or more, using the same transid.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "LUKU payment successful (sample)", + "data": [ + { + "receipt": "RCPT-TEST-0001" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Invalid meter number (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + }, + { + "name": "in-progress-927", + "description": "Result code 927 is also in progress.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "927", + "result": "INPROGRESS", + "message": "Transaction in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success-blank-result", + "description": "Result code 000 with an empty result text is still a success. Classify by resultcode only.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "", + "message": "Transaction successful", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "result-text-ignored", + "description": "The result text says SUCCESS but the code is 111. The code wins.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "SUCCESS", + "message": "Request in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + } + ] +} diff --git a/tests/vectors/responses/utilitypayment.query.json b/tests/vectors/responses/utilitypayment.query.json new file mode 100644 index 0000000..feb1f34 --- /dev/null +++ b/tests/vectors/responses/utilitypayment.query.json @@ -0,0 +1,104 @@ +{ + "operation": "utilitypayment.query", + "method": "GET", + "path": "/v1/utilitypayment/query", + "kind": "status-query", + "notes": "The resultcode is the verdict on the earlier payment. 404 means the gateway never recorded the transid: only then may the same transid be submitted again.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Transaction successful", + "data": [ + { + "receipt": "RCPT-TEST-0001" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Transaction failed (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on a status query: the gateway has no record of this id.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "NOT_FOUND" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + }, + { + "name": "numeric-resultcode", + "description": "resultcode sent as a JSON number. Normalise to a three-digit string before comparing.", + "http_status": 200, + "body": { + "transid": "TXN-UTL-0001", + "reference": "REF0000000001", + "resultcode": 0, + "result": "SUCCESS", + "message": "Transaction successful", + "data": [] + }, + "expected_status": "SUCCESS" + } + ] +} diff --git a/tests/vectors/responses/vendor.balance.json b/tests/vectors/responses/vendor.balance.json new file mode 100644 index 0000000..f2a7abd --- /dev/null +++ b/tests/vectors/responses/vendor.balance.json @@ -0,0 +1,90 @@ +{ + "operation": "vendor.balance", + "method": "POST", + "path": "/v1/vendor/balance", + "kind": "other", + "notes": "A POST that moves no money. The balance is a string of whole shillings.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-BAL-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Balance successful", + "data": [ + { + "balance": "1000000" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-BAL-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-BAL-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-BAL-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Invalid PIN (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-BAL-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/walletcashin.namelookup.json b/tests/vectors/responses/walletcashin.namelookup.json new file mode 100644 index 0000000..f878882 --- /dev/null +++ b/tests/vectors/responses/walletcashin.namelookup.json @@ -0,0 +1,90 @@ +{ + "operation": "walletcashin.namelookup", + "method": "GET", + "path": "/v1/walletcashin/namelookup", + "kind": "other", + "notes": "A lookup moves no money. Its 404 is a failed lookup, not NOT_FOUND.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Name fetch successful", + "data": [ + { + "name": "TEST RECEIVER" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Wallet not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code on an operation that moves no money: raise an invalid-response error.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_error": "INVALID_RESPONSE" + } + ] +} diff --git a/tests/vectors/responses/walletcashin.process.json b/tests/vectors/responses/walletcashin.process.json new file mode 100644 index 0000000..526c7e1 --- /dev/null +++ b/tests/vectors/responses/walletcashin.process.json @@ -0,0 +1,128 @@ +{ + "operation": "walletcashin.process", + "method": "POST", + "path": "/v1/walletcashin/process", + "kind": "payment", + "notes": "Money-moving. Never retried automatically. Settle PENDING and AMBIGUOUS with walletcashin.query after 3 minutes or more, using the same transid.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Cash-in successful (sample)", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Insufficient float balance (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on an operation that is not a status query is an ordinary failure, not NOT_FOUND.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + }, + { + "name": "in-progress-927", + "description": "Result code 927 is also in progress.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "927", + "result": "INPROGRESS", + "message": "Transaction in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "success-blank-result", + "description": "Result code 000 with an empty result text is still a success. Classify by resultcode only.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "", + "message": "Transaction successful", + "data": [] + }, + "expected_status": "SUCCESS" + }, + { + "name": "result-text-ignored", + "description": "The result text says SUCCESS but the code is 111. The code wins.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "SUCCESS", + "message": "Request in progress (sample)", + "data": [] + }, + "expected_status": "PENDING" + } + ] +} diff --git a/tests/vectors/responses/walletcashin.query.json b/tests/vectors/responses/walletcashin.query.json new file mode 100644 index 0000000..00f6006 --- /dev/null +++ b/tests/vectors/responses/walletcashin.query.json @@ -0,0 +1,90 @@ +{ + "operation": "walletcashin.query", + "method": "GET", + "path": "/v1/walletcashin/query", + "kind": "status-query", + "notes": "The resultcode is the verdict on the earlier cash-in. 404 means the gateway never recorded the transid: only then may the same transid be submitted again.", + "scenarios": [ + { + "name": "success", + "description": "Result code 000.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "000", + "result": "SUCCESS", + "message": "Transaction successful", + "data": [ + { + "receipt": "RCPT-TEST-0002" + } + ] + }, + "expected_status": "SUCCESS" + }, + { + "name": "in-progress-111", + "description": "Result code 111: still processing. Query again after 3 minutes or more.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "111", + "result": "INPROGRESS", + "message": "Request in progress. You will receive a callback shortly.", + "data": [] + }, + "expected_status": "PENDING" + }, + { + "name": "ambiguous-999", + "description": "Result code 999: outcome unknown, wait for reconciliation. Never resubmit.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "999", + "result": "AMBIGUOUS", + "message": "Transaction status unknown (sample)", + "data": [] + }, + "expected_status": "AMBIGUOUS" + }, + { + "name": "failure", + "description": "Result code 400: any code outside 000, 111, 927, 999 (and 404 on a query) is a failure.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "400", + "result": "FAIL", + "message": "Transaction failed (sample)", + "data": [] + }, + "expected_status": "FAILED" + }, + { + "name": "not-found-404", + "description": "Result code 404 on a status query: the gateway has no record of this id.", + "http_status": 200, + "body": { + "transid": "TXN-CSH-0001", + "reference": "REF0000000001", + "resultcode": "404", + "result": "FAIL", + "message": "Record not found (sample)", + "data": [] + }, + "expected_status": "NOT_FOUND" + }, + { + "name": "gateway-error-no-json", + "description": "No JSON body and no result code. Not a verdict: report AMBIGUOUS, never FAILED.", + "http_status": 502, + "raw_body": "

502 Bad Gateway

", + "expected_status": "AMBIGUOUS" + } + ] +} diff --git a/tests/vectors/signing.json b/tests/vectors/signing.json new file mode 100644 index 0000000..816896b --- /dev/null +++ b/tests/vectors/signing.json @@ -0,0 +1,868 @@ +{ + "$comment": "Generated by tools/generate_vectors.py from tools/selcom_reference.py. Do not edit by hand. Rules: docs/signing.md.", + "version": 1, + "credentials_note": "api_key and secret values are the sample values printed in Selcom's public documentation, or made up. None of them is a working credential.", + "cases": [ + { + "id": "known-get-single-field", + "description": "Known vector. One field on a GET; also fixes the Authorization value for the docs sample key.", + "known": true, + "scope": "request", + "method": "GET", + "path": "/v1/checkout/order-status", + "timestamp": "2019-02-26T09:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "expected": { + "flattened": [ + ["order_id", "ORD-1001"] + ], + "signed_fields": "order_id", + "signing_string": "timestamp=2019-02-26T09:30:46+03:00&order_id=ORD-1001", + "digest": "pR8qs83hQ34a6EoxXGOKL4yg+JDeJAtzOY6E8fTlvwk=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "order_id=ORD-1001" + } + }, + { + "id": "known-post-nested-billing", + "description": "Known vector. A nested billing object flattens to billing.firstname; the integer amount signs as 8000.", + "known": true, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2019-02-26T09:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1001", + "amount": 8000, + "billing": { + "firstname": "John" + } + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1001"], + ["amount", 8000], + ["billing.firstname", "John"] + ], + "signed_fields": "vendor,order_id,amount,billing.firstname", + "signing_string": "timestamp=2019-02-26T09:30:46+03:00&vendor=TILL123&order_id=ORD-1001&amount=8000&billing.firstname=John", + "digest": "1RVQp/zJv4qFUPBYjAGwZ9kUPINsYSLc9030CfIWwPM=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1001\",\"amount\":8000,\"billing.firstname\":\"John\"}" + } + }, + { + "id": "flat-dotted-key-same-as-nested", + "description": "The caller passes billing.firstname already flat. Same wire form and digest as known-post-nested-billing.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2019-02-26T09:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1001", + "amount": 8000, + "billing.firstname": "John" + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1001"], + ["amount", 8000], + ["billing.firstname", "John"] + ], + "signed_fields": "vendor,order_id,amount,billing.firstname", + "signing_string": "timestamp=2019-02-26T09:30:46+03:00&vendor=TILL123&order_id=ORD-1001&amount=8000&billing.firstname=John", + "digest": "1RVQp/zJv4qFUPBYjAGwZ9kUPINsYSLc9030CfIWwPM=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1001\",\"amount\":8000,\"billing.firstname\":\"John\"}" + } + }, + { + "id": "delete-same-digest-as-get", + "description": "DELETE with the same field and timestamp as known-get-single-field. Method and path are not signed, so the digest is identical.", + "known": false, + "scope": "request", + "method": "DELETE", + "path": "/v1/checkout/cancel-order", + "timestamp": "2019-02-26T09:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "expected": { + "flattened": [ + ["order_id", "ORD-1001"] + ], + "signed_fields": "order_id", + "signing_string": "timestamp=2019-02-26T09:30:46+03:00&order_id=ORD-1001", + "digest": "pR8qs83hQ34a6EoxXGOKL4yg+JDeJAtzOY6E8fTlvwk=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "order_id=ORD-1001" + } + }, + { + "id": "get-query-three-params", + "description": "GET with three query parameters, signed in send order.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/utilitypayment/lookup", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "utilitycode": "LUKU", + "utilityref": "01234567891", + "transid": "TXN-LKP-0001" + }, + "expected": { + "flattened": [ + ["utilitycode", "LUKU"], + ["utilityref", "01234567891"], + ["transid", "TXN-LKP-0001"] + ], + "signed_fields": "utilitycode,utilityref,transid", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&utilitycode=LUKU&utilityref=01234567891&transid=TXN-LKP-0001", + "digest": "8muFCf0vV2uNkfiJDro/QpnRA7N2kL0hPTKh1SCWldo=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "utilitycode=LUKU&utilityref=01234567891&transid=TXN-LKP-0001" + } + }, + { + "id": "get-list-orders-date-range", + "description": "GET with date values; hyphens are unreserved and stay as they are in the query string.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/checkout/list-orders", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "fromdate": "2026-11-01", + "todate": "2026-11-21" + }, + "expected": { + "flattened": [ + ["fromdate", "2026-11-01"], + ["todate", "2026-11-21"] + ], + "signed_fields": "fromdate,todate", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&fromdate=2026-11-01&todate=2026-11-21", + "digest": "OoiH9Wdtja55xcEo2FunpHHJogi2/tPDUrHqAuqiUw8=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "fromdate=2026-11-01&todate=2026-11-21" + } + }, + { + "id": "delete-integer-param", + "description": "DELETE with an integer id. It signs and encodes as plain digits.", + "known": false, + "scope": "request", + "method": "DELETE", + "path": "/v1/checkout/delete-card", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "id": 23, + "gateway_buyer_uuid": "GBU-TEST-0001" + }, + "expected": { + "flattened": [ + ["id", 23], + ["gateway_buyer_uuid", "GBU-TEST-0001"] + ], + "signed_fields": "id,gateway_buyer_uuid", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&id=23&gateway_buyer_uuid=GBU-TEST-0001", + "digest": "d7wv/59d5l+VkiBezLjlmisbBz7ZO9XhOGT2DMjD4IQ=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "id=23&gateway_buyer_uuid=GBU-TEST-0001" + } + }, + { + "id": "get-null-becomes-empty", + "description": "A null value signs as an empty string and is sent as key= with nothing after the equals sign.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/checkout/stored-cards", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "gateway_buyer_uuid": "GBU-TEST-0001", + "buyer_userid": null + }, + "expected": { + "flattened": [ + ["gateway_buyer_uuid", "GBU-TEST-0001"], + ["buyer_userid", ""] + ], + "signed_fields": "gateway_buyer_uuid,buyer_userid", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&gateway_buyer_uuid=GBU-TEST-0001&buyer_userid=", + "digest": "H3++oilMCm7U4C+fMDFMSCJSuh031XW1EMho3L9eMNw=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "gateway_buyer_uuid=GBU-TEST-0001&buyer_userid=" + } + }, + { + "id": "post-nested-billing-with-null", + "description": "Several billing fields flatten in order, in place. The null address_2 signs and is sent as an empty string.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1002", + "amount": 15000, + "currency": "TZS", + "billing": { + "firstname": "Test", + "lastname": "Buyer", + "address_1": "1 Example Street", + "address_2": null, + "city": "Dar es Salaam", + "phone": "255700000000" + }, + "no_of_items": 1 + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1002"], + ["amount", 15000], + ["currency", "TZS"], + ["billing.firstname", "Test"], + ["billing.lastname", "Buyer"], + ["billing.address_1", "1 Example Street"], + ["billing.address_2", ""], + ["billing.city", "Dar es Salaam"], + ["billing.phone", "255700000000"], + ["no_of_items", 1] + ], + "signed_fields": "vendor,order_id,amount,currency,billing.firstname,billing.lastname,billing.address_1,billing.address_2,billing.city,billing.phone,no_of_items", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&vendor=TILL123&order_id=ORD-1002&amount=15000¤cy=TZS&billing.firstname=Test&billing.lastname=Buyer&billing.address_1=1 Example Street&billing.address_2=&billing.city=Dar es Salaam&billing.phone=255700000000&no_of_items=1", + "digest": "x7HHnTjDyBQ3XnQglXoQMUmg292KZz/f+3c11vO8vEo=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1002\",\"amount\":15000,\"currency\":\"TZS\",\"billing.firstname\":\"Test\",\"billing.lastname\":\"Buyer\",\"billing.address_1\":\"1 Example Street\",\"billing.address_2\":\"\",\"billing.city\":\"Dar es Salaam\",\"billing.phone\":\"255700000000\",\"no_of_items\":1}" + } + }, + { + "id": "amount-as-integer", + "description": "Utility payment with the amount as a JSON integer. Compare with amount-as-string.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/utilitypayment/process", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "transid": "TXN-UTL-0001", + "utilitycode": "LUKU", + "utilityref": "01234567891", + "amount": 8000, + "vendor": "TILL123", + "pin": "0000", + "msisdn": "255700000000" + }, + "expected": { + "flattened": [ + ["transid", "TXN-UTL-0001"], + ["utilitycode", "LUKU"], + ["utilityref", "01234567891"], + ["amount", 8000], + ["vendor", "TILL123"], + ["pin", "0000"], + ["msisdn", "255700000000"] + ], + "signed_fields": "transid,utilitycode,utilityref,amount,vendor,pin,msisdn", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&transid=TXN-UTL-0001&utilitycode=LUKU&utilityref=01234567891&amount=8000&vendor=TILL123&pin=0000&msisdn=255700000000", + "digest": "eQj+J+hOefvjtKR7OyIf5FQFNaMkxfCJ8nPwL81tfFo=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"transid\":\"TXN-UTL-0001\",\"utilitycode\":\"LUKU\",\"utilityref\":\"01234567891\",\"amount\":8000,\"vendor\":\"TILL123\",\"pin\":\"0000\",\"msisdn\":\"255700000000\"}" + } + }, + { + "id": "amount-as-string", + "description": "The same payment with the amount as a string. Same signing string and digest; only the body differs.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/utilitypayment/process", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "transid": "TXN-UTL-0001", + "utilitycode": "LUKU", + "utilityref": "01234567891", + "amount": "8000", + "vendor": "TILL123", + "pin": "0000", + "msisdn": "255700000000" + }, + "expected": { + "flattened": [ + ["transid", "TXN-UTL-0001"], + ["utilitycode", "LUKU"], + ["utilityref", "01234567891"], + ["amount", "8000"], + ["vendor", "TILL123"], + ["pin", "0000"], + ["msisdn", "255700000000"] + ], + "signed_fields": "transid,utilitycode,utilityref,amount,vendor,pin,msisdn", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&transid=TXN-UTL-0001&utilitycode=LUKU&utilityref=01234567891&amount=8000&vendor=TILL123&pin=0000&msisdn=255700000000", + "digest": "eQj+J+hOefvjtKR7OyIf5FQFNaMkxfCJ8nPwL81tfFo=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"transid\":\"TXN-UTL-0001\",\"utilitycode\":\"LUKU\",\"utilityref\":\"01234567891\",\"amount\":\"8000\",\"vendor\":\"TILL123\",\"pin\":\"0000\",\"msisdn\":\"255700000000\"}" + } + }, + { + "id": "unicode-values", + "description": "Non-ASCII values, including a character outside the Basic Multilingual Plane. HMAC runs over UTF-8 bytes.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order-minimal", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1003", + "buyer_email": "test.buyer@example.com", + "buyer_name": "Tést Bùyer Ñandú", + "buyer_phone": "255700000001", + "amount": 5000, + "currency": "TZS", + "buyer_remarks": "Asante sana ☕ 🙂 日本", + "no_of_items": 1 + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1003"], + ["buyer_email", "test.buyer@example.com"], + ["buyer_name", "Tést Bùyer Ñandú"], + ["buyer_phone", "255700000001"], + ["amount", 5000], + ["currency", "TZS"], + ["buyer_remarks", "Asante sana ☕ 🙂 日本"], + ["no_of_items", 1] + ], + "signed_fields": "vendor,order_id,buyer_email,buyer_name,buyer_phone,amount,currency,buyer_remarks,no_of_items", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&vendor=TILL123&order_id=ORD-1003&buyer_email=test.buyer@example.com&buyer_name=Tést Bùyer Ñandú&buyer_phone=255700000001&amount=5000¤cy=TZS&buyer_remarks=Asante sana ☕ 🙂 日本&no_of_items=1", + "digest": "ET4tCWSqfeiWdhi4h18SUPZ8agaHK0w8U3NCJdCQJa0=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1003\",\"buyer_email\":\"test.buyer@example.com\",\"buyer_name\":\"Tést Bùyer Ñandú\",\"buyer_phone\":\"255700000001\",\"amount\":5000,\"currency\":\"TZS\",\"buyer_remarks\":\"Asante sana ☕ 🙂 日本\",\"no_of_items\":1}" + } + }, + { + "id": "reserved-characters-post", + "description": "Values with & = + space % / ? # in a JSON body. They go into the signing string raw, with no escaping.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order-minimal", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1004", + "buyer_email": "test.buyer@example.com", + "buyer_name": "Test Buyer", + "buyer_phone": "255700000001", + "amount": 1000, + "currency": "TZS", + "webhook": "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29rP29yZGVyPU9SRC0xMDA0JnNyYz10ZXN0", + "merchant_remarks": "a&b=c+d e%20f/g?h#i", + "no_of_items": 2 + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1004"], + ["buyer_email", "test.buyer@example.com"], + ["buyer_name", "Test Buyer"], + ["buyer_phone", "255700000001"], + ["amount", 1000], + ["currency", "TZS"], + ["webhook", "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29rP29yZGVyPU9SRC0xMDA0JnNyYz10ZXN0"], + ["merchant_remarks", "a&b=c+d e%20f/g?h#i"], + ["no_of_items", 2] + ], + "signed_fields": "vendor,order_id,buyer_email,buyer_name,buyer_phone,amount,currency,webhook,merchant_remarks,no_of_items", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&vendor=TILL123&order_id=ORD-1004&buyer_email=test.buyer@example.com&buyer_name=Test Buyer&buyer_phone=255700000001&amount=1000¤cy=TZS&webhook=aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29rP29yZGVyPU9SRC0xMDA0JnNyYz10ZXN0&merchant_remarks=a&b=c+d e%20f/g?h#i&no_of_items=2", + "digest": "XvcAJ9S9w7XqRpf773KupibnhV5MIK/myauOJqvH6nI=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1004\",\"buyer_email\":\"test.buyer@example.com\",\"buyer_name\":\"Test Buyer\",\"buyer_phone\":\"255700000001\",\"amount\":1000,\"currency\":\"TZS\",\"webhook\":\"aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29rP29yZGVyPU9SRC0xMDA0JnNyYz10ZXN0\",\"merchant_remarks\":\"a&b=c+d e%20f/g?h#i\",\"no_of_items\":2}" + } + }, + { + "id": "reserved-characters-get", + "description": "Reserved characters in a query value. The query string is percent-encoded (space is %20, plus is %2B); the signature covers the decoded value.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/utilitypayment/lookup", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "utilitycode": "LUKU", + "utilityref": "A&B=C+D E/F%G~H", + "transid": "TXN-LKP-0002" + }, + "expected": { + "flattened": [ + ["utilitycode", "LUKU"], + ["utilityref", "A&B=C+D E/F%G~H"], + ["transid", "TXN-LKP-0002"] + ], + "signed_fields": "utilitycode,utilityref,transid", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&utilitycode=LUKU&utilityref=A&B=C+D E/F%G~H&transid=TXN-LKP-0002", + "digest": "m8KyUwdkSqajdVVT3OQqTkeYncbc+INQ+owJI6w1+QI=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "utilitycode=LUKU&utilityref=A%26B%3DC%2BD%20E%2FF%25G~H&transid=TXN-LKP-0002" + } + }, + { + "id": "single-field-get", + "description": "Status query with one field.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/utilitypayment/query", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "transid": "TXN-UTL-0001" + }, + "expected": { + "flattened": [ + ["transid", "TXN-UTL-0001"] + ], + "signed_fields": "transid", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&transid=TXN-UTL-0001", + "digest": "BidQH4pxaE9ofF0FCVYbmkUqE6fcWo2Zd2wjyb/JjCw=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "transid=TXN-UTL-0001" + } + }, + { + "id": "long-field-list", + "description": "Full card checkout order: base64 URLs, billing and shipping objects, colours and expiry. Checks order over many fields.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "vendor": "TILL123", + "order_id": "ORD-1005", + "buyer_email": "test.buyer@example.com", + "buyer_name": "Test Buyer", + "buyer_userid": "test-user-0001", + "buyer_phone": "255700000001", + "gateway_buyer_uuid": "", + "amount": 125000, + "currency": "TZS", + "payment_methods": "ALL", + "redirect_url": "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NvbXBsZXRlP29yZGVyPU9SRC0xMDA1", + "cancel_url": "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NhbmNlbD9vcmRlcj1PUkQtMTAwNQ==", + "webhook": "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29r", + "billing": { + "firstname": "Test", + "lastname": "Buyer", + "address_1": "1 Example Street", + "address_2": "Unit 0", + "city": "Dar es Salaam", + "state_or_region": "Dar es Salaam", + "postcode_or_pobox": "00000", + "country": "TZ", + "phone": "255700000001" + }, + "shipping": { + "firstname": "Test", + "lastname": "Receiver", + "address_1": "2 Example Road", + "address_2": "", + "city": "Arusha", + "state_or_region": "Arusha", + "postcode_or_pobox": "00000", + "country": "TZ", + "phone": "255700000002" + }, + "buyer_remarks": "None", + "merchant_remarks": "Test order", + "no_of_items": 3, + "header_colour": "#FF0012", + "link_colour": "#0000FF", + "button_colour": "#00AA00", + "expiry": 60 + }, + "expected": { + "flattened": [ + ["vendor", "TILL123"], + ["order_id", "ORD-1005"], + ["buyer_email", "test.buyer@example.com"], + ["buyer_name", "Test Buyer"], + ["buyer_userid", "test-user-0001"], + ["buyer_phone", "255700000001"], + ["gateway_buyer_uuid", ""], + ["amount", 125000], + ["currency", "TZS"], + ["payment_methods", "ALL"], + ["redirect_url", "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NvbXBsZXRlP29yZGVyPU9SRC0xMDA1"], + ["cancel_url", "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NhbmNlbD9vcmRlcj1PUkQtMTAwNQ=="], + ["webhook", "aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29r"], + ["billing.firstname", "Test"], + ["billing.lastname", "Buyer"], + ["billing.address_1", "1 Example Street"], + ["billing.address_2", "Unit 0"], + ["billing.city", "Dar es Salaam"], + ["billing.state_or_region", "Dar es Salaam"], + ["billing.postcode_or_pobox", "00000"], + ["billing.country", "TZ"], + ["billing.phone", "255700000001"], + ["shipping.firstname", "Test"], + ["shipping.lastname", "Receiver"], + ["shipping.address_1", "2 Example Road"], + ["shipping.address_2", ""], + ["shipping.city", "Arusha"], + ["shipping.state_or_region", "Arusha"], + ["shipping.postcode_or_pobox", "00000"], + ["shipping.country", "TZ"], + ["shipping.phone", "255700000002"], + ["buyer_remarks", "None"], + ["merchant_remarks", "Test order"], + ["no_of_items", 3], + ["header_colour", "#FF0012"], + ["link_colour", "#0000FF"], + ["button_colour", "#00AA00"], + ["expiry", 60] + ], + "signed_fields": "vendor,order_id,buyer_email,buyer_name,buyer_userid,buyer_phone,gateway_buyer_uuid,amount,currency,payment_methods,redirect_url,cancel_url,webhook,billing.firstname,billing.lastname,billing.address_1,billing.address_2,billing.city,billing.state_or_region,billing.postcode_or_pobox,billing.country,billing.phone,shipping.firstname,shipping.lastname,shipping.address_1,shipping.address_2,shipping.city,shipping.state_or_region,shipping.postcode_or_pobox,shipping.country,shipping.phone,buyer_remarks,merchant_remarks,no_of_items,header_colour,link_colour,button_colour,expiry", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&vendor=TILL123&order_id=ORD-1005&buyer_email=test.buyer@example.com&buyer_name=Test Buyer&buyer_userid=test-user-0001&buyer_phone=255700000001&gateway_buyer_uuid=&amount=125000¤cy=TZS&payment_methods=ALL&redirect_url=aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NvbXBsZXRlP29yZGVyPU9SRC0xMDA1&cancel_url=aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NhbmNlbD9vcmRlcj1PUkQtMTAwNQ==&webhook=aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29r&billing.firstname=Test&billing.lastname=Buyer&billing.address_1=1 Example Street&billing.address_2=Unit 0&billing.city=Dar es Salaam&billing.state_or_region=Dar es Salaam&billing.postcode_or_pobox=00000&billing.country=TZ&billing.phone=255700000001&shipping.firstname=Test&shipping.lastname=Receiver&shipping.address_1=2 Example Road&shipping.address_2=&shipping.city=Arusha&shipping.state_or_region=Arusha&shipping.postcode_or_pobox=00000&shipping.country=TZ&shipping.phone=255700000002&buyer_remarks=None&merchant_remarks=Test order&no_of_items=3&header_colour=#FF0012&link_colour=#0000FF&button_colour=#00AA00&expiry=60", + "digest": "sz7igt6tLmjPV9l0d3nG2RKRNv8HuJLa4AB4XU1ozKU=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"vendor\":\"TILL123\",\"order_id\":\"ORD-1005\",\"buyer_email\":\"test.buyer@example.com\",\"buyer_name\":\"Test Buyer\",\"buyer_userid\":\"test-user-0001\",\"buyer_phone\":\"255700000001\",\"gateway_buyer_uuid\":\"\",\"amount\":125000,\"currency\":\"TZS\",\"payment_methods\":\"ALL\",\"redirect_url\":\"aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NvbXBsZXRlP29yZGVyPU9SRC0xMDA1\",\"cancel_url\":\"aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL2NoZWNrb3V0L2NhbmNlbD9vcmRlcj1PUkQtMTAwNQ==\",\"webhook\":\"aHR0cHM6Ly9zaG9wLmV4YW1wbGUuY29tL3NlbGNvbS93ZWJob29r\",\"billing.firstname\":\"Test\",\"billing.lastname\":\"Buyer\",\"billing.address_1\":\"1 Example Street\",\"billing.address_2\":\"Unit 0\",\"billing.city\":\"Dar es Salaam\",\"billing.state_or_region\":\"Dar es Salaam\",\"billing.postcode_or_pobox\":\"00000\",\"billing.country\":\"TZ\",\"billing.phone\":\"255700000001\",\"shipping.firstname\":\"Test\",\"shipping.lastname\":\"Receiver\",\"shipping.address_1\":\"2 Example Road\",\"shipping.address_2\":\"\",\"shipping.city\":\"Arusha\",\"shipping.state_or_region\":\"Arusha\",\"shipping.postcode_or_pobox\":\"00000\",\"shipping.country\":\"TZ\",\"shipping.phone\":\"255700000002\",\"buyer_remarks\":\"None\",\"merchant_remarks\":\"Test order\",\"no_of_items\":3,\"header_colour\":\"#FF0012\",\"link_colour\":\"#0000FF\",\"button_colour\":\"#00AA00\",\"expiry\":60}" + } + }, + { + "id": "other-key-and-utc-offset", + "description": "A different key and secret, and a +00:00 offset. Authorization changes with the key; the offset is signed exactly as sent.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/checkout/wallet-payment", + "timestamp": "2026-11-21T07:30:46+00:00", + "api_key": "test-key-0001", + "secret": "test-secret-0001", + "params": { + "transid": "TXN-WLT-0001", + "order_id": "ORD-1003", + "msisdn": "255700000001" + }, + "expected": { + "flattened": [ + ["transid", "TXN-WLT-0001"], + ["order_id", "ORD-1003"], + ["msisdn", "255700000001"] + ], + "signed_fields": "transid,order_id,msisdn", + "signing_string": "timestamp=2026-11-21T07:30:46+00:00&transid=TXN-WLT-0001&order_id=ORD-1003&msisdn=255700000001", + "digest": "WisVR30lWh0va5ZNwey0436fyjF43Qn5Hz9rOql1AdY=", + "authorization": "SELCOM dGVzdC1rZXktMDAwMQ==", + "digest_method": "HS256", + "body": "{\"transid\":\"TXN-WLT-0001\",\"order_id\":\"ORD-1003\",\"msisdn\":\"255700000001\"}" + } + }, + { + "id": "timestamp-offset-without-colon", + "description": "The basic offset form +0300 is accepted and signed exactly as sent. Its digest differs from the +03:00 form because the timestamp text differs.", + "known": false, + "scope": "request", + "method": "GET", + "path": "/v1/checkout/order-status", + "timestamp": "2026-11-21T10:30:46+0300", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "expected": { + "flattened": [ + ["order_id", "ORD-1001"] + ], + "signed_fields": "order_id", + "signing_string": "timestamp=2026-11-21T10:30:46+0300&order_id=ORD-1001", + "digest": "cCRaNeIicipMjU4W15BMrxutn3fxClPmCKnhkHz39sY=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "query": "order_id=ORD-1001" + } + }, + { + "id": "wallet-cashin-payout", + "description": "Wallet cash-in payout with a PIN. The PIN is signed like any other field and must never be logged.", + "known": false, + "scope": "request", + "method": "POST", + "path": "/v1/walletcashin/process", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "transid": "TXN-CSH-0001", + "utilitycode": "CASHIN", + "utilityref": "255700000002", + "amount": 2500, + "vendor": "TILL123", + "pin": "0000", + "msisdn": "255700000000" + }, + "expected": { + "flattened": [ + ["transid", "TXN-CSH-0001"], + ["utilitycode", "CASHIN"], + ["utilityref", "255700000002"], + ["amount", 2500], + ["vendor", "TILL123"], + ["pin", "0000"], + ["msisdn", "255700000000"] + ], + "signed_fields": "transid,utilitycode,utilityref,amount,vendor,pin,msisdn", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&transid=TXN-CSH-0001&utilitycode=CASHIN&utilityref=255700000002&amount=2500&vendor=TILL123&pin=0000&msisdn=255700000000", + "digest": "OjruOnfq8Ragkk3J7WhYcUhBjQP8W0F2Jb/PT6aJRrk=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"transid\":\"TXN-CSH-0001\",\"utilitycode\":\"CASHIN\",\"utilityref\":\"255700000002\",\"amount\":2500,\"vendor\":\"TILL123\",\"pin\":\"0000\",\"msisdn\":\"255700000000\"}" + } + }, + { + "id": "signer-booleans-negative-integral-float", + "description": "Signer-level test, not a real request: no v1 field takes these. Booleans sign as true/false, a negative integer keeps its sign, and 8000.0 signs and is sent as 8000.", + "known": false, + "scope": "signer", + "method": "POST", + "path": "/v1/signer-test", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "flag_on": true, + "flag_off": false, + "delta": -5, + "whole": 8000.0 + }, + "expected": { + "flattened": [ + ["flag_on", true], + ["flag_off", false], + ["delta", -5], + ["whole", 8000] + ], + "signed_fields": "flag_on,flag_off,delta,whole", + "signing_string": "timestamp=2026-11-21T10:30:46+03:00&flag_on=true&flag_off=false&delta=-5&whole=8000", + "digest": "QafCkl7gmMepIF5ThhOY4OyXMvcTqzNsEB+w/WLX+Yw=", + "authorization": "SELCOM MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=", + "digest_method": "HS256", + "body": "{\"flag_on\":true,\"flag_off\":false,\"delta\":-5,\"whole\":8000}" + } + } + ], + "rejects": [ + { + "id": "reject-empty-secret", + "description": "Fail closed: never produce or send an empty Digest.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "", + "params": { + "order_id": "ORD-1001" + }, + "error": "EMPTY_SECRET" + }, + { + "id": "reject-empty-api-key", + "description": "An empty key would send 'SELCOM ' with nothing after it.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "error": "EMPTY_API_KEY" + }, + { + "id": "reject-fractional-amount", + "description": "Amounts are whole shillings. Reject, never round or truncate.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001", + "amount": 8000.5 + }, + "error": "NON_INTEGER_NUMBER" + }, + { + "id": "reject-unsafe-integer", + "description": "Integers above 2^53-1 lose precision in JavaScript. Send them as strings.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001", + "amount": 9007199254740993 + }, + "error": "NUMBER_OUT_OF_RANGE" + }, + { + "id": "reject-array-value", + "description": "Arrays have no flat form. payment_methods is a comma-separated string, not a list.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001", + "payment_methods": [ + "CARD", + "MOBILEMONEYPULL" + ] + }, + "error": "UNSUPPORTED_TYPE" + }, + { + "id": "reject-key-with-comma", + "description": "A comma in a key would corrupt Signed-Fields.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order,id": "ORD-1001" + }, + "error": "INVALID_KEY" + }, + { + "id": "reject-duplicate-after-flattening", + "description": "billing.firstname given both flat and nested.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "billing.firstname": "Test", + "billing": { + "firstname": "Other" + } + }, + "error": "DUPLICATE_KEY" + }, + { + "id": "reject-empty-nested-object", + "description": "An empty object has no flat form. Omit it.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001", + "billing": {} + }, + "error": "EMPTY_OBJECT" + }, + { + "id": "reject-empty-params", + "description": "Every v1 operation sends at least one field. An empty Signed-Fields is never valid.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": {}, + "error": "EMPTY_PARAMS" + }, + { + "id": "reject-timestamp-z", + "description": "Use +00:00, not Z.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T07:30:46Z", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "error": "INVALID_TIMESTAMP" + }, + { + "id": "reject-timestamp-fractional-seconds", + "description": "No fractional seconds.", + "method": "POST", + "path": "/v1/checkout/create-order", + "timestamp": "2026-11-21T10:30:46.123+03:00", + "api_key": "202cb962ac59075b964b07152d234b70", + "secret": "81dc9bdb52d04dc20036dbd8313ed055", + "params": { + "order_id": "ORD-1001" + }, + "error": "INVALID_TIMESTAMP" + } + ] +}