Sample MPESA B2C PHP Code for Using Daraja API

Sample 1

Here is a sample of the code you might use to create a simple Mpesa B2C (business-to-customer) payment using the Daraja API in PHP. This code demonstrates how to initiate a B2C payment request and check the status of the payment using the Daraja API. Note that this is just a basic example and you will need to add additional error handling and other code to make it fully functional.

This code first generates an access token by making a request to the OAuth API.

				
					<?php // Set your consumer key and secret
$consumerKey = 'your_consumer_key';
$consumerSecret = 'your_consumer_secret';

// Set the B2C payment details
$initiatorName = 'testapi';
$securityCredential = 'your_security_credential';
$commandId = 'BusinessPayment';
$amount = '1000';
$partyA = 'your_shortcode';
$partyB = '254700000000'; // Phone number of the customer
$remarks = 'Sample B2C payment';
$queueTimeOutURL = 'https://example.com/timeout';
$resultURL = 'https://example.com/result';

// Get the access token
$authenticationUrl = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init($authenticationUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($consumerKey.':'.$consumerSecret)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$curl_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = json_decode($curl_response);
$accessToken = $result->access_token;

// Set the B2C request parameters
$url = 'https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$accessToken));

$curl_post_data = array(
    'InitiatorName' => $initiatorName,
    'SecurityCredential' => $securityCredential,
    'CommandID' => $commandId,
    'Amount' => $amount,
    'PartyA' => $partyA,
    'PartyB' => $partyB,
    'Remarks' => $remarks,
    'QueueTimeOutURL' => $queueTimeOutURL,
    'ResultURL' => $resultURL
);

$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

$curl_response = curl_exec($curl);
print_r($curl_response);


				
			

Sample 2

				
					<?php // Set your Consumer Key and Consumer Secret
define('CONSUMER_KEY', 'your-consumer-key');
define('CONSUMER_SECRET', 'your-consumer-secret');

// Set the endpoint for the B2C payment API
$endpoint = 'https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest';

// Set the data for the B2C payment
$data = [
    'InitiatorName' => 'testapi',
    'SecurityCredential' => 'your-security-credential',
    'CommandID' => 'BusinessPayment',
    'Amount' => '100',
    'PartyA' => 'your-shortcode',
    'PartyB' => '254700000000', // This should be the phone number of the customer
    'Remarks' => 'B2C payment test',
    'QueueTimeOutURL' => 'https://your-callback-url.com/timeout',
    'ResultURL' => 'https://your-callback-url.com/result',
    'Occasion' => 'B2C payment test'
];

// Set the access token for the API request
$access_token = getAccessToken(CONSUMER_KEY, CONSUMER_SECRET);

// Make the API request
$response = makeRequest($endpoint, $data, $access_token);

// Print the response
print_r($response);

/**
 * Get the access token for the API request
 *
 * @param string $consumer_key The Consumer Key for your M-PESA API credentials
 * @param string $consumer_secret The Consumer Secret for your M-PESA API credentials
 * @return string The access token to use in the API request
 */
function getAccessToken($consumer_key, $consumer_secret) {
    // Set the endpoint for the OAuth API
    $endpoint = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';

    // Set the HTTP headers for the request
    $headers = [
        'Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret),
        'Content-Type: application/json'
    ];

    // Make the API request
    $response = makeRequest($endpoint, [], $headers);

    // Return the access token from the response
    return $response->access_token;
}

/**
 * Make an API request
 *
 * @param string $endpoint The API endpoint to call
 * @param array $data The data to send in the request
 * @param mixed $headers The headers to include in the request (can be an array or a string)
 * @return object The API response
 */
function makeRequest($endpoint, $data, $headers) {
    // Set the options for the request
    $options = [
        CURLOPT_URL => $endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOP

				
			

Sample 3

				
					<?php // Set the API endpoint and API keys
$api_endpoint = 'https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest';
$consumer_key = '<your_consumer_key>';
$consumer_secret = '<your_consumer_secret>';

// Set the B2C payment details
$command_id = 'BusinessPayment';
$amount = '100';
$party_a = '<your_shortcode>';
$party_b = '<customer_phone_number>';
$remarks = 'B2C Payment Test';
$queue_timeout_url = '<your_queue_timeout_url>';
$result_url = '<your_result_url>';
$initiator_name = '<your_initiator_name>';
$security_credential = '<your_security_credential>';

// Build the request body
$request_body = [
    'CommandID' => $command_id,
    'Amount' => $amount,
    'PartyA' => $party_a,
    'PartyB' => $party_b,
    'Remarks' => $remarks,
    'QueueTimeOutURL' => $queue_timeout_url,
    'ResultURL' => $result_url,
    'InitiatorName' => $initiator_name,
    'SecurityCredential' => $security_credential,
];

// Set the request headers
$request_headers = [
    'Content-Type: application/json',
    'Authorization: Bearer '.get_access_token($consumer_key, $consumer_secret)
];

// Make the request
$response = make_request($api_endpoint, $request_headers, $request_body);

// Print the response
print_r($response);

// Function to get the access token
function get_access_token($consumer_key, $consumer_secret) {
    $api_endpoint = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    $credentials = base64_encode($consumer_key.':'.$consumer_secret);
    $request_headers = ['Authorization: Basic '.$credentials];
    $response = make_request($api_endpoint, $request_headers);
    return $response->access_token;
}

// Function to make an HTTP request
function make_request($url, $headers, $data = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS
</your_security_credential></your_initiator_name></your_result_url></your_queue_timeout_url></customer_phone_number></your_shortcode></your_consumer_secret>
				
			

Sample 4

				
					<?php // Set your M-Pesa API keys
$consumer_key = "your_consumer_key";
$consumer_secret = "your_consumer_secret";

// Set your M-Pesa shortcode
$shortcode = "your_shortcode";

// Set the phone number of the customer
$phone_number = "customer_phone_number";

// Set the amount to be paid (in Kenyan shillings)
$amount = "100";

// Set the M-Pesa account to be used for the transaction (e.g. "Paybill" or "Buy Goods")
$account_reference = "Paybill";

// Set a unique transaction reference
$transaction_reference = "your_transaction_reference";

// Set a description for the transaction
$description = "Payment for goods or services";

// Set the Daraja API endpoint URL
$url = "https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";

// Set the HTTP method and headers
$method = "POST";
$curl_headers = array(
  "Authorization: Bearer ".$access_token,
  "Content-Type: application/json"
);

// Set the request body
$curl_post_data = array(
  "InitiatorName" => $shortcode,
  "SecurityCredential" => "",
  "CommandID" => "SalaryPayment",
  "Amount" => $amount,
  "PartyA" => $shortcode,
  "PartyB" => $phone_number,
  "Remarks" => $description,
  "QueueTimeOutURL" => "https://your-timeout-url.com",
  "ResultURL" => "https://your-result-url.com",
  "Occasion" => $account_reference
);

// Initialize the cURL request
$curl = curl_init();

// Set the cURL options
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curl_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));

// Execute the cURL request
$curl_response = curl_exec($curl);

// Close the cURL session
curl_close($curl);

// Print the response
echo $curl_response;

?>

				
			

This code assumes that you have already obtained an access token, which is required to authenticate the API request. You can use the following code to obtain an access token:

				
					<?php // Replace YOUR_CONSUMER_KEY and YOUR_CONSUMER_SECRET with your actual consumer key and secret
define("CONSUMER_KEY", "YOUR_CONSUMER_KEY");
define("CONSUMER_SECRET", "YOUR_CONSUMER_SECRET");

// Set up the API endpoint and parameters
$url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";

// Set up the authorization header
$credentials = base64_encode(CONSUMER_KEY . ":" . CONSUMER_SECRET);
$headers = array(
    "Authorization: Basic " . $credentials
);

// Initialize cURL
$ch = curl_init();

// Set the API endpoint, authorization header, and other options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request and get the response
$response = curl_exec($ch);

// Close cURL
curl_close($ch);

// Decode the response and get the access token
$responseData = json_decode($response, true);
$accessToken = $responseData["access_token"];

echo "Access token: " . $accessToken;

				
			

This code sends a request to the API endpoint using cURL, with the necessary authorization header and parameters. The API responds with a JSON object containing the access token, which is then extracted and printed to the screen.

You can then use this access token to make API calls to the B2C API.

I hope this helps! Let me know if you have any questions.

What's your reaction?
1Smile0Shocked0Cool0Sad0Laugh