PHP code example of mesasdk / php-mpesa

1. Go to this page and download the library: Download mesasdk/php-mpesa 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/ */

    

mesasdk / php-mpesa example snippets


use MesaSDK\PhpMpesa\Config;
use MesaSDK\PhpMpesa\Mpesa;
use MesaSDK\PhpMpesa\Exceptions\MpesaException;

// Initialize configuration
$config = new Config();
$config->setBaseUrl("https://apisandbox.safaricom.et")
    ->setEnvironment('sandbox')  // Use 'production' for live environment
    ->setConsumerKey('your_consumer_key')
    ->setConsumerSecret('your_consumer_secret')
    ->setShortCode('your_shortcode')
    ->setPassKey('your_passkey')
    ->setVerifySSL(true);  // Always true in production

// Create M-Pesa instance
$mpesa = new Mpesa($config);

try {
    $response = $mpesa->authenticate()
        ->setC2BAmount(110.00)
        ->setC2BMsisdn('251945628580')
        ->setC2BBillRefNumber('091091')
        ->executeC2BSimulation();

    if ($response->isSuccessful()) {
        echo "Transaction initiated successfully!";
        echo "Response Code: " . $response->getResponseCode();
        echo "Conversation ID: " . $response->getConversationId();
    }
} catch (MpesaException $e) {
    echo "Error: " . $e->getMessage();
}

$config = new Config();
$config->setBaseUrl("https://apisandbox.safaricom.et")  // Add base URL
    ->setEnvironment($_ENV['MPESA_ENVIRONMENT'])
    ->setConsumerKey($_ENV['MPESA_CONSUMER_KEY'])
    ->setConsumerSecret($_ENV['MPESA_CONSUMER_SECRET'])
    ->setShortCode($_ENV['MPESA_SHORTCODE'])
    ->setPassKey($_ENV['MPESA_PASS_KEY'])
    ->setVerifySSL(true);  // Set to false only for sandbox testing

try {
    $mpesa->authenticate()
        ->setPhoneNumber('2517XXXXXXXX')
        ->setAmount(100)
        ->setAccountReference('INV' . time())   // Dynamic reference
        ->setTransactionDesc('Payment for Package')
        ->setCallbackUrl('https://your-domain.com/callback');

    // For sandbox testing only
    if ($config->getEnvironment() === 'sandbox') {
        $mpesa->setTestPassword('your-test-password');
    }

    $response = $mpesa->ussdPush();

    if ($mpesa->isSuccessful()) {
        echo "Transaction Details:\n";
        echo "Merchant Request ID: " . $mpesa->getMerchantRequestID() . "\n";
        echo "Checkout Request ID: " . $mpesa->getCheckoutRequestID() . "\n";
    }
} catch (MpesaException $e) {
    echo "M-Pesa Error: " . $e->getMessage();
}

try {
    $result = $mpesa->authenticate()
        ->setInitiatorName('your_initiator')
        ->setSecurityCredential('your_security_credential')
        ->setCommandId('BusinessPayment')  // Options: SalaryPayment, BusinessPayment, PromotionPayment
        ->setAmount(100)
        ->setPartyA('your_shortcode')
        ->setPartyB('2517XXXXXXXX')
        ->setRemarks('Payment description')
        ->setOccasion('Optional reference')
        ->setQueueTimeOutUrl('https://your-domain.com/timeout')
        ->setResultUrl('https://your-domain.com/result')
        ->b2c();

    if ($result && $result->getResponseMessage()) {
        echo "B2C payment initiated successfully!";
        // Store conversation IDs for reconciliation
        $conversationId = $result->getConversationId();
        $originatorConversationId = $result->getOriginatorConversationId();
    }
} catch (MpesaException $e) {
    echo "Error: " . $e->getMessage();
}

use MesaSDK\PhpMpesa\Models\C2BSimulationResponse;

