1. Go to this page and download the library: Download codenson/daraja-api library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
codenson / daraja-api example snippets
namespace App\Http\Controllers;
use Codenson\Daraja\Facades\Daraja;
use Codenson\Daraja\Exceptions\DarajaException;
class MpesaController extends Controller
{
//Get access token (auto-managed, but you can manually get it)
public function getToken()
{
try {
$token = Daraja::getAccessToken();
return response()->json(['token' => $token]);
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Load funds to B2C shortcode
public function topUpB2CAccount(Request $request)
{
try
{
$response = Daraja::b2cAccountTopUp()->topUp([
'amount' => 50000, // Amount to load
'reference' => 'TOPUP-001', // Reference
'remarks' => 'Monthly fund loading',
]);
return response()->json($response);
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Create standing order
public function createStandingOrder(Request $request)
{
try
{
$response = Daraja::mpesaRatiba()->create([
'amount' => 1000, // Amount per transaction
'phone_number' => '254712345678', // Customer phone
'start_date' => '2025-02-01', // Start date (Y-m-d)
'end_date' => '2025-12-31', // End date (Y-m-d)
'frequency' => 'MONTHLY', // DAILY, WEEKLY, MONTHLY
'day_of_month' => 15, // For monthly (1-31)
'day_of_week' => 'MON', // For weekly (MON, TUE, etc.)
'account_reference' => 'LOAN-001', // Reference
'remarks' => 'Loan repayment',
]);
return response()->json($response);
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Cancel standing order
public function cancelStandingOrder($orderId)
{
try
{
$response = Daraja::mpesaRatiba()->cancel($orderId);
return response()->json($response);
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Query standing order status
public function queryStandingOrder($orderId)
{
try
{
$response = Daraja::mpesaRatiba()->query($orderId);
return response()->json($response);
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Generate dynamic QR code
public function generateQRCode(Request $request)
{
try
{
$response = Daraja::dynamicQR()->generate([
'merchant_name' => 'My Store', // Merchant name
'ref_no' => 'INV-001', // Reference number
'amount' => 1500, // Amount
'trx_code' => 'BG', // BG=Buy Goods, PB=Paybill
'cpi' => '123456', // Till/Paybill number
'size' => '300', // QR size in pixels
]);
if ($response['ResponseCode'] === '0') {
return response()->json([
'qr_code' => $response['QRCode'], // Base64 encoded image
'response_description' => $response['ResponseDescription']
]);
}
} catch (DarajaException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Codenson\Daraja\Models\DarajaTransaction;
class MpesaCallbackController extends Controller
{
private function handleSuccessfulPayment($callback)
{
// Update order status
// Send email/SMS notification
// Generate receipt
// Trigger other business logic
}
}
# Run all tests
composer test
# Run specific test
./vendor/bin/phpunit tests/Unit/STKPushServiceTest.php
# Run with coverage
composer test-coverage
# Test API configuration (returns current config values)
Route::get('/mpesa/test-config', function () {
return [
'environment' => config('daraja.environment'),
'shortcode' => config('daraja.shortcode'),
'has_consumer_key' => !empty(config('daraja.consumer_key')),
'has_consumer_secret' => !empty(config('daraja.consumer_secret')),
'has_passkey' => !empty(config('daraja.passkey')),
'has_callback_urls' => !empty(config('daraja.callback_urls.stk_push')),
];
});
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.