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.
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
'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
';
$consumer_secret = '';
// Set the B2C payment details
$command_id = 'BusinessPayment';
$amount = '100';
$party_a = '';
$party_b = '';
$remarks = 'B2C Payment Test';
$queue_timeout_url = '';
$result_url = '';
$initiator_name = '';
$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
Sample 4
$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:
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.
