daraja-openapi

PHP

A client for Safaricom's Daraja (M-PESA) API with no dependencies: just PHP 8.1+ with the curl, json and openssl extensions that every host has. Works in Laravel, Symfony, WordPress plugins and plain PHP. Built from the daraja-openapi spec and tested against its mock.

composer require bytegigs/daraja

STK Push

use ByteGigs\Daraja\Daraja;
use ByteGigs\Daraja\Callbacks;

$daraja = new Daraja(
    getenv('DARAJA_CONSUMER_KEY'),
    getenv('DARAJA_CONSUMER_SECRET'),
    environment: 'sandbox',
    shortCode: '174379',
    passkey: getenv('DARAJA_PASSKEY'),
);

$push = $daraja->stkPush(
    amount: 150,
    phone: '0712 345 678',          // any Kenyan format
    callbackUrl: 'https://your-app.example/daraja/callback',
    accountReference: 'INV-1001',
    description: 'Invoice 1001',
);

At your callback URL, read the result, then confirm it before delivering: Daraja callbacks are not signed.

$result = Callbacks::stk(file_get_contents('php://input'));
if ($result?->isPaid()) {
    $status = $daraja->stkQuery($result->checkoutRequestId);
    if ($status->isPaid()) {
        markPaid($result->receipt, $result->amount);
    }
}

waitForStkResult() polls instead, but it blocks the PHP process: use it in a queued job, not a web request.

Keep tokens between requests

PHP usually starts fresh for every request. Pass a TokenStore that uses your cache so you don't ask Daraja for a token each time:

final class LaravelTokenStore implements \ByteGigs\Daraja\TokenStore
{
    public function get(string $key): ?array { return Cache::get($key); }
    public function put(string $key, string $token, int $expiresAt): void
    {
        Cache::put($key, [$token, $expiresAt], $expiresAt - time());
    }
    public function forget(string $key): void { Cache::forget($key); }
}

$daraja = new Daraja($key, $secret, shortCode: '174379', passkey: $passkey,
                     tokenStore: new LaravelTokenStore());

Payouts and the other APIs

$daraja = new Daraja($key, $secret, shortCode: '600996',
    initiatorName: 'testapi',
    initiatorPassword: getenv('DARAJA_INITIATOR_PASSWORD'),
    certificate: file_get_contents('SandboxCertificate.cer'),
);

$daraja->b2cPayment(
    originatorConversationId: 'refund-order-77',   // reuse on retries
    amount: 150, phone: '0712345678', remarks: 'Refund order 77',
    resultUrl: 'https://your-app.example/daraja/result',
    timeoutUrl: 'https://your-app.example/daraja/timeout',
);

// At resultUrl:
$outcome = Callbacks::asyncResult(file_get_contents('php://input'));
if ($outcome?->ok) {
    echo $outcome->transactionId, ' ', $outcome->params['TransactionAmount'];
}

Also: c2bRegisterUrls, c2bSimulate, b2bPayment, reversal, transactionStatus, accountBalance (read with ->accountBalances()) and dynamicQr (returns PNG bytes). Callbacks::c2b() reads C2B confirmations.

Errors are DarajaException (status, errorCode, isPending(), isRateLimited(), isProductMissing()); bad input throws ValidationException before anything is sent. Secrets are marked #[SensitiveParameter] so they stay out of stack traces, and out of var_dump.

Tests

npm run build -w packages/mock   # from the repository root
php packages/php/tests/run.php

View the source of this page

Built by ByteGigs Labs. Apache 2.0. M-PESA, Daraja and Safaricom are trademarks of Safaricom PLC; this project is independent and not endorsed by Safaricom.