try {
    /** @var C2BSimulationResponse $response */
    $response = $mpesa->authenticate()
        ->setC2BAmount(110.00)
        ->setC2BMsisdn('251945628580')
        ->setC2BBillRefNumber('091091')
        ->executeC2BSimulation();

    if ($response->isSuccessful()) {
        echo "C2B payment simulation initiated successfully!";
        echo "Response Code: " . $response->getResponseCode();
        echo "Conversation ID: " . $response->getConversationId();
        echo "Customer Message: " . $response->getCustomerMessage();
    } else {
        echo "C2B payment simulation failed: " . $response->getResponseDescription();
    }
} catch (MpesaException $e) {
    echo "Error: " . $e->getMessage();
}

try {
    $response = $mpesa->authenticate()
        ->setSecurityCredential("your-security-credential")
        ->setAccountBalanceInitiator('your_initiator')
        ->setAccountBalancePartyA('your_shortcode')
        ->setAccountBalanceRemarks('Balance check')
        ->setAccountBalanceIdentifierType('4')
        ->setQueueTimeOutUrl('https://your-domain.com/timeout')
        ->setResultUrl('https://your-domain.com/result')
        ->checkAccountBalance();

    // Handle immediate response
    if ($response['ResponseCode'] === '0') {
        echo "Balance query initiated successfully";
    }

    // If this is a result callback
    if (isset($response['Result'])) {
        $balanceInfo = $mpesa->parseBalanceResult($response);
        foreach ($balanceInfo as $account) {
            echo sprintf(
                "Account: %s\nCurrency: %s\nAmount: %s\n",
                $account['account'],
                $account['currency'],
                $account['amount']
            );
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

$response = $mpesa->authenticate()
    ->registerUrls(
        'https://your-domain.com/mpesa/confirm',
        'https://your-domain.com/mpesa/validate'
    );


{
    // Get the callback data
    $callbackData = file_get_contents('php://input');
    $callback = json_decode($callbackData, true);

    // Validate and process the callback
    if (isset($callback['Body']['stkCallback'])) {
        $resultCode = $callback['Body']['stkCallback']['ResultCode'];
        $resultDesc = $callback['Body']['stkCallback']['ResultDesc'];

        if ($resultCode === 0) {
            // Payment successful
            $amount = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][0]['Value'];
            $mpesaReceiptNumber = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value'];
            $transactionDate = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][3]['Value'];
            $phoneNumber = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value'];

            // Store transaction details in your database
            // Update order status
            // Send confirmation to customer

            // Return success response
            http_response_code(200);
            echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Success']);
        } else {
            // Payment failed
            error_log("Payment failed: " . $resultDesc);
            // Handle the error (notify customer, update order status, etc.)
        }
    }
} catch (Exception $e) {
    error_log("Callback Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error']);
}

// In your confirmation endpoint handler
try {
    $request = json_decode(file_get_contents('php://input'), true);
    $response = $mpesa->handleConfirmation($request);

    // Store transaction details
    $transactionId = $response->getTransactionId();
    $amount = $response->getAmount();
    $phoneNumber = $response->getPhoneNumber();

    header('Content-Type: application/json');
    echo json_encode($response);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

/** @var C2BSimulationResponse $response */
$response = $mpesa->executeC2BSimulation();

if ($response->isSuccessful()) {
    // Type-safe access to response data
    $conversationId = $response->getConversationId();
    $merchantRequestId = $response->getMerchantRequestId();
    $checkoutRequestId = $response->getCheckoutRequestId();

    // Convert to array if needed
    $responseArray = $response->toArray();
}



{
    // Get the callback data
    $callbackData = file_get_contents('php://input');
    $callback = json_decode($callbackData, true);

    // Validate and process the callback
    if (isset($callback['Body']['stkCallback'])) {
        $resultCode = $callback['Body']['stkCallback']['ResultCode'];
        $resultDesc = $callback['Body']['stkCallback']['ResultDesc'];

        if ($resultCode === 0) {
            // Payment successful
            $amount = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][0]['Value'];
            $mpesaReceiptNumber = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value'];
            $transactionDate = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][3]['Value'];
            $phoneNumber = $callback['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value'];

            // Store transaction details in your database
            // Update order status
            // Send confirmation to customer

            // Return success response
            http_response_code(200);
            echo json_encode(['ResultCode' => 0, 'ResultDesc' => 'Success']);
        } else {
            // Payment failed
            error_log("Payment failed: " . $resultDesc);
            // Handle the error (notify customer, update order status, etc.)
        }
    }
} catch (Exception $e) {
    error_log("Callback Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error']);
}

use MesaSDK\PhpMpesa\Exceptions\MpesaException;
use MesaSDK\PhpMpesa\Exceptions\ConfigurationException;
use MesaSDK\PhpMpesa\Exceptions\ValidationException;

try {
    $response = $mpesa->authenticate()
        ->setPhoneNumber('2517XXXXXXXX')
        ->setAmount(100)
        ->ussdPush();
} catch (ConfigurationException $e) {
    // Handle configuration errors (invalid credentials, missing _log("M-Pesa Error: " . $e->getMessage());
    error_log("Error Code: " . $e->getCode());
    echo "Transaction failed. Please try again later.";
} catch (Exception $e) {
    // Handle unexpected errors
    error_log("Unexpected Error: " . $e->getMessage());
    echo "An unexpected error occurred.";
}

use MesaSDK\PhpMpesa\Logging\Logger;

// Configure custom logging
$logger = new Logger();

// Set custom log path
$logger->setLogPath('/path/to/your/logs');

// Enable debug logging
$logger->setDebug(true);

// Add logger to M-Pesa instance
$mpesa->setLogger($logger);

// Logs will now 

$response->isSuccessful();                    // Check if request was successful
$response->getResponseCode();                 // Get response code
$response->getResponseDescription();          // Get response description
$response->getConversationId();              // Get conversation ID
$response->getOriginatorConversationId();    // Get originator conversation ID
$response->toArray();                        // Convert response to array

/** @var C2BSimulationResponse $response */
$response = $mpesa
    ->setC2BAmount(110.00)
    ->setC2BMsisdn('251945628580')
    ->setC2BBillRefNumber('091091')
    ->executeC2BSimulation();

if ($response->isSuccessful()) {
    $customerMessage = $response->getCustomerMessage();
    $merchantRequestId = $response->getMerchantRequestId();
    $checkoutRequestId = $response->getCheckoutRequestId();
}

/** @var C2BValidationResponse $response */
$response = $mpesa->handleValidation($request);

$thirdPartyTransId = $response->getThirdPartyTransId();
$transactionDetails = $response->getTransactionDetails();
$specificDetail = $response->getTransactionDetail('key', 'default');

use MesaSDK\PhpMpesa\Models\C2BSimulationResponse;

/** @var C2BSimulationResponse $response */
$response = $mpesa->executeC2BSimulation();

if ($response->isSuccessful()) {
    // All these methods provide type-safe access to response data
    $conversationId = $response->getConversationId();
    $merchantRequestId = $response->getMerchantRequestId();
    $checkoutRequestId = $response->getCheckoutRequestId();

    // Convert to array if needed
    $responseArray = $response->toArray();
}


try {
    $response = $mpesa->authenticate()
        ->setSecurityCredential("your-security-credential")
        ->setAccountBalanceInitiator('apitest')
        ->setAccountBalancePartyA('1020')
        ->setAccountBalanceRemarks('Monthly balance check')
        // Optional parameters
        ->setAccountBalanceIdentifierType('4')
        ->setQueueTimeOutUrl('https://your-domain.com/timeout')
        ->setResultUrl('https://your-domain.com/result')
        ->checkAccountBalance();

    // Handle successful response
    if (isset($response['Result'])) {
        $balanceInfo = $mpesa->parseBalanceResult($response);
        foreach ($balanceInfo as $account) {
            echo sprintf(
                "Account: %s\nCurrency: %s\nAmount: %s\n\n",
                $account['account'],
                $account['currency'],
                $account['amount']
            );
        }
    }
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}
bash
composer