PHP code example of codexoft / mpesa-sdk
1. Go to this page and download the library: Download codexoft/mpesa-sdk 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/ */
codexoft / mpesa-sdk example snippets
use codexoft\MpesaSdk\Mpesa;
$config = [
'env' => 'sandbox', // or 'production'
'credentials' => [
'passKey' => 'your-pass-key',
'initiatorPass' => 'your-initiator-pass',
'initiatorName' => 'your-initiator-name'
],
'appInfo' => [
'consumerKey' => 'your-consumer-key',
'consumerSecret' => 'your-consumer-secret'
],
'businessShortCode' => 'your-shortcode',
'shortCodeType' => 'paybill', // or 'till'
'requester' => 'your-requester-id'
];
$config = [
'env' => $_ENV['MPESA_ENV'],
'credentials' => [
'passKey' => $_ENV['MPESA_PASS_KEY'],
'initiatorPass' => $_ENV['MPESA_INITIATOR_PASS'],
'initiatorName' => $_ENV['MPESA_INITIATOR_NAME']
],
'appInfo' => [
'consumerKey' => $_ENV['MPESA_CONSUMER_KEY'],
'consumerSecret' => $_ENV['MPESA_CONSUMER_SECRET']
],
'businessShortCode' => $_ENV['MPESA_BUSINESS_SHORTCODE'],
'shortCodeType' => $_ENV['MPESA_SHORTCODE_TYPE'],
'requester' => $_ENV['MPESA_REQUESTER']
];
try {
$mpesa = new Mpesa($config);
} catch (InvalidArgumentException $e) {
// Handle configuration errors
log_error("Configuration Error: " . $e->getMessage());
} catch (Exception $e) {
// Handle other initialization errors
log_error("Initialization Error: " . $e->getMessage());
}
try {
$response = $mpesa->stkPush(
amount: 100,
phoneNumber: '254712345678',
accountNumber: 'INV001',
callBackUrl: 'https://example.com/callback',
description: 'Payment for Invoice 001'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->stkPushQuery(
checkoutRequestCode: 'ws_CO_123456789'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->generateQRCode(
amount: 100,
accountNumber: 'INV001',
size: 300 // Size in pixels
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->registerUrl(
responseType: 'Completed|Cancelled',
confirmationUrl: 'https://example.com/confirmation',
validationUrl: 'https://example.com/validation'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->initiateB2C(
amount: 100,
phoneNumber: '254712345678',
commandID: 'BusinessPayment|SalaryPayment|PromotionPayment', // or 'SalaryPayment', 'PromotionPayment'
resultUrl: 'https://example.com/b2c-result',
queueTimeoutUrl: 'https://example.com/b2c-timeout',
remarks: 'Salary Payment'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->initiateB2B(
amount: 1000,
paymentType: 'PaybillToPaybill|PaybillToTill|B2BAccountTopUp', // or 'PaybillToTill', 'B2BAccountTopUp'
shortCode: '600000',
accountNumber: 'ACC001',
resultUrl: 'https://example.com/b2b-result',
queueTimeoutUrl: 'https://example.com/b2b-timeout'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->initiateB2BExpressCheckout(
amount: 1000,
receiverShortCode: '600000',
callBackUrl: 'https://example.com/express-callback',
partnerName: 'Vendor Name',
paymentRef: 'PAY123', // optional
requestRef: 'REQ123' // optional
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->transactionStatus(
transactionID: 'SLU000000',
resultUrl: 'https://example.com/status-result',
queueTimeoutUrl: 'https://example.com/status-timeout'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->accountBalance(
resultUrl: 'https://example.com/balance-result',
queueTimeoutUrl: 'https://example.com/balance-timeout'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->reverseTransaction(
amount: 100,
transactionID: 'SLU000000',
resultUrl: 'https://example.com/reversal-result',
queueTimeoutUrl: 'https://example.com/reversal-timeout'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->taxRemittance(
amount: 1000,
paymentRegistrationNo: 'PRN12345',
resultUrl: 'https://example.com/tax-result',
queueTimeoutUrl: 'https://example.com/tax-timeout'
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
$response = $mpesa->mpesaRatiba(
amount: 1000,
phoneNumber: '254712345678',
accountReference: 'ACC001',
startDate: '2024-01-01',
endDate: '2024-12-31',
standingOrderName: 'Monthly Subscription',
callBackUrl: 'https://example.com/ratiba-callback',
frequency: '4' // Monthly
);
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
try {
// M-Pesa API call
} catch (InvalidArgumentException $e) {
// Handle validation errors
error_log("Validation error: " . $e->getMessage());
} catch (Exception $e) {
// Handle API errors
error_log("API error: " . $e->getMessage());
// Get HTTP status code if available
if (property_exists($e, 'httpCode')) {
error_log("HTTP Status: " . $e->httpCode);
}
}
// webhook.php
// Get the raw post data
$callbackData = file_get_contents('php://input');
// Validate JSON data
if (!$callbackJson = json_decode($callbackData, true)) {
header('HTTP/1.1 400 Bad Request');
exit('Invalid JSON');
}
// Log the callback
error_log("M-Pesa Callback: " . print_r($callbackJson, true));
// Process based on callback type
switch ($callbackJson['TransactionType'] ?? '') {
case 'Pay Bill':
// Handle C2B payment
processC2BPayment($callbackJson);
break;
case 'B2B Payment':
// Handle B2B payment
processB2BPayment($callbackJson);
break;
// Add other transaction types
}
// Respond to M-Pesa
header('Content-Type: application/json');
echo json_encode([
'ResultCode' => 0,
'ResultDesc' => 'Success'
]);
function processC2BPayment($data) {
// Implementation
}
function processB2BPayment($data) {
// Implementation
}
// All these will be formatted to 254712345678
$phoneNumber = '0712345678';
$phoneNumber = '712345678';
$phoneNumber = '254712345678';
$config['env'] = 'sandbox';
// Use sandbox credentials
$config['env'] = 'production';
// Use production credentials