How to Develop Mpesa Integration to Website Using Safaricom C2B API

Introduction

In this guide, you are going to learn how to develop Mpesa integration to website. Mpesa is one of the most popular mobile money transfer services in the world.

The innovative product is offered by Safaricom – Kenya’s leading telecommunication company with the strongest and widest network coverage.

With Mpesa, anyone can send money to you in Kenya using their Safaricom sim card and a mobile phone that supports a Sim Tool Kit(STK).

Safaricom has a ‘Lipa na Mpesa’ service specifically tailored for businesses that want to collect payments through the Mpesa payment gateway for Till and Paybill numbers(short codes).

Lipa na Mpesa offers a lot of convenience to customers and businesses. Text notifications are sent to merchants’ nominated mobile numbers when customers make payments to the business’s short code that is issued for free by Safaricom.

Apart from the SMS notifications, it is possible to develop Mpesa integration to website. This is a more effective way of pushing Mpesa transactions details to a website’s database automatically.

The transaction can then be processed further to update a website work-flow or business logic. The same analogy is used by banks in Kenya to credit customers’ Mpesa transactions to their respective accounts.

Developers can integrate with M-Pesa payment gateway by following the steps below.

Prerequisites

  • A domain name for your business (e.g. www.example.com). You will get this free of charge if you purchase hosting space from Bluehost otherwise, you will have to part with $15/year
  • A web hosting space. I recommend a fast hosting provider like Bluehost to avoid timeouts when your API endpoints are called by Safaricom servers.

  • Apache or any other web server that supports PHP. This is installed by default if you purchase a host from Bluehost.
  • MySQL database – free from Bluehost.
  • PhpMyadmin to administer your database.
  • An FTP username with privileges to upload files to a web server.

Step 1: Create an account at Safaricom Developer Portal

Mpesa maintains a central developer portal at https://developer.safaricom.co.ke/login-register. Just click the link above to create your account.

You will need to enter the following details. Please make sure the details are accurate.

  • First Name *
  • Last Name *
  • Account Type *
  • Username *
  • E-mail address *
  • Company Name
  • Country *
  • Mobile Number *

Step 2: Creating a C2B API and Generating a Consumer Key and a Consumer Secret

Once your account is approved, log in to the Mpesa developer portal https://developer.safaricom.co.ke/login-register by entering your username and password.

Click the “My APPs” link at the top left to create your first app, and then click on the “Add a new APP” button on your right.

Since you are creating Mpesa integration to website using c2b API, check the box that reads, “Mpesa sandbox for b2b, b2c and c2b apis” . Then assign your app any name e.g. MyWebsite Api

Then, click on the “Create APP” button.

Once your app is created, you need to click it under the heading, “These are your apps! Explore them!

At the bottom left, you will see your consumer key and consumer secret. Just copy-paste those details somewhere on your computer – we will need them later.

Step 3: Creating a Security Token to Safeguard Against Fake Transactions

Using M-Pesa payment gateway is a good way to receive payments on your website. However, it can become a target of hackers. To safeguard against this, you need to generate a strong password with a mix of letters, numbers and special characters. e..g

yourPU_RstrongPasswordSample$

The password will be used as an authorization mechanism to secure your website’s call back URLs that Safaricom API will notify once you receive a payment on your Mpesa Till or Paybill number.

Step 4: Retrieve a Test Short-code

The Safaricom developer portal allows you to generate a short code that you can use to test your integration of Mpesa to your website before moving to production.

While logged in on the Mpesa developer website, click the link below to get the  test short code.

https://developer.safaricom.co.ke/test_credentials

Copy the 6 digit shortcode 1 number and keep it alongside the consumer key and consumer secret that you generate earlier.

Step 4: Creating a Database Table to Store Mpesa Transactions

Integrating Mpesa on your website requires you to have a  database for storing transactions. You need to create a database and a table. You can use PHPMyAdmin to do this.

Your table schema should look like this. Let’s give this table a name like mpesa_payments

Auto - Auto number
TransactionType Varchar 40
TransID  Varchar 40
TransTime Varchar 40
TransAmount double
BusinessShortCode Varchar 15
BillRefNumber Varchar 40
InvoiceNumber Varchar 40
ThirdPartyTransID Varchar 40
MSISDN Varchar 20
FirstName Varchar 60
MiddleName Varchar 60
LastName Varchar 60
OrgAccountBalance Double

The length of the variable characters used above can be optimized and we have just used an arbitrary length to make sure the transactions will not fail.

Step 5:  Creating a Folder on your Website to Store Validation and Confirmation URLs

Next, we need to create a folder for holding Mpesa website API call back URL’s. When a customer makes payment to your till or Paybill number, Mpesa will first send the transaction details on your validation URL.

You should do your business logic to validate the transactions. For instance, you can check the amount or the account number and reject the transaction.

