createPayment([ * 'amount' => 5000, // TZS, whole shillings * 'customer' => ['phone' => '0712345678', 'name' => 'Asha Juma'], * 'reference' => 'ORDER-1001', // your own id; sending it again never charges twice * 'description' => 'School fees, term 1', * ]); * // $payment['status']: 'forwarded' = the customer has the prompt on their phone * * Or send the customer to a PigaPay payment page (hosted checkout): * $checkout = $pigapay->createCheckout([ * 'amount' => 5000, 'reference' => 'ORDER-1001', * 'success_url' => 'https://shop.example/paid', 'cancel_url' => 'https://shop.example/cart', * ]); * header('Location: ' . $checkout['url']); * * Receive the result (your webhook URL): * $event = PigaPay\Webhook::fromRequest(getenv('PIGAPAY_WEBHOOK_SECRET')); // throws when the signature is wrong * if ($event['event'] === 'payment.completed') { ... mark ORDER-1001 paid ... } * http_response_code(200); * * Balance, customers, withdrawals, bulk payouts and refunds (give the key those permissions in the dashboard): * $pigapay->balance()['available']; * $pigapay->createWithdrawal(['amount' => 50000, 'reference' => 'SETTLE-1']); // to the saved payout account * $pigapay->createPayout(['title' => 'Salaries', 'reference' => 'PAY-11', 'lines' => [['name' => 'Asha', 'phone' => '0712345678', 'amount' => 150000]]]); * $pigapay->createRefund(['payment' => 'ORDER-1001', 'amount' => 5000, 'reason' => 'Item out of stock']); // to the phone that paid * * Keep the API key and webhook secret on your server only (environment variable or a settings file outside * the web folder), never in JavaScript, a mobile app or a code repository. */ namespace PigaPay; class ApiException extends \Exception { /** @var int HTTP status (0 = no answer) */ public $status; /** @var string e.g. validation_failed, unauthorized, rate_limited */ public $errorCode; /** @var array field => problem, for validation_failed */ public $errors; /** @var string|null quote this when asking PigaPay support */ public $requestId; /** @var int|null seconds to wait (rate_limited, too_many_failed_attempts) */ public $retryAfter; public function __construct($message, $status = 0, $errorCode = 'error', array $errors = [], $requestId = null, $retryAfter = null) { parent::__construct($message, $status); $this->status = $status; $this->errorCode = $errorCode; $this->errors = $errors; $this->requestId = $requestId; $this->retryAfter = $retryAfter; } } class Client { const VERSION = '2.1.0'; private $apiKey; private $baseUrl; private $timeout; /** * @param string $apiKey pp_live_... or pp_test_... (PigaPay dashboard > API Keys) * @param array $options base_url (default https://pay.pigatech.com/api/v1), timeout (seconds, default 30) */ public function __construct($apiKey, array $options = []) { if (!is_string($apiKey) || !preg_match('/^(pp|pk)_(live|test)_[A-Za-z0-9]+$/', $apiKey)) { throw new \InvalidArgumentException('PigaPay: give the API key from your dashboard (pp_live_... or pp_test_...).'); } $this->apiKey = $apiKey; $this->baseUrl = rtrim($options['base_url'] ?? 'https://pay.pigatech.com/api/v1', '/'); $this->timeout = (int)($options['timeout'] ?? 30); } /** True for a test key: payments never reach a phone and no money moves */ public function isTestMode() { return strpos($this->apiKey, '_test_') !== false; } /** The key and account in use (good for checking a new setup) */ public function me() { return $this->request('GET', '/me'); } /** * Send a mobile money prompt to the customer's phone. * $params: amount (TZS), customer[phone, name, email], reference, description, webhook_url, metadata (array) */ public function createPayment(array $params) { return $this->request('POST', '/payments', $params); } /** One payment, by "pay_..." id or by your own reference */ public function getPayment($idOrReference) { return $this->request('GET', '/payments/' . rawurlencode($idOrReference)); } /** * A PigaPay payment page for the customer (hosted checkout). Send the customer to the returned 'url'; * they come back to success_url?checkout_id=...&reference=...&status=paid. Trust the webhook or * getCheckout(), not the return alone. * $params: amount (TZS), reference, description, success_url, cancel_url, customer[name, email, phone], * webhook_url, metadata (array), expires_in_minutes (5-1440, default 60) */ public function createCheckout(array $params) { return $this->request('POST', '/checkout', $params); } /** A checkout by "chk_..." id or your reference: status open, processing, paid, expired or cancelled */ public function getCheckout($idOrReference) { return $this->request('GET', '/checkout/' . rawurlencode($idOrReference)); } /** Your payments, newest first. $query: status, limit (max 100), offset */ public function listPayments(array $query = []) { return $this->request('GET', '/payments' . ($query ? '?' . http_build_query($query) : ''), null, true); } /** Available balance, money on hold and the withdrawal rules (permission balance:read) */ public function balance() { return $this->request('GET', '/balance'); } /** People who paid you, most paid first. $query: search, limit (max 100), offset (customers:read) */ public function listCustomers(array $query = []) { return $this->request('GET', '/customers' . ($query ? '?' . http_build_query($query) : ''), null, true); } /** One customer by phone number (0712..., 255712...) with their latest payments (customers:read) */ public function getCustomer($phone) { return $this->request('GET', '/customers/' . rawurlencode($phone)); } /** * Withdraw to the payout account saved in the PigaPay dashboard (withdrawals:write). * $params: amount (TZS), reference (your id: sending it again returns the same withdrawal), note */ public function createWithdrawal(array $params) { return $this->request('POST', '/withdrawals', $params); } /** A withdrawal by "WTH-..." id or your reference (payouts:read) */ public function getWithdrawal($idOrReference) { return $this->request('GET', '/withdrawals/' . rawurlencode($idOrReference)); } /** Your withdrawals, newest first. $query: status, limit (max 100), offset (payouts:read) */ public function listWithdrawals(array $query = []) { return $this->request('GET', '/withdrawals' . ($query ? '?' . http_build_query($query) : ''), null, true); } /** * Pay a list of people from your balance; PigaPay approves it first (payouts:write). * $params: title, reference, lines (each: name, phone, amount) */ public function createPayout(array $params) { return $this->request('POST', '/payouts', $params); } /** A bulk payout with its lines, by "BAT-..." id or your reference (payouts:read) */ public function getPayout($idOrReference) { return $this->request('GET', '/payouts/' . rawurlencode($idOrReference)); } /** * Give a customer money back for a completed payment; PigaPay approves it first (refunds:write). * $params: payment ("pay_..." id or its reference), amount (default: all that is left), reason, reference */ public function createRefund(array $params) { return $this->request('POST', '/refunds', $params); } /** A refund by "RFD-..." id or your reference (refunds:read) */ public function getRefund($idOrReference) { return $this->request('GET', '/refunds/' . rawurlencode($idOrReference)); } /** Your refunds, newest first. $query: payment, status, limit (max 100), offset (refunds:read) */ public function listRefunds(array $query = []) { return $this->request('GET', '/refunds' . ($query ? '?' . http_build_query($query) : ''), null, true); } /** Your bulk payouts, newest first. $query: limit (max 100), offset (payouts:read) */ public function listPayouts(array $query = []) { return $this->request('GET', '/payouts' . ($query ? '?' . http_build_query($query) : ''), null, true); } private function request($method, $path, ?array $body = null, $withPagination = false) { $headers = [ 'Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: PigaPay-PHP/' . self::VERSION, ]; $ch = curl_init($this->baseUrl . $path); $options = [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, ]; if ($body !== null) { $headers[] = 'Content-Type: application/json'; $options[CURLOPT_POSTFIELDS] = json_encode($body); } $options[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $options); $raw = curl_exec($ch); if ($raw === false) { $error = curl_error($ch); curl_close($ch); throw new ApiException('PigaPay could not be reached: ' . $error); } $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); $headerSize = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE); curl_close($ch); $responseHeaders = substr($raw, 0, $headerSize); $data = json_decode(substr($raw, $headerSize), true); if ($status >= 200 && $status < 300 && is_array($data) && !empty($data['success'])) { return $withPagination ? ['data' => $data['data'], 'pagination' => $data['pagination'] ?? null] : $data['data']; } $retryAfter = preg_match('/^Retry-After:\s*(\d+)/mi', $responseHeaders, $m) ? (int)$m[1] : null; throw new ApiException( $data['message'] ?? ('PigaPay answered HTTP ' . $status), $status, $data['error'] ?? 'error', $data['errors'] ?? [], $data['request_id'] ?? null, $retryAfter ); } } class Webhook { /** * Check a webhook and return the event. Throws \UnexpectedValueException when the signature is wrong * or the event is older than $tolerance seconds (an old event sent again by someone else). * * @param string $rawBody the body exactly as received (file_get_contents('php://input')) * @param string $signatureHeader the PigaPay-Signature header: "t=