How to Develop Mpesa Integration to Website Using Safaricom C2B API


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.


  • A domain name for your business (e.g. 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 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 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 come up with a strong password that has a mix of letters, numbers, and special characters. e.g.


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, open the link below to get a  test short code (e.g. 600413).

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, you can create a folder like However, using a random name is more secure e.g

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

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



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

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

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

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.



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

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

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

echo "Invalid input";

$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']); 
$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']); 

$sql="INSERT INTO mpesa_payments

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

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

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.

$consumerkey    ="replacewithyourconsumerkey";
$consumersecret ="replacewithyourconsumersecret";
/* testing environment, comment the below two lines if on production */
$registerurl = '';
/* production un-comment the below two lines if you are in production */
//$registerurl = '';
$credentials= base64_encode($consumerkey.':'.$consumersecret);
$username=$consumerkey ;
  // 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_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);

//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$

Confirmation URL$

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 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:

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:

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 and ask them to activate the same.

Sample Email:


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.



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


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


Mpesa API Integration to Website
Article Name
Mpesa API Integration to Website
This is a step-by-step guide for integrating Mpesa API on your website to receive automated Mpesa transactions details in real time.
Publisher Name
Tek Fans World
Ads by Google

233 thoughts on “How to Develop Mpesa Integration to Website Using Safaricom C2B API”

  1. This is an awesome Mpesa API guide, I think Safaricom should purchase this article. What they have on their Mpesa API portal is far much complex and scaring!

    1. Hi,
      I am using a demo subdomain. I have followed the procedure, but I get this:
      Confirmation URL is not valid
      Validation URL is not valid.
      But this happened after I created the database. What could be the problem?

  2. HI you are missing something like



    ….//Put the json string that we received from Safaricom to an array
    $array = json_decode($request, true);

    In your confirmation.php file.
    As it is i believe it cannot capture the submited $_POST parameters from Safaricom servers

      1. I have managed to register the urls but the files are empty. I have
        inside the results.php and confirm.php page. it is empty.

          1. Hello Francis, I would like to be assisted in the integration process, of course at a fee

      2. Hello Francis, nice work there, nice work.

        This is my output for register.php
        { “ConversationID”: “”, “OriginatorCoversationID”: “”, “ResponseDescription”: “success” }
        which I bet the code ran successfully, but

        my validation.php and confirmation.php throw a technical error, meaning token is not set, but I can’t seem to know why. Any assistance, I’l be very glad

  3. Boss, hats off to you. I have been looking for a guide how to go about Integrating Mpesa API. I will post how my integration goes.

      1. The integration was successful. Am just having a problem going live. Can you help. I used safaricom test provided Paybill, when I input that paybill number, I dont know what to use for the organization name n mpesa username

        1. Hey Michael?
          When you are going live on Mpesa API for C2B, you must use an actual Paybill number that is already working and capable of receiving transactions. On the organisation name input the full business name registered with the Paybill number. On the username field, ask the owner of the Paybill to provide you with any username used to login to the Mpesa portal.

          1. Hey Francis,
            Many thanks. I will sure let u guys know how it goes. I hope to finish it up soon. U could also provide ur telephone number for consultancy and immediate assistance.

          2. You can get immediate support by contacting Safaricom, this guide is just for illustration purposes and I have no mandate to offer full consultation.

          3. If you have multiple Paybill no’s or till numbers, you must think of a way to differentiate the transactions. Luckily, the Paybill/Till no is sent back when a transaction is completed from the Mpesa’s side.

  4. Nice tutorial,I managed to intergrate Mpesa API for opencart. Do you know how to send parameters to safaricom servers to initiate Mpesa API STK push. The php code logic?

  5. I am very grateful! God bless the work of your hands!!
    I wish I could send you something small for this well done job (hehehehhe)
    But anyways very good article.

  6. Hi Francis,
    I followed the tutorial and everything is working fine, thank you. The only issue though is that am not able to have the simulated transcation inserted into the database. Kindly educate me.

  7. Did anyone happen to encounter this error while registering and how did you solve it?
    requestId “14066-3235959-1”
    errorCode “401.003.01”
    errorMessage “Error Occurred – Invalid Access Token – Invalid access token”

  8. Hi Francis not sure where i went wrong on this but am receiving this error yet i think I have saved the correct path

    requestId “15880-412563-1”
    errorCode “400.003.02”
    errorMessage “Bad Request – Invalid ValidationURL”

  9. May I know please.How does this integration work from a customer’s perspective?is it like a checkout button that takes you to your lipa na mpesa page or it asks the customer to leave the page get to mpesa and pay and then come back to complete? Does it work like the visa cards checkout process with geteways like 2checkout which is very seamless and the customer is taken through a clear process without living the page.

    Maybe a link to a website already using this form of integration would help .Thanks.

    1. The customer has to come back and complete the transaction using the Mpesa transaction number. If you don’t want customers to leave the page, consider integrating with Mpesa STK Push API instead.

  10. For registration form am getting an error which is

    ( ! ) Notice: Trying to get property of non-object in C:\wamp64\www\nguo\fashion\register.php on line 31

  11. Hey Francis, good stuff.

    Should this be the response after registration or I am lost?
    “ConversationID”: “”,
    “OriginatorCoversationID”: “”,
    “ResponseDescription”: “success”

    1. Yes, precisely, that should be the response that you should get once you have successfully registered your end points or URL’s on the Safaricom Mpesa API gateway. Congratulations David!

  12. Notice: Trying to get property of non-object ERROR
    I keep getting this error i dont know if its my token which has a problem or i dont know how to generate it.please help

      1. Hi Francis
        am gettin the reponce
        “ConversationID”: “”,
        “OriginatorCoversationID”: “”,
        “ResponseDescription”: “success”
        but where will i put the amount and customername so i can validate the results

    1. You will just use the same procedure to register Mpesa API urls during production but this time, use the live Paybill number and production end points

  13. Hi Francis, what if I have a multi-vendor website.
    Let me show you how it works
    There are two people who can add a product for sale.
    1. The customer can upload money to their E-Wallet(Which will be stored in our Mpesa)
    2. A customer can pay the vendor directly without our consent but we will just be notified that a transaction was made.
    3. The admin can pay a vendor if a customer paid for an item through his/her E-Wallet
    4. The vendor can pay admin for a membership fee
    5. The customer can pay admin if he/she buys an item posted by admin
    So, how do we go about this? Maybe if you can write another article about it.
    I already have Paypal integrated. I thought it might be possible with M-Pesa.

  14. Hi Francis,

    Can someone do this integration on a shared hosting environment or you will need a dedicated IP?

    1. Thanks Julius for this question. Before the Daraja API was launched, Mpesa required developers to have a dedicated IP addresses. However, Mpesa API has changed and instead of SOAP, they are using REST API with JSON.

      The good thing about this new integration is that you don’t need a dedicated IP address. All you need is a domain name (e.g. or a sub-domain(e.g.

      What that means is that you can run as many Paybill/Till number integration using a single domain name.

        1. Yes, but why not test it from an online server which is cheap and easy to use. With localhost, you will get a lot of connectivity problems.

    1. Unfortunately, the only details I can provide are included in this guide. I will add more screenshots to prove the concept.

  15. This is good work Francis. Everything worked well up to the registration part. What is not clear to me is about the test case document.
    “look for the c2b worksheet name at the bottom and enter the word “okay” all the way from top to bottom on the right most column.” That column has content – unless it has changed since you wrote this guide. Are we supposed to replace the content ?
    This is clearly supposed to be the easiest part, yet I am lost.

    1. I apologize for the confusion Okello, I will be editing the Mpesa API guide to include a screen shot for the same.

    1. A blank page when running PHP scripts signified syntax error. Kindly check your server error logs for more details.

  16. Hi Francis,

    Nice piece of work you have here. Does this work out of the box or does it require additional work?

    Have you considered doing the same for the WordPress/WooCommerce community?

    There’s no reliable plugin for WooCommerce/Mpesa integration out there. I’ve tested quite a number but I finally got frustrated. I gave up and hired someone to do the integration for me.

    Consider this:

    eCommerce is the future and WooCommerce is the engine that will power the majority of eCommerce websites. Woocommerce now powers more than 2.2 million websites according to BuiltWith. Needless to mention that Mobile money is the easy and convenient way to purchase goods and services not just in Kenya, but across the world.

    Your plugin could save millions of WooCommerce developers and store owners who are currently going through hell tying to integrate their stores with the clumsy and cumbersome Safaricom Mpesa/Mobile API.

    Nairobi, Kenya

    1. Hello Flavian,
      I am also trying to figure out how to link woocommerce with mpesa.
      Do you have a particular secure plugin that you used?


  17. Hi, I am not a programmer so i don’t understand most of the code. In the file confirmation.php, line 13 (shown below)
    [Line 13] $con = mysqli_connect($servername, $username, $password, $dbname);

    Is it correct to replace with my database information as follows?
    $con = mysqli_connect($, $myUserName, $myPassword, $myDBname);

    is this ($ the correct format of entering the server name?

    Thanks for making this code available to laymen. God bless you.

    1. Try something like this:
      $con = mysqli_connect(‘localhost’, ‘james’, ‘PASSWORDHERE’, ‘db_name’); Replace james and db_name with the correct values.

      1. Hi i have followed the article but unfortunately i have not succed what could be missing if you check screenshot

        SyntaxError: JSON.parse: unexpected end of data at line 1 column 5 of the JSON data

    2. No you cannot replace it with that www host,,,the mysqli con connects to the the website to the database ,the format should be $con = mysqli_connect($servername, $username, $password, $dbname);

    1. You can program the Mpesa API on a localhost but this will cost you a lot of time. The best thing is to buy a hosting package.

  18. requestId “18506-3224060-1”
    errorCode “401.003.01”
    errorMessage “Error Occurred – Invalid Access Token – Invalid API call as no apiproduct match found”

    I’m getting this error after implementing the go live option and changing the access keys

  19. Hello I have tried the API especially the registration portion but the token generated returns a blank string which is not object passable. What configuration issue could be existing. Kind Regards

  20. Hi Francis, this is so cool man. It works well with me, i couldn’t understand the official documentation on safaricom website. Just a question, is the new STK Push nearly similar to this one? I dont seem to understand it well. Also a suggestion, may be you can consider developing a plugin for STK push as tihis will save millions. You can list it as a premium one.

    1. I will write an article about Mpesa STK push API soon. The logic is the same, but in this case, the transaction should be triggered on the website/mobile app. However, the developer will still need a confirmation url to capture the Mpesa transaction details from the API gateway.

  21. Nice tut.

    Sandbox everything works fine and after going live the register link step fails with this:
    …. [errorCode] => 400.003.02 [errorMessage] => Bad Request – Invalid ValidationURL )

    what could be the issue here? The validation url supplied went through normally during sand boxing.

  22. Hello Francis. Nice article. Though going through some small challenges to complete. Kindly could you contact me through my email or whatsapp XXXXXXXXXX you help me finish it. Am willing to pay something for it. Thanks

  23. Hi frank.
    following error is what iam geting amy leads on what iam missing
    SyntaxError: JSON.parse: unexpected end of data at line 1 column 5 of the JSON data

  24. Something not clear to me, what is the difference between the security token in step 3 and the token in step 6. Could you please add some screenshot on how to get them

      1. Nice article Francis, my email is n*****
        Please drop me your email. need help in completing these steps for my Till number.
        07XX XXX XXX

    1. The business logic is beyond the scope of this blog. You must be an experienced programmer to do this. Otherwise you will need to find someone with the knowledge and pay for it.

  25. Hello Mr Ndungu, i get the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in my confirmation.php and validation.php file when I call them in the browser. What could be the problem? I have seen some people have asked the same question but have not been answered.

  26. Hi , great tutorial, i was talking to someone who claims to know a lot concerning this c2b integration to website and she was telling me that i have to upgrade my mpesa till account to i don’t know bank transactions or something like that. would you please shed light on the same,
    regards, Patrick

    1. No upgrade is required for your till to work with Mpesa API. However, you need to have credentials for logging to the Mpesa portal(NOT DEVELOPER PORTAL)

  27. How can i make it give pop up to customers mobile like it happens with jumia checkout or jambosho check out.

  28. Bro I owe you coffee… this is an awesome guide, thanks. About the coffee we could talk about hehehee seriuosly though!

  29. hey .am tring to intergrate the same with my website but i dont have a domain can i work with a local host sever to do the same for testing before i go to production

    1. It will work with local server but you will need a lot of tools to test the Mpesa API. Just buy a hosting space for one month and try with it.

  30. Hi..hail to you for this great article. I am, however, faced with one short-coming. when i try the reister.php through my browser, i get this error.

    Warning: Cannot modify header information – headers already sent by (output started at /abc/xyz/anythingl/thefolder/validation.php:1) in /abc/xyz/anything/thefolder/validation.php on line 2
    Technical error

    How can i go about this?

      1. Great work there Mr Francis,

        my validation.php and confirmation.php throw a (technical error) error, wthout any logs for the headers.

        Just technical error which appears even when using your URL testing tool

        1. It seems the token you are appending when testing on the tool is not the one on your validation and confirmation urls

  31. Hey, Nice tutorial there

    I get a technical error on testing the validation.php and confirmation.php, which I guess means token is not set, What cold be the issues, kindly

  32. Hello Francis,
    I have made it all the way as it regards your excellent tutorial. I’m just learning so I’m wondering what next after getting a success message. Do I create a payment form? If so how do I link the validation URL to my form? Kindly if you can assist I will greatly appreciate.

    1. The business login is beyond the scope of this article. You can design the payment form depending on your business logic.

  33. Finally i managed doing it, @Francis Ndungu, really you have saved many.

    ConversationID “”
    OriginatorCoversationID “”
    ResponseDescription “success”

    Now i’m straded, how i will know the person who made the payment because i’m not seen mobile number being returned from the mpesa database. I want to use phone number which made the payment to approve ‘payment done on my site’ … How can i go about it? I’m reaaly straded

  34. Hi Francis,

    What would be the reason for this ?

    Validation URL said :

    400 Bad Request Bad Request Your browser sent a request that this server could not understand. Apache/2.4.10 (Debian) Server at *** Port 443
    Confirmation URL said :

    400 Bad Request Bad Request Your browser sent a request that this server could not understand. Apache/2.4.10 (Debian) Server at **** Port 443

        1. This token helps you to safeguard your server from fake transactions. If you don’t set the token, then anyone who knows your validation and confirmation urls can send a fake transaction.

          1. Mr Ndungu. Thanks for the answer. However, the question is “How do we create the security token (password) in step three?”
            Please explain How. The article does not explain how it is done.

          2. This is just a password that you create by your own, just like the way you created a Gmail account password

    1. That means your URLs are configured correctly, but then, you have to issue the right token on the URL when making the request.

  35. i need your services someone did my mpesa intergration but its not woking yet the validation and confirmation urls are working on your testing tool and the register url says ‘Bad Request – Kindly use your own ShortCode’

  36. Hi Francis, Kudos to the great job you have done…

    I am a developer having a very poor internet connection within Thika. Any network you could recommend?

  37. Hi, I am having problems using your simulator tool.
    A couple of question:
    1. How do I initiate transactions using either the 2 shortcodes provides, 1 lipa na mpesa shortcode and the MSISDN no. ?
    2. Do I need to have a registered paybill already?

  38. great work!!
    i have done everything in the tutorial correct, i have no issue with the registration url, my problem is with the validation and confirmation url, i am getting technical error, even after changing the token variable, what should i do? to get rid of the technical error

  39. <?php
    if (!isset($_GET["token"]))
    echo "Technical error";
    if ($_GET["token"]!='mypasswordhere')
    echo "Invalid authorization";

    besides changing the password is their anything i should change in the above code, like defining and initializing the token variable? my register url is working correctly

  40. What exact values do you put in the token variable, in the confirmation ad validation url
    please don’t give a short answer try to expound

  41. Hi, you have just made wonders bro. I owe you something big. we need to donate something to this legend. !!!!!!!

  42. This is a very great step by step tutorial on how to work with the safaricom API. Thanks Francis, you have solved my million and one problems.

    Testing it out

  43. Error registering url:
    {“Envelope”:{“encodingStyle”:”http:\/\/\/soap\/encoding\/”,”Body”:{“Fault”:{“faultcode”:”soap:Server”,”faultstring”:”Execution of ServiceCallout SCO-AddURLVault failed. Reason: ResponseCode 500 is treated as error”,”faultactor”:{},”detail”:{“source”:{“errorcode”:”steps.servicecallout.ExecutionFailed”}}}}}}

  44. Hi Francis, how can i generate the Security token for Safeguard against Hackers, i can’t figure out how to do it

  45. Hi Francis,
    we have a paybill which is already integrated by a broker to our bank-transactions are credited into our bank realtime as they hit Mpesa portal.Now we want to integrate the same paybill with our ERP,but on trying to register the URLs we get the following error
    “Duplicate notification info, SP ID is 100839, correlator is 98……. “.
    Is it possible to register two URLs on one paybill.If not what other ways do we have to integrate the paybill without affecting the already existing integration done by our bank.


  46. Hi Francis, what could be the reason for this error when registering urls ?

    {“Envelope”:{“encodingStyle”:”http:\/\/\/soap\/encoding\/”,”Body”:{“Fault”:{“faultcode”:”soap:Server”,”faultstring”:”Execution of ServiceCallout SCO-AddURLVault failed. Reason: ResponseCode 500 is treated as error”,”faultactor”:{},”detail”:{“source”:{“errorcode”:”steps.servicecallout.ExecutionFailed”}}}}}}

  47. Hi Francis,
    Before starting i want to know what happens if we try above steps in local server as client did not provide us server and he want project to be completed immediately, can you please tell me??

  48. A great tutorial indeed.
    Im getting this on registering production urls;
    “ConversationID”: “”,
    “OriginatorCoversationID”: “”,
    “ResponseDescription”: “success”

    so after i write to safaricom requesting them to enable external validation for our Paybil , what would happen when a client makes a payment outside the web, or else, what triggers the transaction?

  49. hello sir, thanks for great article, kindly assist, i got success after testing register.php, unfortunately am getting this error when using a simulator tool

    500 Internal Server Error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

  50. Hello Francis,
    When I try to Testi the Validation and Confirmation URLs Configurations using Mpesa API URLs simulator
    The results are as follow ;

    Mpesa PHP API Testing Results
    Sample data sent :

    { “TransactionType”: “Pay Bill”, “TransID”: “LTD7996ATN”, “TransTime”: “20190906133747”, “TransAmount”: “0.02”, “BusinessShortCode”: “999999”, “BillRefNumber”: “SAMPLE ACCOUNT 101”, “InvoiceNumber”: “”, “OrgAccountBalance”: “0.02”, “ThirdPartyTransID”: “”, “MSISDN”: “254000000000”, “FirstName”: “JOHN”, “MiddleName”: “M.”, “LastName”: “DOE” }

    Validation URL said :

    {“ResultCode”:0, “ResultDesc”:”Success”, “ThirdPartyTransID”: 0}
    Confirmation URL said :

    Field ‘ThirdPartyTransID’ doesn’t have a default value

    Is there any problem with my confirmation URL?

  51. hello,i i would like some help on the above code. i have generated the access token but on registering the url it keeps on saying invalid access token

  52. Hi Francis , thanks for the guide. Safaricom aren’t replying to my request on verification of the paybill. Would you kindly offer me another email which they’ll sure reply to on verification of the paybill.
    I can’t go live from that next step!

  53. Hello TekfansWorld,
    I have been searching for this code online to almost no avail. But yay! I got it here. Thanks, Francis and I will bookmark this page as a guide until I get done setting up my payments gateway. Regards and thank you again. Your guide is very nice and different from the others I have seen out there…

  54. Hello,
    I have integrated the API successfully and everything seems to be working fine but I have an issue with the process of Testing the Validation and Confirmation URLs Configurations. I wanted to be able to enter the mobile number (MSISDN) and test it using my phone from my end, is it possible to do that and how would I go about it so that if it’s working I can go live?

  55. {
    “errorCode”: “500.002.1001”,
    “errorMessage”: “Service is currently under maintenance. Please try again later”

    What should I do not to get this error

  56. {
    “errorCode”: “500.002.1001”,
    “errorMessage”: “Service is currently under maintenance. Please try again later”
    How do I do away with this error

  57. Hi,
    Anyone else who has registered their URLs sucessfully. Tested on the simulator tool and worked perfectly but no data is sent by safaricom to their database.

    I have this issue now for a while.

  58. the simulator cant work without https. am pointing through http and getting error “Could not resolve host:” and SyntaxError: “JSON.parse: unexpected end of data at line 1 column 5 of the JSON data on register.php”

  59. Hi Francis;
    I got this error after while testing it with the Mpesa C2B Simulator Tool, where I am going wrong??

    Validation URL said :
    Technical error
    Confirmation URL said :
    Technical error

  60. Hi Francis, for the CustomerBuyGoodsOnline commandID, what are the parameters for the Test Creds and the billRefNumber?? Leaving the BillRef blank is generating an error.

  61. Hi,

    1. I want to associate my payments with something like an order Number for the product. How do I like send the order Number along the request?

    2. Is the Bill Reference No unique? who provides it? me or safaricom

  62. Kindly am getting this error when running my register.php{
    “errorCode”: “500.002.1001”,
    “errorMessage”: “Service is currently under maintenance. Please try again later”

  63. Hi Francis, help me to resolve this error when running register.php

    “errorCode”: “500.002.1001”,
    “errorMessage”: “Service is currently under maintenance. Please try again later”

  64. Hi Francis. Am successfully doing STK pushes on sandbox but the confirmation.php can’t register transactions. Using the test tool in this website, the confirmation.php works fine. What might be wrong?

  65. This code doesn’t work for me.
    I get this error

    “errorCode”: “400.003.02”,
    “errorMessage”: “Bad Request – Invalid ResponseType”

    Any help please?

  66. Hello & thanks for this!
    I’m getting
    ” SyntaxError: JSON.parse: unexpected character at line 1 column 5 of the JSON data” when I try to register the URL. Any idea what might be the problem?

  67. Thanks for the tutorial !, it’s quite simple to follow. I did ran the register url with success.
    However the Mpesa C2B Simulator Tool returns the following :-
    Validation URL said :You do not have permission to view this directory or page.
    Confirmation URL said :You do not have permission to view this directory or page.

    I am using a windows shared hosting domain and i’ve checked on the directory permissions.

    Any clue on this?

  68. Hi Francis,
    I got this error after while testing it with the Mpesa C2B Simulator Tool, where I am going wrong??

    Validation URL said :
    Technical error
    Confirmation URL said :
    Technical error

    1. Hello Francis,
      First thanks for the extremely helpful documentation, its rare to find such tutorials here in Kenya and Africa but you have done us pround. I followed the prompt but am getting lost somewhere, when running the register.php I get below error;
      { “requestId”:”4358-6135275-1″, “errorCode”: “500.003.1001”, “errorMessage”: “error generated by Generate Soap Error” }

      Kindly assist, we can settle to do a commercial engagement on this, am okay with it. Get ack through my mail kindly. Thanks

  69. Hi Francis;
    Kindly assist me with a sample code on how to validate transaction on validation.php using the amount paid, and ether reject or complete the transaction.
    Thanks. Regards, Migwi.

  70. Hi Francis, I have encountered this error while trying to register urls
    “errorCode”: “400.003.02”,
    “errorMessage”: “Bad Request – Invalid ValidationURL – URL has the word MPESA”
    I have gone through the other replies and I have not identified a person with a similar problem. Kindly help

  71. Hi Francis am having problem at live step 2 i upload excel but next step fail what cause error please advice me….
    Paybill Verification failed due to the following reason: Activity timed out
    Service Request for Regsitration Failed

  72. Sample data sent :

    { “TransactionType”: “Pay Bill”, “TransID”: “LTD7996ATN”, “TransTime”: “20190906133747”, “TransAmount”: “0.02”, “BusinessShortCode”: “999999”, “BillRefNumber”: “SAMPLE ACCOUNT 101”, “InvoiceNumber”: “”, “OrgAccountBalance”: “0.02”, “ThirdPartyTransID”: “”, “MSISDN”: “254000000000”, “FirstName”: “JOHN”, “MiddleName”: “M.”, “LastName”: “DOE” }

    Validation URL said :

    {“ResultCode”:0, “ResultDesc”:”Success”, “ThirdPartyTransID”: 0}
    Confirmation URL said :

    Field ‘ThirdPartyTransID’ doesn’t have a default value

    Is there any problem with my confirmation URL?

  73. {
    “errorCode”: “400.003.02”,
    “errorMessage”: “Bad Request – Invalid ValidationURL”
    getting this error

  74. I am able to register the URls successfully as seen below.
    “ConversationID”: “”,
    “OriginatorCoversationID”: “”,
    “ResponseDescription”: “success”

    However Mpesa PHP API Testing Results from the provided tool are as below:

    Sample data sent :

    { “TransactionType”: “Pay Bill”, “TransID”: “LUB2931EWK”, “TransTime”: “20200811142501”, “TransAmount”: “0.08”, “BusinessShortCode”: “999999”, “BillRefNumber”: “SAMPLE ACCOUNT 101”, “InvoiceNumber”: “”, “OrgAccountBalance”: “0.08”, “ThirdPartyTransID”: “”, “MSISDN”: “254000000000”, “FirstName”: “JOHN”, “MiddleName”: “M.”, “LastName”: “DOE” }

    Validation URL said :

    Technical error
    Confirmation URL said :

    What could be the problem sir?

    Also reach me please, I have a small task for you at a fee.

  75. Hello Francis.

    My URLs have registered successfully.

    However I get Technical Error when doing the test with the tool you have provided, see below.

    Mpesa PHP API Testing Results
    Sample data sent :

    { “TransactionType”: “Pay Bill”, “TransID”: “LHT7539MJV”, “TransTime”: “20200811144220”, “TransAmount”: “0.06”, “BusinessShortCode”: “999999”, “BillRefNumber”: “SAMPLE ACCOUNT 101”, “InvoiceNumber”: “”, “OrgAccountBalance”: “0.06”, “ThirdPartyTransID”: “”, “MSISDN”: “254000000000”, “FirstName”: “JOHN”, “MiddleName”: “M.”, “LastName”: “DOE” }

    Validation URL said :

    Technical error
    Confirmation URL said :

    When I ran the validation URL on my browse it generates same technical error but the confirmation URL triggers 404.

    Kindly assist.
    Also reach to me please I have a small task for you at a fee of course.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.