Create a folder on your website root. Assuming your website is www.example.com, you can create a folder like www.example.com/mpesa/. However, using a random name is more secure e.g www.example.com/ixoisjus/

Step 6:  Creating a C2B validation Callback URL  

Next, you need to upload a PHP validation file to that folder. You can use notepad to create the file and give it a name like “validation.php

So your full validation URL will read like this www.example.com/mpesa/validation.php

Then, you need to copy-paste the following text on that file.

<?php 

header("Content-Type:application/json"); 

if (!isset($_GET["token"]))
{
echo "Technical error";
exit();
}



if ($_GET["token"]!='yourPU_RstrongPasswordSample$')
{
echo "Invalid authorization";
exit();
}



/* 
here you need to parse the json format 
and do your business logic e.g. 
you can use the Bill Reference number 
or mobile phone of a customer 
to search for a matching record on your database. 
*/ 

/* 
Reject an Mpesa transaction 
by replying with the below code 
*/ 

echo '{"ResultCode":1, "ResultDesc":"Failed", "ThirdPartyTransID": 0}'; 

/* 
Accept an Mpesa transaction 
by replying with the below code 
*/ 

echo '{"ResultCode":0, "ResultDesc":"Success", "ThirdPartyTransID": 0}';
 
?>

As you can see, you can either reject or accept the transaction by replying with the appropriate response.

Remember to change the token variable with the password that you created above.

Step 7:  Creating a C2B Confirmation Callback URL on Your Website

Create another file and give it a name like “confirmation.php

Your full confirmation URL will read like this www.example.com/mpesa/confirmation.php

The confirmation URL will be called back by Safaricom when a customer transaction is finalized on their side. Therefore, we need to strip the JSON input from the Mpesa API and save the transaction details on our database that we created above.

Just copy-paste the below content on the confirmation.php file and upload it on your website. You can either do this using Filezilla or the file manager that ships with Cpanel especially if you are using Bluehost

Remember to replace the token variable with the password that you chose above. You also need to supply your Mysql hostname(server name), username, password and database name in the appropriate fields.

<?php

header("Content-Type:application/json");

if (!isset($_GET["token"]))
{
echo "Technical error";
exit();
}



if ($_GET["token"]!='yourPU_RstrongPasswordSample$')
{
echo "Invalid authorization";
exit();
}



if (!$request=file_get_contents('php://input'))

{
echo "Invalid input";
exit();
}






$con = mysqli_connect($servername, $username, $password, $dbname);

if (!$con) 
{
die("Connection failed: " . mysqli_connect_error());
}



//Put the json string that we received from Safaricom to an array
$array = json_decode($request, true);
$transactiontype= mysqli_real_escape_string($con,$array['TransactionType']); 
$transid=mysqli_real_escape_string($con,$array['TransID']); 
$transtime= mysqli_real_escape_string($con,$array['TransTime']); 
$transamount= mysqli_real_escape_string($con,$array['TransAmount']); 
$businessshortcode=  mysqli_real_escape_string($con,$array['BusinessShortCode']); 
$billrefno=  mysqli_real_escape_string($con,$array['BillRefNumber']); 
$invoiceno=  mysqli_real_escape_string($con,$array['InvoiceNumber']); 
$msisdn=  mysqli_real_escape_string($con,$array['MSISDN']); 
$orgaccountbalance=   mysqli_real_escape_string($con,$array['OrgAccountBalance']); 
$firstname=mysqli_real_escape_string($con,$array['FirstName']); 
$middlename=mysqli_real_escape_string($con,$array['MiddleName']); 
$lastname=mysqli_real_escape_string($con,$array['LastName']); 
 


$sql="INSERT INTO mpesa_payments
( 
TransactionType,
TransID,
TransTime,
TransAmount,
BusinessShortCode,
BillRefNumber,
InvoiceNumber,
MSISDN,
FirstName,
MiddleName,
LastName,
OrgAccountBalance
)  
VALUES  
( 
'$transactiontype', 
'$transid', 
'$transtime', 
'$transamount', 
'$businessshortcode', 
'$billrefno', 
'$invoiceno', 
'$msisdn',
'$firstname', 
'$middlename', 
'$lastname', 
'$orgaccountbalance' 
)";
 

if (!mysqli_query($con,$sql)) 
 
{ 
echo mysqli_error($con); 
} 
 
 
else 
{ 
echo '{"ResultCode":0,"ResultDesc":"Confirmation received successfully"}';
}
 
mysqli_close($con); 
?>

Step 8:  Registering Validation and Confirmation Callback URLs on Safaricom API

Finally, we need to register the validation and confirmation URLs on the M-Pesa payment gateway. This will enable Safaricom to call our URL’s when a transaction occurs on their side.

