Go to the Safaricom Developer Portal (https://developer.safaricom.co.ke/) and create a developer account if you don’t already have one.
Obtain your API credentials (consumer key and consumer secret) from the developer portal.
Create a new WordPress plugin or modify an existing one to add the necessary code to integrate with the Daraja API. You can use the API documentation (https://developer.safaricom.co.ke/docs) as a reference.
In the plugin, create a custom payment gateway that allows customers to make payments using Mpesa.
Add the necessary code to handle the payment process, including generating the payment request, sending it to the Daraja API, and handling the response.
Test the plugin to ensure that it works as expected.
If everything is working properly, you can publish the plugin and make it available for other WooCommerce users to install and use.
Here is some sample code that demonstrates how you can use the Daraja API to initiate a c2b payment request:
$url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer ACCESS_TOKEN')); // Replace ACCESS_TOKEN with your actual access token
$curl_post_data = array(
// Fill in the request parameters
'ShortCode' => '123456',
'ResponseType' => 'Completed',
'ConfirmationURL' => 'https://example.com/confirm',
'ValidationURL' => 'https://example.com/validate'
);
$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);
curl_close($curl);
This code sends a request to the Daraja API to register a short code and URLs for handling c2b transactions. You can use similar code to handle other aspects of the payment process, such as confirming and validating payments.
It’s important to note that this is just a sample and you will need to modify the code to fit your specific requirements and integrate it into your plugin. You should also use the live API endpoint and your live API credentials when you are ready to go live with your plugin.
