reason = $reason; } } } namespace Moolre { /** What every API call returns. `raw` is the untouched response JSON (as an array). */ final class Result { /** @var bool status === 1 (the API sends 1, "1", 0 or "0" depending on the endpoint) */ public $ok; /** @var int|string */ public $status; /** @var string */ public $code; /** @var mixed */ public $message; /** @var mixed */ public $data; /** @var mixed */ public $go; /** @var string|null */ public $requestId; /** @var array[] */ public $notices; /** @var bool True when an Idempotency-Key matched an earlier request and the stored response was replayed */ public $replayed; /** @var int */ public $httpStatus; /** @var array */ public $raw; public function __construct(array $raw, int $httpStatus, ?string $headerRequestId) { $this->raw = $raw; $this->httpStatus = $httpStatus; $this->status = $raw['status'] ?? (($httpStatus >= 200 && $httpStatus < 300) ? 1 : 0); $this->ok = (string) $this->status === '1'; $this->code = isset($raw['code']) ? (string) $raw['code'] : ''; $this->message = $raw['message'] ?? null; $this->data = $raw['data'] ?? null; $this->go = $raw['go'] ?? null; // Request id: meta.requestid, else legacy top-level request_id, else the X-Request-Id header. // Notices: meta.notices, else legacy top-level notices, else []. $meta = isset($raw['meta']) && is_array($raw['meta']) ? $raw['meta'] : []; $rid = isset($meta['requestid']) && is_string($meta['requestid']) ? $meta['requestid'] : null; if ($rid === null && isset($raw['request_id']) && is_string($raw['request_id'])) { $rid = $raw['request_id']; } $this->requestId = $rid !== null ? $rid : $headerRequestId; if (isset($meta['notices']) && is_array($meta['notices'])) { $this->notices = $meta['notices']; } else { $this->notices = isset($raw['notices']) && is_array($raw['notices']) ? $raw['notices'] : []; } $this->replayed = ($meta['replayed'] ?? false) === true || ($raw['replayed'] ?? false) === true; } /** Collection answered TP14: ask the customer for the SMS code and call verifyOtp(). */ public function otpRequired(): bool { return $this->code === 'TP14'; } /** Collection answered TP17: the number is verified; call initiate() again without otpCode. */ public function otpVerified(): bool { return $this->code === 'TP17'; } } } namespace Moolre\Exceptions { use Moolre\Result; /** The API answered status 0 (or a 4xx/5xx in strict mode). */ class ApiError extends MoolreException { /** @var string Moolre application code, e.g. TP13 */ public $apiCode; /** @var string */ public $apiMessage; /** @var string[] Names of the request fields the API complained about */ public $fields; /** @var string|null */ public $requestId; /** @var int */ public $httpStatus; /** @var array */ public $notices; /** @var Result */ public $result; public function __construct(Result $result) { $message = is_array($result->message) ? implode(' ', array_filter($result->message, 'is_scalar')) : (string) ($result->message ?? ''); parent::__construct($result->code . ': ' . $message, $result->httpStatus); $this->apiCode = $result->code; $this->apiMessage = $message; $this->fields = self::fieldsOf($result->data); $this->requestId = $result->requestId; $this->httpStatus = $result->httpStatus; $this->notices = $result->notices; $this->result = $result; } /** @param mixed $data */ private static function fieldsOf($data): array { if (is_string($data) && $data !== '' && $data !== 'all') { return [$data]; } if (is_array($data)) { return array_values(array_filter($data, 'is_string')); } return []; } public static function fromResult(Result $result): self { $http = $result->httpStatus; if ($result->code === 'IDEM01' || $http === 409) { return new IdempotencyError($result); } if ($result->code === 'OTP429' || $http === 429) { return new RateLimitError($result); } if ($http === 401 || in_array($result->code, ['AIN01', 'AIN03', 'IN01', 'SW05'], true)) { return new AuthenticationError($result); } if ($http === 404) { return new NotFoundError($result); } if ($http === 400 || $http === 422) { return new ValidationError($result); } if ($http >= 500) { return new ServerError($result); } return new self($result); } } } namespace Moolre\Exceptions { /** AIN01, AIN03, IN01, SW05 or HTTP 401. */ class AuthenticationError extends ApiError { } } namespace Moolre\Exceptions { /** HTTP 404 in strict mode. */ class NotFoundError extends ApiError { } } namespace Moolre\Exceptions { /** HTTP 400 or 422 in strict mode. */ class ValidationError extends ApiError { } } namespace Moolre\Exceptions { /** IDEM01 or HTTP 409: Idempotency-Key reused with a different request. */ class IdempotencyError extends ApiError { } } namespace Moolre\Exceptions { /** OTP429 or HTTP 429. */ class RateLimitError extends ApiError { } } namespace Moolre\Exceptions { /** HTTP 5xx with a Moolre JSON body. */ class ServerError extends ApiError { } } namespace Moolre { use Moolre\Exceptions\ApiError; use Moolre\Exceptions\ConfigurationError; use Moolre\Exceptions\InvalidResponseError; use Moolre\Exceptions\NetworkError; /** * HTTP layer of the server SDK (curl + json only). * * @internal Use Moolre\Moolre. */ final class Transport { public const VERSION = '1.1.2'; public const LIVE_URL = 'https://api.moolre.com'; public const SANDBOX_URL = 'https://sandbox.moolre.com'; /** @var array */ public $opts; /** @var string */ public $baseUrl; /** @var array */ private $seenNotices = []; /** @param array $opts */ public function __construct(array $opts) { $env = $opts['environment'] ?? 'live'; if ($env !== 'live' && $env !== 'sandbox') { throw new ConfigurationError('environment must be "live" or "sandbox"'); } if (!function_exists('curl_init')) { throw new ConfigurationError('The curl extension is required.'); } $this->opts = $opts; $this->baseUrl = rtrim((string) ($opts['baseUrl'] ?? ($env === 'live' ? self::LIVE_URL : self::SANDBOX_URL)), '/'); } /** * @param array $body * @param array{method?: string, query?: array, retry?: string, idempotencyKey?: ?string, needs?: string[]} $o */ public function call(string $path, array $body = [], array $o = []): Result { $opts = $this->opts; if (empty($opts['user'])) { throw new ConfigurationError('`user` (X-API-USER) is required'); } $needs = $o['needs'] ?? []; if ($needs !== []) { $has = false; foreach ($needs as $n) { if (!empty($opts[$n])) { $has = true; } } if (!$has) { throw new ConfigurationError('This call needs one of: ' . implode(', ', $needs)); } } $method = $o['method'] ?? 'POST'; $key = $o['idempotencyKey'] ?? null; if ($key !== null && preg_match('/^[\x20-\x7e]{1,128}$/D', $key) !== 1) { throw new ConfigurationError('idempotencyKey must be 1-128 printable ASCII characters'); } $url = $this->baseUrl . $path; $query = self::clean($o['query'] ?? []); if ($query !== []) { $url .= '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986); } $headers = ['Accept: application/json', 'User-Agent: moolre-php/' . self::VERSION, 'X-API-USER: ' . $opts['user']]; foreach (['apiKey' => 'X-API-KEY', 'pubKey' => 'X-API-PUBKEY', 'vasKey' => 'X-API-VASKEY'] as $k => $h) { if (!empty($opts[$k])) { $headers[] = $h . ': ' . $opts[$k]; } } if (!empty($opts['strictHttpStatus'])) { $headers[] = 'X-Moolre-Http-Status: strict'; } if ($key !== null) { $headers[] = 'Idempotency-Key: ' . $key; } $payload = null; if ($method === 'POST') { $headers[] = 'Content-Type: application/json'; $clean = self::clean($body); $payload = $clean === [] ? '{}' : json_encode($clean, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($payload === false) { throw new ConfigurationError('Request body could not be encoded as JSON: ' . json_last_error_msg()); } } $retry = $o['retry'] ?? 'never'; $retryable = $retry === 'read' || ($retry === 'idempotent' && $key !== null); $maxRetries = $retryable ? (int) ($opts['maxRetries'] ?? 2) : 0; for ($attempt = 0;; $attempt++) { [$status, $text, $reqId, $err] = $this->send($url, $method, $headers, $payload); if ($err !== null) { if ($attempt < $maxRetries) { $this->sleep($attempt); continue; } throw $err; } if ($status >= 500 && $attempt < $maxRetries) { $this->sleep($attempt); continue; } $parsed = json_decode($text, true); if (!is_array($parsed) || ($parsed !== [] && array_keys($parsed) === range(0, count($parsed) - 1))) { throw new InvalidResponseError(sprintf('Moolre returned a non-JSON response (HTTP %d): %s', $status, substr($text, 0, 200)), $status); } $result = new Result($parsed, $status, $reqId); $this->logNotices($result); if (!$result->ok && ($opts['throwOnError'] ?? true)) { throw ApiError::fromResult($result); } return $result; } } /** @return array{0:int,1:string,2:?string,3:?NetworkError} */ private function send(string $url, string $method, array $headers, ?string $payload): array { $ch = curl_init($url); $reqId = null; $opts = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_TIMEOUT => (int) ceil((float) ($this->opts['timeoutSec'] ?? 60)), CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_HEADERFUNCTION => static function ($c, string $line) use (&$reqId): int { if (stripos($line, 'x-request-id:') === 0) { $reqId = trim(substr($line, 13)); } return strlen($line); }, ]; if ($payload !== null) { $opts[CURLOPT_POSTFIELDS] = $payload; } if (!empty($this->opts['caFile'])) { $opts[CURLOPT_CAINFO] = $this->opts['caFile']; } curl_setopt_array($ch, $opts); $body = curl_exec($ch); $errno = curl_errno($ch); $error = curl_error($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($body === false || $errno !== 0) { $msg = $errno === 28 ? 'timed out' : 'failed'; return [0, '', null, new NetworkError(sprintf('Request to %s %s: %s', parse_url($url, PHP_URL_PATH), $msg, $error))]; } return [$status, (string) $body, $reqId, null]; } private function sleep(int $attempt): void { $base = (int) ($this->opts['retryDelayMs'] ?? 500); usleep((int) ($base * (2 ** $attempt) * (0.75 + mt_rand(0, 500) / 1000) * 1000)); } private function logNotices(Result $result): void { $logger = array_key_exists('logger', $this->opts) ? $this->opts['logger'] : 'default'; if ($logger === null || $logger === false) { return; } foreach ($result->notices as $n) { $code = is_array($n) ? (string) ($n['code'] ?? '') : ''; if (isset($this->seenNotices[$code])) { continue; } $this->seenNotices[$code] = true; $docs = is_array($n) && !empty($n['docs']) ? ' (' . $n['docs'] . ')' : ''; $msg = '[moolre] ' . $code . ': ' . (is_array($n) ? (string) ($n['message'] ?? '') : '') . $docs; if (is_callable($logger)) { $logger($msg, ['requestId' => $result->requestId, 'notice' => $n]); } else { error_log($msg); } } } /** * Drop null values (top level). * * @param array $a * @return array */ public static function clean(array $a): array { return array_filter($a, static function ($v) { return $v !== null; }); } /** @param int|float|string $a */ public static function amount($a): string { return (is_int($a) || is_float($a)) ? number_format((float) $a, 2, '.', '') : (string) $a; } /** @param int|string $c */ public static function channel($c): string { $s = trim((string) $c); $u = strtoupper($s); return in_array($u, ['MTN', 'TELECEL', 'AT', 'BANK'], true) ? $u : $s; } } } namespace Moolre { /** A parsed webhook payload. */ final class WebhookEvent { /** @var string|null "evt_" + 24 hex, stable across retries: dedupe on this (null on legacy payloads) */ public $eventId; /** @var string|null payment.succeeded | payment.failed | payout.succeeded | payout.failed | payment_link.expired | bulk_payout.completed | invoice.paid | invoice.expired | webhook.test */ public $event; /** @var string|null ISO 8601 UTC with Z */ public $created; /** @var int|string|null */ public $status; /** @var string|null */ public $code; /** @var mixed */ public $message; /** @var mixed */ public $data; /** @var array[] */ public $notices; /** @var array */ public $raw; public function __construct(array $raw) { $this->raw = $raw; $this->eventId = isset($raw['event_id']) ? (string) $raw['event_id'] : null; $this->event = isset($raw['event']) ? (string) $raw['event'] : null; $this->created = isset($raw['created']) ? (string) $raw['created'] : null; $this->status = $raw['status'] ?? null; $this->code = isset($raw['code']) ? (string) $raw['code'] : null; $this->message = $raw['message'] ?? null; $this->data = $raw['data'] ?? null; $meta = isset($raw['meta']) && is_array($raw['meta']) ? $raw['meta'] : []; if (isset($meta['notices']) && is_array($meta['notices'])) { $this->notices = $meta['notices']; } else { $this->notices = isset($raw['notices']) && is_array($raw['notices']) ? $raw['notices'] : []; } } } } namespace Moolre { use Moolre\Exceptions\WebhookSignatureError; /** * Webhook signature helpers (Contract W). * * X-Moolre-Signature: t=,v1=.")> * * Always pass the RAW request body (file_get_contents('php://input')), never re-encoded JSON. */ final class Webhook { /** Returns null when valid, otherwise 'malformed' | 'mismatch' | 'timestamp'. */ public static function check(string $rawBody, ?string $signatureHeader, string $secret, int $toleranceSec = 300, ?int $now = null): ?string { if ($signatureHeader === null || $signatureHeader === '' || $secret === '') { return 'malformed'; } $t = null; $sigs = []; foreach (explode(',', $signatureHeader) as $part) { $i = strpos($part, '='); if ($i === false) { continue; } $k = trim(substr($part, 0, $i)); $v = trim(substr($part, $i + 1)); if ($k === 't' && $t === null) { $t = $v; } elseif ($k === 'v1') { $sigs[] = $v; } } if ($t === null || preg_match('/^[0-9]{1,15}$/D', $t) !== 1) { return 'malformed'; } $valid = []; foreach ($sigs as $s) { if (preg_match('/^[0-9a-fA-F]{64}$/D', $s) === 1) { $valid[] = $s; } } if ($valid === []) { return 'malformed'; } $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret, true); $match = false; foreach ($valid as $s) { if (hash_equals($expected, (string) hex2bin($s))) { $match = true; } } if (!$match) { return 'mismatch'; } $current = $now ?? time(); if ($toleranceSec > 0 && abs($current - (int) $t) > $toleranceSec) { return 'timestamp'; } return null; } public static function verify(string $rawBody, ?string $signatureHeader, string $secret, int $toleranceSec = 300, ?int $now = null): bool { return self::check($rawBody, $signatureHeader, $secret, $toleranceSec, $now) === null; } /** Parse a webhook body. Does not verify anything. */ public static function parse(string $rawBody): WebhookEvent { $raw = json_decode($rawBody, true); if (!is_array($raw) || ($raw !== [] && array_keys($raw) === range(0, count($raw) - 1))) { throw new WebhookSignatureError('malformed', 'Webhook body is not a JSON object'); } return new WebhookEvent($raw); } /** Verify then parse; throws WebhookSignatureError (reason: malformed | mismatch | timestamp). */ public static function construct(string $rawBody, ?string $signatureHeader, string $secret, int $toleranceSec = 300, ?int $now = null): WebhookEvent { $failure = self::check($rawBody, $signatureHeader, $secret, $toleranceSec, $now); if ($failure !== null) { throw new WebhookSignatureError($failure, 'Invalid Moolre webhook signature (' . $failure . ')'); } return self::parse($rawBody); } /** Test helper: build a header the way Moolre signs. */ public static function sign(string $rawBody, string $secret, ?int $now = null): string { $t = $now ?? time(); return 't=' . $t . ',v1=' . hash_hmac('sha256', $t . '.' . $rawBody, $secret); } } } namespace Moolre\Api { use Moolre\Exceptions\ConfigurationError; use Moolre\Transport; /** @internal */ abstract class Resource { /** @var Transport */ protected $t; public function __construct(Transport $t) { $this->t = $t; } /** @param array $p */ protected function account(array $p): string { $a = $p['accountNumber'] ?? ($this->t->opts['accountNumber'] ?? null); if ($a === null || $a === '') { throw new ConfigurationError('accountNumber is required (pass it to the call or to the client)'); } return (string) $a; } /** * @param array $p * @param string[] $keys */ protected function need(array $p, array $keys): void { foreach ($keys as $k) { if (!isset($p[$k]) || $p[$k] === '') { throw new ConfigurationError(sprintf('Missing required parameter "%s"', $k)); } } } /** * @param array $p * @return array{idtype:int,id:string} */ protected function lookup(array $p): array { if (isset($p['externalRef'])) { return ['idtype' => 1, 'id' => (string) $p['externalRef']]; } if (isset($p['transactionId'])) { return ['idtype' => 2, 'id' => (string) $p['transactionId']]; } throw new ConfigurationError('Pass externalRef or transactionId'); } /** @param array $o */ protected function key(array $o): ?string { return isset($o['idempotencyKey']) ? (string) $o['idempotencyKey'] : null; } } } namespace Moolre\Api { use Moolre\Result; use Moolre\Transport; /** Mobile money collections, Payment IDs and bank collection accounts. */ final class Payments extends Resource { /** * Request a mobile money payment. When the customer's number needs verifying the API answers TP14 * ($result->otpRequired()): ask for the SMS code and call verifyOtp(). On TP17 call initiate() again * without otpCode. * * @param array{channel:string,currency:string,payer:string,amount:mixed,externalRef:string,reference?:string,otpCode?:string,sessionId?:string,skipOtp?:bool,accountNumber?:string} $p * @param array{idempotencyKey?:string} $o */ public function initiate(array $p, array $o = []): Result { $this->need($p, ['channel', 'currency', 'payer', 'amount', 'externalRef']); return $this->t->call('/open/transact/payment', [ 'type' => 1, 'channel' => Transport::channel($p['channel']), 'currency' => $p['currency'], 'payer' => $p['payer'], 'amount' => Transport::amount($p['amount']), 'externalref' => $p['externalRef'], 'reference' => $p['reference'] ?? null, 'otpcode' => $p['otpCode'] ?? null, 'sessionid' => $p['sessionId'] ?? null, 'accountnumber' => $this->account($p), 'skipotp' => $p['skipOtp'] ?? null, ], ['needs' => ['pubKey'], 'retry' => 'idempotent', 'idempotencyKey' => $this->key($o)]); } /** Second step of the OTP flow: initiate() with otpCode. */ public function verifyOtp(array $p, array $o = []): Result { $this->need($p, ['otpCode']); return $this->initiate($p, $o); } /** Status by ['externalRef' => ...] or ['transactionId' => ...]. */ public function status(array $p): Result { return $this->t->call('/open/transact/status', ['type' => 1, 'accountnumber' => $this->account($p)] + $this->lookup($p), ['needs' => ['apiKey', 'pubKey'], 'retry' => 'read']); } public function createPaymentId(array $p): Result { $this->need($p, ['phone', 'name', 'currency', 'externalRef']); return $this->t->call('/open/account/create', [ 'type' => 2, 'phone' => $p['phone'], 'name' => $p['name'], 'currency' => $p['currency'], 'amount' => isset($p['amount']) ? Transport::amount($p['amount']) : null, 'externalref' => $p['externalRef'], 'accountnumber' => $this->account($p), ], ['needs' => ['pubKey']]); } public function createBankAccount(array $p): Result { $this->need($p, ['currency', 'firstName', 'lastName', 'phone', 'email', 'externalRef']); return $this->t->call('/open/account/create', [ 'type' => 9, 'currency' => $p['currency'], 'amount' => isset($p['amount']) ? (float) $p['amount'] : null, 'firstname' => $p['firstName'], 'lastname' => $p['lastName'], 'phone' => $p['phone'], 'email' => $p['email'], 'externalref' => $p['externalRef'], 'accountnumber' => $this->account($p), ], ['needs' => ['pubKey']]); } public function listBankAccounts(array $p = []): Result { return $this->t->call('/open/transact/status', ['type' => 3, 'accountnumber' => $this->account($p)], ['needs' => ['pubKey'], 'retry' => 'read']); } /** Payments received on a Payment ID or bank account, and its status. */ public function accountTransactions(string $externalRef, array $p = []): Result { return $this->t->call('/open/transact/status', ['type' => 2, 'externalref' => $externalRef, 'accountnumber' => $this->account($p)], ['needs' => ['pubKey'], 'retry' => 'read']); } } } namespace Moolre\Api { use Moolre\Result; use Moolre\Transport; final class PaymentLinks extends Resource { /** * @param array{amount:mixed,email:string,externalRef:string,currency:string,callback?:string,redirect?:string,reusable?:bool,expirationTime?:int,metadata?:array,accountNumber?:string} $p */ public function create(array $p): Result { $this->need($p, ['amount', 'email', 'externalRef', 'currency']); return $this->t->call('/embed/link', [ 'type' => 1, 'amount' => Transport::amount($p['amount']), 'email' => $p['email'], 'externalref' => $p['externalRef'], 'callback' => $p['callback'] ?? null, 'redirect' => $p['redirect'] ?? null, 'reusable' => !empty($p['reusable']) ? '1' : '0', 'expiration_time' => $p['expirationTime'] ?? null, 'currency' => $p['currency'], 'accountnumber' => $this->account($p), 'metadata' => $p['metadata'] ?? null, ], ['needs' => ['pubKey']]); } } } namespace Moolre\Api { use Moolre\Result; use Moolre\Transport; /** Payouts, name validation and internal transfers. */ final class Transfers extends Resource { /** * Pay out to a mobile money wallet or bank account (channel MTN | TELECEL | AT | BANK). * Pass ['idempotencyKey' => ...] to make retries safe. * * @param array{channel:string,currency:string,amount:mixed,receiver:string,externalRef:string,subListId?:string,reference?:string,senderName?:string,accountNumber?:string} $p * @param array{idempotencyKey?:string} $o */ public function create(array $p, array $o = []): Result { $this->need($p, ['channel', 'currency', 'amount', 'receiver', 'externalRef']); return $this->t->call('/open/transact/transfer', [ 'type' => 1, 'channel' => Transport::channel($p['channel']), 'currency' => $p['currency'], 'amount' => Transport::amount($p['amount']), 'receiver' => $p['receiver'], 'sublistid' => $p['subListId'] ?? null, 'externalref' => $p['externalRef'], 'reference' => $p['reference'] ?? null, 'sendername' => $p['senderName'] ?? null, 'accountnumber' => $this->account($p), ], ['needs' => ['apiKey'], 'retry' => 'idempotent', 'idempotencyKey' => $this->key($o)]); } public function status(array $p): Result { return $this->t->call('/open/transact/status', ['type' => 1, 'accountnumber' => $this->account($p)] + $this->lookup($p), ['needs' => ['apiKey', 'pubKey'], 'retry' => 'read']); } /** Confirm the account holder's name before paying out. */ public function validateName(array $p): Result { $this->need($p, ['channel', 'currency', 'receiver']); $name = Transport::channel($p['channel']); // /open/transact/validate currently reads the numeric channel ids only. $legacy = ['MTN' => '1', 'TELECEL' => '6', 'AT' => '7', 'BANK' => '2']; return $this->t->call('/open/transact/validate', [ 'type' => 1, 'receiver' => $p['receiver'], 'channel' => $legacy[$name] ?? $name, 'sublistid' => $p['subListId'] ?? null, 'currency' => $p['currency'], 'accountnumber' => $this->account($p), ], ['needs' => ['apiKey', 'pubKey'], 'retry' => 'read']); } /** Move money between two Moolre accounts (receiver is an account number, not a phone number). */ public function internal(array $p): Result { $this->need($p, ['currency', 'amount', 'receiver', 'externalRef']); return $this->t->call('/open/transact/internal', [ 'type' => 1, 'currency' => $p['currency'], 'amount' => Transport::amount($p['amount']), 'receiver' => $p['receiver'], 'externalref' => $p['externalRef'], 'reference' => $p['reference'] ?? null, 'accountnumber' => $this->account($p), ], ['needs' => ['apiKey']]); } } } namespace Moolre\Api { use Generator; use Moolre\Result; final class Accounts extends Resource { public function status(array $p = []): Result { return $this->t->call('/open/account/status', ['type' => 1, 'accountnumber' => $this->account($p)], ['needs' => ['apiKey'], 'retry' => 'read']); } /** @param array{accountName?:string,currency?:string,api?:bool,callback?:string,settlement?:array,accountNumber?:string} $p */ public function update(array $p): Result { return $this->t->call('/open/account/update', [ 'type' => 1, 'accountnumber' => $this->account($p), 'accountname' => $p['accountName'] ?? null, 'currency' => $p['currency'] ?? 'GHS', 'api' => $p['api'] ?? null, 'callback' => $p['callback'] ?? null, 'settlement' => $p['settlement'] ?? null, ], ['needs' => ['apiKey']]); } /** Sandbox only: create a test wallet. */ public function create(array $p): Result { $this->need($p, ['accountName', 'callback']); $cur = $p['currency'] ?? 'GHS'; return $this->t->call('/open/account/create', [ 'type' => 1, 'accountname' => $p['accountName'], 'currency' => $cur, 'api' => $p['api'] ?? null, 'callback' => $p['callback'], 'settlement' => $p['settlement'] ?? ['currency' => $cur, 'frequency' => '', 'channel' => '', 'recipient' => '', 'sublist' => ''], ]); } /** * One page of transactions. * * @param array{startDate?:string,endDate?:string,status?:int,limit?:int,descending?:bool,startId?:mixed,endId?:mixed,accountNumber?:string} $p */ public function transactions(array $p = []): Result { return $this->t->call('/open/account/status', [ 'type' => 2, 'accountnumber' => $this->account($p), 'startdate' => $p['startDate'] ?? null, 'enddate' => $p['endDate'] ?? null, 'limit' => $p['limit'] ?? null, 'status' => $p['status'] ?? null, 'descending' => isset($p['descending']) ? ($p['descending'] ? 1 : 0) : null, 'startid' => $p['startId'] ?? null, 'endid' => $p['endId'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** * Iterate every matching transaction with the id cursor (startid/endid): pages never overlap. * Newest first unless ['descending' => false]. Options: pageSize (default 100, max 1000), maxItems. * * @return Generator */ public function iterateTransactions(array $p = [], array $page = []): Generator { $size = min(max((int) ($page['pageSize'] ?? 100), 2), 1000); $max = $page['maxItems'] ?? null; $desc = ($p['descending'] ?? true) !== false; $startId = isset($p['startId']) ? (int) $p['startId'] : null; $endId = isset($p['endId']) ? (int) $p['endId'] : null; $seen = 0; while (true) { $r = $this->transactions(['descending' => $desc, 'limit' => $size, 'startId' => $startId, 'endId' => $endId] + $p); $rows = is_array($r->data) && isset($r->data['transactions']) && is_array($r->data['transactions']) ? $r->data['transactions'] : []; foreach ($rows as $row) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $row; } if (count($rows) < $size) { return; } $ids = []; foreach ($rows as $row) { if (isset($row['transactionid']) && ctype_digit((string) $row['transactionid'])) { $ids[] = (int) $row['transactionid']; } } if ($ids === []) { return; } if ($desc) { $endId = min($ids) - 1; if ($endId <= 1) { // the API needs endid > 1 return; } } else { $startId = max($ids) + 1; } } } } } namespace Moolre\Api { use Moolre\Result; use Moolre\Transport; /** Airtime and data bundle sales (wallet must be linked to Sell on Our Platform). */ final class Sales extends Resource { /** @param array{channel:string,receiver:string,amount:mixed,externalRef:string,reference?:string,accountNumber?:string} $p */ public function airtime(array $p): Result { $this->need($p, ['channel', 'receiver', 'amount', 'externalRef']); return $this->t->call('/open/sales/airtime', [ 'type' => 1, 'channel' => Transport::channel($p['channel']), 'receiver' => $p['receiver'], 'amount' => Transport::amount($p['amount']), 'currency' => 'GHS', 'accountnumber' => $this->account($p), 'externalref' => $p['externalRef'], 'reference' => $p['reference'] ?? null, ], ['needs' => ['apiKey']]); } /** @param array{channel:string,receiver:string,bundle:string,externalRef:string,reference?:string,accountNumber?:string} $p */ public function data(array $p): Result { $this->need($p, ['channel', 'receiver', 'bundle', 'externalRef']); return $this->t->call('/open/sales/data', [ 'type' => 1, 'channel' => Transport::channel($p['channel']), 'receiver' => $p['receiver'], 'bundle' => $p['bundle'], 'currency' => 'GHS', 'accountnumber' => $this->account($p), 'externalref' => $p['externalRef'], 'reference' => $p['reference'] ?? null, ], ['needs' => ['apiKey']]); } /** @param array{network?:string,accountNumber?:string} $p */ public function bundles(array $p = []): Result { return $this->t->call('/open/sales/bundles', [ 'accountnumber' => $this->account($p), 'network' => isset($p['network']) ? Transport::channel($p['network']) : null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** Look up by ['externalRef'], ['transactionId'] or ['reference']. */ public function status(array $p): Result { $look = isset($p['reference']) ? ['idtype' => 3, 'id' => (string) $p['reference']] : $this->lookup($p); return $this->t->call('/open/sales/status', ['type' => 1, 'accountnumber' => $this->account($p)] + $look, ['needs' => ['apiKey'], 'retry' => 'read']); } } } namespace Moolre\Api { use Moolre\Result; /** SMS (needs vasKey). */ final class Sms extends Resource { /** * @param array{senderId:string,messages:array,network?:string} $p */ public function send(array $p): Result { $this->need($p, ['senderId', 'messages']); return $this->t->call('/open/sms/send', [ 'type' => 1, 'senderid' => $p['senderId'], 'network' => $p['network'] ?? null, 'messages' => $p['messages'], ], ['needs' => ['vasKey']]); } /** Delivery status by message ref: 0 unknown, 1 sent, 2 delivered, 3 failed. */ public function status(array $refs): Result { return $this->t->call('/open/sms/status', ['type' => 5, 'ref' => array_values($refs)], ['needs' => ['vasKey'], 'retry' => 'read']); } public function balance(): Result { return $this->t->call('/open/sms/status', ['type' => 2], ['needs' => ['vasKey'], 'retry' => 'read']); } public function senderIdStatus(string $senderId): Result { return $this->t->call('/open/sms/status', ['type' => 1, 'senderid' => $senderId], ['needs' => ['vasKey'], 'retry' => 'read']); } public function listSenderIds(): Result { return $this->t->call('/open/sms/status', ['type' => 7], ['needs' => ['vasKey'], 'retry' => 'read']); } /** @param array $senderIds */ public function createSenderIds(array $senderIds): Result { return $this->t->call('/open/sms/query', ['type' => 3, 'senderids' => $senderIds], ['needs' => ['vasKey']]); } /** Reseller permission required. approve: 0 pending, 1 approved, 2 rejected. */ public function approveSenderIds(array $senderIds): Result { return $this->t->call('/open/sms/status', ['type' => 6, 'senderids' => $senderIds], ['needs' => ['vasKey']]); } } } namespace Moolre\Api { use Generator; use Moolre\Result; /** WhatsApp template messages (needs vasKey). */ final class WhatsApp extends Resource { /** One page of approved templates; $next is the cursor from the previous page ($result->raw['next']). */ public function templates(?string $next = null): Result { return $this->t->call('/open/whatsapp/template', [], ['method' => 'GET', 'query' => ['next' => $next], 'needs' => ['vasKey'], 'retry' => 'read']); } /** @return Generator */ public function iterateTemplates(array $page = []): Generator { $max = $page['maxItems'] ?? null; $next = null; $seen = 0; do { $r = $this->templates($next); foreach (is_array($r->data) ? $r->data : [] as $t) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $t; } $n = $r->raw['next'] ?? null; $next = is_string($n) && $n !== '' ? $n : null; } while ($next !== null); } /** @param array{templateName:string,language:string,messages:array} $p */ public function send(array $p): Result { $this->need($p, ['templateName', 'language', 'messages']); return $this->t->call('/open/whatsapp/send', [ 'template_name' => $p['templateName'], 'language' => $p['language'], 'messages' => $p['messages'], ], ['needs' => ['vasKey']]); } public function status(array $refs): Result { return $this->t->call('/open/whatsapp/status', ['ref' => array_values($refs)], ['needs' => ['vasKey'], 'retry' => 'read']); } } } namespace Moolre\Api { use Moolre\Result; final class Reference extends Resource { /** Supported banks and their codes (use as subListId). */ public function banks(string $country = 'gha'): Result { return $this->t->call('/open/transact/data', [], [ 'method' => 'GET', 'query' => ['country' => $country, 'data' => 'banks'], 'needs' => ['apiKey', 'pubKey'], 'retry' => 'read', ]); } } } namespace Moolre\Api { use Generator; use Moolre\Result; use Moolre\Transport; /** Bulk payouts: up to 500 payouts per batch, sent by a background worker. */ final class Bulk extends Resource { /** * Submit 1 to 500 payouts. Each item: externalRef, receiver, channel (MTN|TELECEL|AT|BANK|GHQR), amount, * subListId? (BANK), senderName? (1-40 chars), reference?. The result's data holds batchid, batchref, * accepted, rejected[{index,code,message,externalref}], total_amount, status "queued", balance_warning?. * The same batchRef with the same body replays the batch (code BLK02, replayed true). * * @param array{currency:string,batchRef:string,items:array,callback?:string,atomic?:bool,accountNumber?:string} $p * @param array{idempotencyKey?:string} $o */ public function create(array $p, array $o = []): Result { $this->need($p, ['currency', 'batchRef', 'items']); $items = []; foreach ($p['items'] as $i) { $items[] = Transport::clean([ 'externalref' => $i['externalRef'] ?? null, 'receiver' => $i['receiver'] ?? null, 'channel' => isset($i['channel']) ? Transport::channel($i['channel']) : null, 'amount' => isset($i['amount']) ? Transport::amount($i['amount']) : null, 'sublistid' => $i['subListId'] ?? null, 'sendername' => $i['senderName'] ?? null, 'reference' => $i['reference'] ?? null, ]); } return $this->t->call('/open/transact/bulk', [ 'type' => 1, 'accountnumber' => $this->account($p), 'currency' => $p['currency'], 'batchref' => $p['batchRef'], 'callback' => $p['callback'] ?? null, 'atomic' => $p['atomic'] ?? null, 'items' => $items, ], ['needs' => ['apiKey'], 'retry' => 'idempotent', 'idempotencyKey' => $this->key($o)]); } /** * Batch summary plus one page of items. Use iterateItems() to walk them all. * * @param array{batchId?:string,batchRef?:string,status?:string,after?:int,limit?:int,accountNumber?:string} $p */ public function status(array $p): Result { return $this->t->call('/open/transact/bulk_status', [ 'accountnumber' => $this->account($p), 'batchid' => $p['batchId'] ?? null, 'batchref' => $p['batchRef'] ?? null, 'status' => $p['status'] ?? null, 'after' => $p['after'] ?? null, 'limit' => $p['limit'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** * Walk every item of a batch (follows data.next_after). * * @return Generator */ public function iterateItems(array $p, array $page = []): Generator { $size = min(max((int) ($page['pageSize'] ?? 100), 1), 500); $max = $page['maxItems'] ?? null; $after = null; $seen = 0; while (true) { $r = $this->status(['after' => $after, 'limit' => $size] + $p); $d = is_array($r->data) ? $r->data : []; foreach ($d['items'] ?? [] as $item) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $item; } if (!isset($d['next_after'])) { return; } $after = (int) $d['next_after']; } } /** * Recent batches, newest first. data = {batches, has_more, next_cursor}. * * @param array{limit?:int,startingAfter?:string,status?:string,accountNumber?:string} $p */ public function list(array $p = []): Result { return $this->t->call('/open/transact/bulk_list', [ 'accountnumber' => $this->account($p), 'limit' => $p['limit'] ?? null, 'starting_after' => $p['startingAfter'] ?? null, 'status' => $p['status'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** @return Generator */ public function iterateBatches(array $p = [], array $page = []): Generator { $max = $page['maxItems'] ?? null; $after = null; $seen = 0; while (true) { $r = $this->list(['limit' => min((int) ($page['pageSize'] ?? 25), 100), 'startingAfter' => $after] + $p); $d = is_array($r->data) ? $r->data : []; foreach ($d['batches'] ?? [] as $b) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $b; } if (empty($d['has_more']) || empty($d['next_cursor'])) { return; } $after = (string) $d['next_cursor']; } } } } namespace Moolre\Api { use Generator; use Moolre\Result; use Moolre\Transport; /** Invoices: the same invoices the dashboard shows. */ final class Invoices extends Resource { /** * Create an invoice; give the customer $result->data['payment_link']. The same reference with the same body * replays the original (code INV02, replayed true). * * @param array{currency:string,invoiceName:string,customer:array{name:string,phone?:string,email?:string},dueDate:string,amount?:mixed,items?:array,tax?:int|float,narration?:string,reference?:string,metadata?:array,serviceId?:string,accountNumber?:string} $p * @param array{idempotencyKey?:string} $o */ public function create(array $p, array $o = []): Result { $this->need($p, ['currency', 'invoiceName', 'customer', 'dueDate']); $lines = null; if (isset($p['items'])) { $lines = []; foreach ($p['items'] as $i) { $lines[] = Transport::clean([ 'description' => $i['description'] ?? null, 'quantity' => $i['quantity'] ?? null, 'amount' => isset($i['amount']) ? Transport::amount($i['amount']) : null, ]); } } return $this->t->call('/open/invoice/create', [ 'accountnumber' => $this->account($p), 'currency' => $p['currency'], 'service_id' => $p['serviceId'] ?? null, 'invoice_name' => $p['invoiceName'], 'customer' => $p['customer'], 'amount' => isset($p['amount']) ? Transport::amount($p['amount']) : null, 'items' => $lines, 'tax' => $p['tax'] ?? null, 'due_date' => $p['dueDate'], 'narration' => $p['narration'] ?? null, 'reference' => $p['reference'] ?? null, 'metadata' => $p['metadata'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'idempotent', 'idempotencyKey' => $this->key($o)]); } /** By ['invoiceId' => '5-1'] or ['reference' => '...']. */ public function status(array $p): Result { return $this->t->call('/open/invoice/status', [ 'accountnumber' => $this->account($p), 'invoiceid' => $p['invoiceId'] ?? null, 'reference' => $p['reference'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** data = {invoices, has_more, next_cursor}, newest first. */ public function list(array $p = []): Result { return $this->t->call('/open/invoice/list', [ 'accountnumber' => $this->account($p), 'limit' => $p['limit'] ?? null, 'starting_after' => $p['startingAfter'] ?? null, 'status' => $p['status'] ?? null, 'reference' => $p['reference'] ?? null, 'service_id' => $p['serviceId'] ?? null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** @return Generator */ public function iterate(array $p = [], array $page = []): Generator { $max = $page['maxItems'] ?? null; $after = null; $seen = 0; while (true) { $r = $this->list(['limit' => min((int) ($page['pageSize'] ?? 25), 100), 'startingAfter' => $after] + $p); $d = is_array($r->data) ? $r->data : []; foreach ($d['invoices'] ?? [] as $inv) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $inv; } if (empty($d['has_more']) || empty($d['next_cursor'])) { return; } $after = (string) $d['next_cursor']; } } /** Cancel an unpaid invoice (its hosted link stops working). INV18 if it has payments. */ public function cancel(string $invoiceId, array $p = []): Result { return $this->t->call('/open/invoice/cancel', ['accountnumber' => $this->account($p), 'invoiceid' => $invoiceId], ['needs' => ['apiKey']]); } } } namespace Moolre\Api { use Generator; use Moolre\Result; use Moolre\Webhook; use Moolre\WebhookEvent; /** Webhook deliveries, resend and test events. */ final class Webhooks extends Resource { /** * Webhooks Moolre has sent (or is retrying), newest first. data = {items, has_more, next_cursor}. * * @param array{event?:string,state?:string,from?:string,to?:string,limit?:int,startingAfter?:string,includePayload?:bool,accountNumber?:string} $p */ public function deliveries(array $p = []): Result { return $this->t->call('/open/webhook/deliveries', [ 'accountnumber' => $this->account($p), 'event' => $p['event'] ?? null, 'state' => $p['state'] ?? null, 'from' => $p['from'] ?? null, 'to' => $p['to'] ?? null, 'limit' => $p['limit'] ?? null, 'starting_after' => $p['startingAfter'] ?? null, 'include_payload' => !empty($p['includePayload']) ? 1 : null, ], ['needs' => ['apiKey'], 'retry' => 'read']); } /** * Walk all deliveries (follows data.next_cursor). * * @return Generator */ public function iterateDeliveries(array $p = [], array $page = []): Generator { $max = $page['maxItems'] ?? null; $after = $p['startingAfter'] ?? null; $seen = 0; while (true) { $r = $this->deliveries(['limit' => min((int) ($page['pageSize'] ?? 25), 100), 'startingAfter' => $after] + $p); $d = is_array($r->data) ? $r->data : []; foreach ($d['items'] ?? [] as $row) { if ($max !== null && $seen >= $max) { return; } $seen++; yield $row; } if (empty($d['has_more']) || empty($d['next_cursor'])) { return; } $after = (string) $d['next_cursor']; } } /** Put an event back in the delivery queue (same event_id, full retry schedule). */ public function resend(string $eventId, array $p = []): Result { return $this->t->call('/open/webhook/resend', ['accountnumber' => $this->account($p), 'event_id' => $eventId], ['needs' => ['apiKey']]); } /** Send a signed `webhook.test` event to the wallet's callback URL now. data = {event_id, delivered, http, error}. */ public function test(array $p = []): Result { return $this->t->call('/open/webhook/test', ['accountnumber' => $this->account($p)], ['needs' => ['apiKey']]); } public function verify(string $rawBody, ?string $signatureHeader, string $secret, int $toleranceSec = 300): bool { return Webhook::verify($rawBody, $signatureHeader, $secret, $toleranceSec); } public function construct(string $rawBody, ?string $signatureHeader, string $secret, int $toleranceSec = 300): WebhookEvent { return Webhook::construct($rawBody, $signatureHeader, $secret, $toleranceSec); } } } namespace Moolre { use Moolre\Api\Accounts; use Moolre\Api\Bulk; use Moolre\Api\Invoices; use Moolre\Api\PaymentLinks; use Moolre\Api\Payments; use Moolre\Api\Reference; use Moolre\Api\Sales; use Moolre\Api\Sms; use Moolre\Api\Transfers; use Moolre\Api\Webhooks; use Moolre\Api\WhatsApp; /** * Moolre server SDK client (separate from the hosted-checkout Moolre\Client). * * Options: environment ('live'|'sandbox'), baseUrl, user, apiKey, pubKey, vasKey, accountNumber, * strictHttpStatus (bool), throwOnError (bool, default true), maxRetries (default 2), retryDelayMs, * timeoutSec (default 60), logger (callable(string $message, array $context) | null), caFile. */ final class Moolre { /** @var Payments */ public $payments; /** @var PaymentLinks */ public $paymentLinks; /** @var Transfers */ public $transfers; /** @var Accounts */ public $accounts; /** @var Sales */ public $sales; /** @var Sms */ public $sms; /** @var WhatsApp */ public $whatsapp; /** @var Reference */ public $reference; /** @var Bulk */ public $bulk; /** @var Invoices */ public $invoices; /** @var Webhooks */ public $webhooks; /** @param array $options */ public function __construct(array $options) { $t = new Transport($options); $this->payments = new Payments($t); $this->paymentLinks = new PaymentLinks($t); $this->transfers = new Transfers($t); $this->accounts = new Accounts($t); $this->sales = new Sales($t); $this->sms = new Sms($t); $this->whatsapp = new WhatsApp($t); $this->reference = new Reference($t); $this->bulk = new Bulk($t); $this->invoices = new Invoices($t); $this->webhooks = new Webhooks($t); } /** Build from MOOLRE_ENV, MOOLRE_USER, MOOLRE_API_KEY, MOOLRE_PUBKEY, MOOLRE_VASKEY, MOOLRE_ACCOUNT. */ public static function fromEnv(array $overrides = []): self { return new self($overrides + [ 'environment' => getenv('MOOLRE_ENV') === 'sandbox' ? 'sandbox' : 'live', 'user' => getenv('MOOLRE_USER') ?: null, 'apiKey' => getenv('MOOLRE_API_KEY') ?: null, 'pubKey' => getenv('MOOLRE_PUBKEY') ?: null, 'vasKey' => getenv('MOOLRE_VASKEY') ?: null, 'accountNumber' => getenv('MOOLRE_ACCOUNT') ?: null, ]); } /** A random Idempotency-Key (UUID v4). Store it with your order and reuse it when retrying. */ public static function newIdempotencyKey(): string { $b = random_bytes(16); $b[6] = chr((ord($b[6]) & 0x0f) | 0x40); $b[8] = chr((ord($b[8]) & 0x3f) | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4)); } } }