To do this, we need to create a third file and upload it to our website. You can call this file register.php.

So your full register.php URL will read like this

www.example.com/mpesa/register.php

To register our validation and confirmation URL’s, we will use curl and PHP. Just copy-paste the text below on your register.php file and replace your shortcode, consumer key and consumer secret.

<?php
header("Content-Type:application/json");
$shortcode='replacewithyourshortcode';
$consumerkey    ="replacewithyourconsumerkey";
$consumersecret ="replacewithyourconsumersecret";
$validationurl="enteryourvalidationurlhere";
$confirmationurl="enteryourconfirmationurlhere";
/* testing environment, comment the below two lines if on production */
$authenticationurl='https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$registerurl = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl';
/* production un-comment the below two lines if you are in production */
//$authenticationurl='https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
//$registerurl = 'https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl';
$credentials= base64_encode($consumerkey.':'.$consumersecret);
$username=$consumerkey ;
$password=$consumersecret;
  // Request headers
  $headers = array(  
    'Content-Type: application/json; charset=utf-8'
  );
  // Request
  $ch = curl_init($authenticationurl);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  //curl_setopt($ch, CURLOPT_HEADER, TRUE); // Includes the header in the output
  curl_setopt($ch, CURLOPT_HEADER, FALSE); // excludes the header in the output
  curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); // HTTP Basic Authentication
  $result = curl_exec($ch);  
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
$result = json_decode($result);
$access_token=$result->access_token;
curl_close($ch);

//Register urls
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $registerurl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$access_token)); 
$curl_post_data = array(
  //Fill in the request parameters with valid values
  'ShortCode' => $shortcode,
  'ResponseType' => 'Cancelled',
  'ConfirmationURL' => $confirmationurl,
  'ValidationURL' => $validationurl
);
$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);
echo $curl_response;
?>

However, you need to append the password that you chose above on your validation and confirmation URL’s using a token variable when registering the URLs.

So your validation and confirmation urls will read like this on the register.php file.

Validation URL

https://www.example.com/mpesa/validation.php?token=yoPURstrongPasswordGoeshere$

Confirmation URL

https://www.example.com/mpesa/confirmation.php?token=yoPURstrongPasswordGoeshere$

Once the file is ready, upload it to your website. You will then need to open the file with your web browser to register the URLs.

So on your web browser,  visit www.example.com/mpesa/register.php and your URLs will be registered automatically with the Mpesa API.

Step 9: Testing the Validation and Confirmation URLs Configurations

You can test the configurations of your validation and confirmation URLs using our Mpesa API URLs simulator: https://www.tekfansworld.com/simulate/mpesa-c2b-api-simulation.php

This tool mimics what the Mpesa server does when a customer makes a transaction to your Paybill or Till number.

Once your validation and confirmation URLs are all set as discussed above, use our tool to send sample transactions to your website and see whether  Mpesa API works as expected.

Again, you can visit the tool from this link: https://www.tekfansworld.com/simulate/mpesa-c2b-api-simulation.php

The tool looks like this:

Step 10:  Moving Mpesa API to Production

If you are able to complete the above steps and you got a success message during url registration. You can now move to production. On the Safaricom developer portal, click on the, “Go Live” link at the portal, you will be taken through a series of steps to prove ownership of your Paybill or Till number.

You will also need to download an Excel test case document, look for the c2b worksheet name at the bottom.

On the worksheet, create a new column with the name Actual Results and enter the word ‘okay’ or ‘success’ all the way from top to bottom. This signifies that you were able to run all Mpesa API test cases on your C2B API on the sandbox environment.

Mpesa API testcases.xlsx
Mpesa API test cases

Once everything is finalized, your app will be moved to production and you will get a new set of consumer key and consumer secret. Then, you will need to re-register URLs with your live Paybill or Till number plus the new set of credentials.

From this point forward, all transactions will be routed to your website database and you can do your business logic for further processing.

Pro Tip : Validation on your shortcode is not enabled by default. 

If you want validation for your Paybill or Till number, kindly write to APIfeedback@Safaricom.co.ke and ask them to activate the same.

Sample Email:

Greetings,

Kindly enable external validation for our Paybill/Till number 111111. Our organization name is Sample Company. 

We would like to validate all Mpesa transactions before they are completed.

Regards,

Signatories

Remember to replace 111111 with your Mpesa Paybill/Till number and Sample Company with the real name associated with your Paybill or Till number

Conclusion

You can use this Mpesa API documentation to develop a customer to business API for your website. Remember, you can always refer to the Mpesa developer portal tutorials in case you run into a problem.

However, if you have followed the above Mpesa integration for website tutorial step by step, your c2b API will work without any hiccups.

Remember to check out our Mpesa C2B Simulator tool for simplified testing.

You might also like:

Mpesa B2C(Business to Customer) API