APIs
Authorization
Authorization
Gives you a time bound access token to call allowed APIs.
GET
https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
This API generates the tokens for authenticating your API calls. This is the first API you will engage with within the set of APIs available because all the other APIs require authentication information from this API to work.



The test is automated so that you can easily generate access tokens via the simulator section of this API,  just select the app you are testing, and the keys will auto-populate and then simulate the request. You will have your token that expires in 3600 seconds.



You can also get the postman collection then access your Consumer Key and Consumer Secret under the Keys tab from My apps on Daraja, and paste them on username and password respectively.

Request Body
// AUTHORIZATION (Basic Auth)
 username 
 password
// HEADERS
 {
   Authorization: `Basic Q2RtTmJkdDBpQk4xb3FEZkthc200ZGFiZHBLbXRhTm46RExLRzdQQnVuNzIwR1ppbQ==`;
 }
// PARAMS
  grant_type;
  client_credentials;       
Request Parameter Definition
Name

Description

Type

Sample Values

grant_type

the client_credentials grant type is supported. Put this under Params.

Query

client_credentials

Response Body
{    
   "access_token": "c9SQxWWhmdVRlyh0zh8gZDTkubVF",
   "expires_in":"3599"
}
Response Parameter Definition
Name

Description

Type

Sample Values

access_token

Access token to access other APIs

JSON Response Item

c9SQxWWhmdVRlyh0zh8gZDTkubVF

expiry_in

Token expiry time in seconds

JSON Response Item

3599


...............


M-Pesa Express Simulate
Initiates online payment on behalf of a customer.
POST
https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
Lipa na M-PESA online API also known as M-PESA express (STK Push/NI push) is a Merchant/Business initiated C2B (Customer to Business) Payment.



Once you, our merchant integrate with the API, you will be able to send a payment prompt on the customer's phone (Popularly known as STK Push Prompt) to your customer's M-PESA registered phone number requesting them to enter their M-PESA pin to authorize and complete payment.

This eliminates the challenge of having to remember business pay bill numbers and account numbers and allows customers to confirm the transaction by entering their M-PESA PIN on their mobile phones. For the business, this API enables them to preset all the correct info in the payment request and reduce the chances of wrong payments being performed to their systems. It is a C2B transaction, but the initiator is the organization instead of the customer. Since the organization has the option of presetting all required variables in the request before sending the request, this API has no Validation-Confirmation process like C2B API.


STK push simply means sim tool kit initiated push, this has now evolved to NI push (network initiated push).


The Lipa na M-PESA online API process is explained below;


1.   The Merchant(Partner) captures and sets the API required parameters and sends the API request.

2.   The API receives the request and validates it internally first, then sends you an acknowledgment response.

3.   Through API Proxy an STK Push trigger request is sent to the M-PESA registered phone number of the customer's making the payment.

4.   The customer confirms by entering their M-PESA PIN.

5.   The response is sent back to M-PESA and is processed as below:

a)    M-PESA validates the customer's PIN

b)      M-PESA debits the customer's Mobile Wallet.

c)      M-PESA credits the Merchant (Partner) account.

6.   Once the request is processed send the RESULTS back to the API Management system which is then forwarded to the merchant via the callback URL specified in the REQUEST. 

7.   The customer receives an SMS confirmation message of the payment.



Now let’s dive into the request;

You will first generate an access token to allow you to make the API call. See how to generate an access token here Authorization API link. We’ve also automated this on the simulate request section.

Request Body
{    
   "BusinessShortCode": "174379",    
   "Password": "MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMTYwMjE2MTY1NjI3",    
   "Timestamp":"20160216165627",    
   "TransactionType": "CustomerPayBillOnline",    
   "Amount": "1",    
   "PartyA":"254708374149",    
   "PartyB":"174379",    
   "PhoneNumber":"254708374149",    
   "CallBackURL": "https://mydomain.com/pat",    
   "AccountReference":"Test",    
   "TransactionDesc":"Test"
}
Request Parameter Description
Name

Description

Parameter Type

Sample Values

BusinessShortCode

This is the organization's shortcode (Paybill or Buygoods - A 5 to 6-digit account number) used to identify an organization and receive the transaction.

Numeric

Shortcode (5 to 6 digits) e.g. 654321

Password

This is the password used for encrypting the request sent: A base64 encoded string. (The base64 string is a combination of Shortcode+Passkey+Timestamp)

String

base64.encode(Shortcode+Passkey+Timestamp)

Timestamp

This is the Timestamp of the transaction, normally in the format of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHMMSS) Each part should be at least two digits apart from the year which takes four digits.

Timestamp

YYYYMMDDHHmmss

 

TransactionType

This is the transaction type that is used to identify the transaction when sending the request to M-PESA. The transaction type for M-PESA Express is "CustomerPayBillOnline" for PayBill Numbers and "CustomerBuyGoodsOnline" for Till Numbers.

String

CustomerPayBillOnline

CustomerBuyGoodsOnline

Amount

This is the Amount transacted normally a numeric value. Money that the customer pays to the Shortcode. Only whole numbers are supported.

Numeric

10

PartyA

The phone number sending money. The parameter expected is a Valid Safaricom Mobile Number that is M-PESA registered in the format 2547XXXXXXXX

Numeric

MSISDN (12 digits Mobile Number) e.g. 2547XXXXXXXX

PartyB

The organization that receives the funds. The parameter expected is a 5 to 6-digit as defined in the Shortcode description above. This can be the same as the BusinessShortCode value above.

Numeric

Shortcode (6 digits)

PhoneNumber

The Mobile Number to receive the STK Pin Prompt. This number can be the same as PartyA value above.

Numeric

MSISDN (12 digits Mobile Number) e.g. 2547XXXXXXXX

CallBackURL

A CallBack URL is a valid secure URL that is used to receive notifications from M-Pesa API. It is the endpoint to which the results will be sent by M-Pesa API.

URL

https://ip or domain:port/path

e.g: https://mydomain.com/path

https://0.0.0.0:9090/path

AccountReference

Account Reference: This is an Alpha-Numeric parameter that is defined by your system as an Identifier of the transaction for the CustomerPayBillOnline transaction type. Along with the business name, this value is also displayed to the customer in the STK Pin Prompt message. Maximum of 12 characters.

Alpha-Numeric

Any combination of letters and numbers

TransactionDesc

This is any additional information/comment that can be sent along with the request from your system. Maximum of 13 Characters.

String

Any string between 1 and 13 characters.

Response Body
{    
   "MerchantRequestID": "29115-34620561-1",    
   "CheckoutRequestID": "ws_CO_191220191020363925",    
   "ResponseCode": "0",    
   "ResponseDescription": "Success. Request accepted for processing",    
   "CustomerMessage": "Success. Request accepted for processing"
}
Response Parameter Description
Name

Description

Type

Sample Values

MerchantRequestID

This is a global unique Identifier for any submitted payment request.

String

16813-1590513-1 

CheckoutRequestID

This is a global unique identifier of the processed checkout transaction request.

String

ws_CO_DMZ_12321_23423476

ResponseDescription

Response description is an acknowledgment message from the API that gives the status of the request submission. It usually maps to a specific ResponseCode value. It can be a Success submission message or an error description.

String

-The service request has failed

-The service request has been accepted successfully.

- Invalid Access Token

ResponseCode

This is a Numeric status code that indicates the status of the transaction submission. 0 means successful submission and any other code means an error occurred. 

Numeric

0 or 404.001.03

CustomerMessage

This is a message that your system can display to the customer as an acknowledgment of the payment request submission.

String

E.g.: Success. Request accepted for processing.

Result Body
{    
   "Body": {        
      "stkCallback": {            
         "MerchantRequestID": "29115-34620561-1",            
         "CheckoutRequestID": "ws_CO_191220191020363925",            
         "ResultCode": 0,            
         "ResultDesc": "The service request is processed successfully.",            
         "CallbackMetadata": {                
            "Item": [{                        
               "Name": "Amount",                        
               "Value": 1.00                    
            },                    
            {                        
               "Name": "MpesaReceiptNumber",                        
               "Value": "NLJ7RT61SV"                    
            },                    
            {                        
               "Name": "TransactionDate",                        
               "Value": 20191219102115                    
            },                    
            {                        
               "Name": "PhoneNumber",                        
               "Value": 254708374149                    
            }]            
         }        
      }    
   }
}
Results Parameter Description
Name

Description

Type

Sample Values

Body

This is the root key for the entire Callback message.

JSON Object

{"Body":{ }   }

stkCallback

This is the first child of the Body.

JSON Object

 


MerchantRequestID

This is a global unique Identifier for any submitted payment request. This is the same value returned in the acknowledgment message of the initial request.

String

29115-34620561-1

CheckoutRequestID

This is a globally unique identifier of the processed checkout transaction request. This is the same value returned in the acknowledgment message of the initial request.

String

ws_CO_191220191020363925

ResultCode

This is a numeric status code that indicates the status of the transaction processing. 0 means successful processing and any other code means an error occurred or the transaction failed.

Numeric

0

1032

ResultDesc

The result description is a message from the API that gives the status of the request processing. It usually maps to a specific ResultCode value. It can be a Success processing message or an error description message.

String

E.g:

0: The service request is processed successfully.

1032: Request canceled by the user 

 

CallbackMetadata

This is the JSON object that holds more details for the transaction. It is only returned for successful transactions.

JSON Object

 


Item

This is a JSON Array, within the CallbackMetadata, that holds additional transaction details in JSON objects. Since this array is returned under the CallbackMetadata, it is only returned for successful transactions.

JSON Array

 


Amount

This is the Amount that was transacted

Decimal

10500.5

MpesaReceiptNumber

This is the unique M-PESA transaction ID for the payment request. The same value is sent to the customer by SMS upon successful processing.

String

LHG31AA5TX

Balance

This is the Balance of the account for the shortcode used as partyB.

Decimal

32009.9

TransactionDate

This is a timestamp that represents the date and time that the transaction was completed in the format YYYYMMDDHHmmss 

TimeStamp

20170827163400

PhoneNumber

This is the number of the customer who made the payment.

PhoneNumber

0722000000

Unsuccessful results body structure
Whenever you receive an error in your callback URL, the unsuccessful transaction will have a body results as below and, the error details will be captured under the Items ResultCode and ResultDesc; You can view a list of possible Lipa na M-PESA online errors on the errors tab.



{    
   "Body": {
      "stkCallback": {
         "MerchantRequestID": "29115-34620561-1",
         "CheckoutRequestID": "ws_CO_191220191020363925",
         "ResultCode": 1032,
         "ResultDesc": "Request canceled by user."
      }
   }
}


Errors
Error

Description

Possible cause and Solution

1037

DS timeout user cannot be reached

Applies to Lipa Na M-PESA API. It means that the STK Push Prompt never got to the user. Causes include:

Cause

The user not having an updated SIM Card that has a small sim size and thus needs an update.

The SIM card is too old (3+ years) to have received the STK Update to allow access to this service.

Mobile phone is offline.

Solution

Update SIM card via *234*1*6# or Upgrade SIM card and perform a SIM swap/replacement at Safaricom Agent shop.

Make sure the target SIM card's mobile phone is online.

NB: STK push camouflaged to NI push meaning it's now a network-initiated prompt as opposed to a sim tool kit-initiated push, this change reduced the error significantly.

1025

An error occurred while sending a push request

Cause

System error

Solution

Retry the request, and make sure your system is working as expected.

9999

An error occurred while sending a push request.



1025

An error occurred while sending a push request

Cause

USSD message from M-PESA  is too long ie more than 182 characters

Solution

Make sure the messaging is less than 182 characters

1037

No response from the user

Cause

This means that the STK Push Prompt got to the customer but the response by the customer was not sent back on time. This is a backend API issue, not a user issue.



Solution

Simply retry again after receiving the callback. Make sure to notify the user that the request failed.

1032

The request was canceled by the user

Cause

This means that the STK Push Prompt was canceled from the user's end. This occurs when:

STK Prompt timed out waiting for user input (takes between 1-3 minutes depending on phone model).

The user canceled the request on their phone.

Solution

Depending on the scenario, either inform the user that they did not respond or just cancel the transaction, then try again.

1

The balance is insufficient for the transaction.

Cause

Subscriber has declined using Overdraft aka Fuliza

The subscriber has insufficient funds on M-PESA.

Solution

Advise customer to deposit funds on their M-PESA or use Overdraft(Fuliza) when prompted

2001

The initiator information is invalid.

Cause

The user initiating the push has given invalid password input

The user has entered the wrong pin to validate the STKPUSH request.

Solution

Use correct user credentials Subscriber to key in the correct M-PESA pin

1019

Transaction has expired

Cause

The transaction has taken a long before being processed within the allowable time

1001

Unable to lock subscriber, a transaction is already in process for the current subscriber

Cause

Duplicated MSISDN, MSISDN has an existing USSD session.

Conflicting of sessions.

The user has an ongoing USSD Session.

Supplementary services are barred for user.

Solution

Close the session before initiating another push

User to try again between 2-3 minutes

Make sure you send one push request to a user at a time.

User to contact Safaricom for unbarring


-------------------


Customer To Business Register URL
Register validation and confirmation URLs on M-Pesa
POST
https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl
Register URL API works hand in hand with Customer to Business (C2B) APIs and allows receiving payment notifications to your paybill. This API enables you to register the callback URLs via which you shall receive notifications for payments to your pay bill/till number.

There are two URLs required for Register URL API: Validation URL and Confirmation URL.

Validation URL: This is the URL that is only used when a Merchant (Partner) requires to validate the details of the payment before accepting. For example, a bank would want to verify if an account number exists in their platform before accepting a payment from the customer.

Confirmation URL:  This is the URL that receives payment notification once payment has been completed successfully on M-PESA.

NB: C2B Transaction Validation is an optional feature that needs to be activated on M-Pesa, the owner of the shortcode needs to make this request for activation by emailing us at apisupport@safaricom.co.ke or M-pesabusiness@safaricom.co.ke  if they need their transactions validated before execution.





 

The above chart, explains how URLs are registered to send requests and receive responses.

Flowchart of the C2B process


The process is explained below:

Payment request to a pay bill by a customer from their phone.
M-PESA receives requests and validates them internally
M-Pesa then checks if External Validation has been activated for the paybill.
If External Validation is enabled:
M-PESA first sends a Validation request to the Validation URL registered in the system by the integrated partner with the payment details.
The integrated partner system validates the request and sends an appropriate response to M-PESA. This response must be received within a given period or M-Pesa marks the partner endpoint as unreachable. The response informs M-Pesa to either complete or cancel the payment:
M-Pesa receives the response and processes the transaction accordingly:
As explained in item 6 below, If you had registered a default action value to complete the transaction, M-PESA sends a Confirmation request to your Confirmation URL with the details of the completed transaction. The transaction is then complete. Thus you shall receive two API calls on your system.
If you had registered cancelled as the default action, M-Pesa simply cancels the transaction and no other request is sent. The transaction is then complete
If External Validation is disabled, M-Pesa automatically completes the transaction, and if the transaction is a success, M-Pesa sends a Confirmation request to the Confirmation URL registered in the system. This is the only API call you shall receive on your end.
If External Validation is enabled, but for some reason, M-Pesa could not reach your endpoint to validate the transaction within the stipulated time period (usually < 8 seconds from the moment the request leaves M-PESA), or no response was received by the time M-PESA terminates the request, it checks on the default action value saved during registration of the URLs. If the default action was set to Completed, M-PESA automatically completes the transaction and also tries to send a Confirmation request to your other endpoint. If the default action was set to Cancelled, M-Pesa simply cancels the transaction and no Confirmation callbacks are sent. The transaction is then complete.
If no URLs are registered in the system, M-PESA automatically completes the request.
M-PESA then sends an SMS notification to both the customer and the paybill owner with the results of the transaction as usual.
When external notifications fail to be sent, you can use Pull transaction API for reconciliation or check on the M-PESA Org portal https://org.ke.m-pesa.com/login.action and cross-check against received callbacks. The portal has all the payments ever made available, whether you received the callback or not.
URL Requirements
Use publicly available (Internet-accessible) IP addresses or domain names.
All Production URLs must be HTTPS, on Sandbox you're allowed to simulate using HTTP.
Avoid using keywords such as M-PESA, M-Pesa, M-Pesa, Safaricom, exe, exec, cmd, SQL, query, or any of their variants in either upper or lower cases in your URLs.
Do not use public URL testers e.g. ngrok, mockbin, or requestbin, especially on production, they are also usually blocked by the API. Use your own application URLs and do not make them public or share them with any of your peers.
NB:

On the sandbox, you are free to register your URLs multiple times or even overwrite the existing ones. In the production environment, this is a one-time API call that registers your validation and confirmation URLs to have them changed you can delete them on the URL management tab under self-service and re-register using register URL API, you can also email us at apisupport@safaricom.co.ke for assistance.

As you set up the default value, the words “Cancelled/Completed” must be in sentence case and well-spelled.

Request Body
{    
   "ShortCode": "601426",
   "ResponseType":"[Cancelled/Completed]",
   "ConfirmationURL":"[confirmation URL]",
   "ValidationURL":"[validation URL]"
}
Request Parameter Definition
Name

Description

Type

Sample Values

Validation URL

This is the URL that receives the validation request from the API upon payment submission. The validation URL is only called if the external validation on the registered shortcode is enabled. (By default External Validation is disabled).

URL

https://ip or domain:port/path

ConfirmationURL

This is the URL that receives the confirmation request from API upon payment completion.

URL

https://ip or domain:port/path

ResponseType

This parameter specifies what is to happen if for any reason the validation URL is not reachable. Note that, this is the default action value that determines what M-PESA will do in the scenario that your endpoint is unreachable or is unable to respond on time. Only two values are allowed: Completed or Cancelled. Completed means M-PESA will automatically complete your transaction, whereas Cancelled means M-PESA will automatically cancel the transaction, in the event M-PESA is unable to reach your Validation URL.

String

- Canceled

- Completed


Shortcode

Usually, a unique number is tagged to an M-PESA pay bill/till number of the organization.

Numeric

123456

Response Body
{
    "OriginatorCoversationID": "7619-37765134-1",
    "ResponseCode": "0",
    "ResponseDescription": "success"
}
Response Parameters Definition
Name

Description

Type

Sample Values

OriginatorCoversationID

This is a global unique identifier for the transaction request returned by the API proxy upon successful request submission.

Alpha-numeric

An alpha-numeric string of fewer than 20 characters

ResponseCode

It indicates whether Mobile Money accepts the request or not.

Alpha-numeric

0

ResponseDescription

This is the status of the request.

String

Success



NB: Before any API request register URL is included, you will require authorization by generating an access token from the authorization API to allow you successfully make an API call.

Once you’ve registered URLs as explained above, C2B API payment transaction is initiated by the customer when they are paying. You can use the simulator to have an overview of how the request looks. You don’t need to develop anything on your side for this part.



Upon successful payment, we post the payment details to your confirmation and validation URLs as explained in the resulting body below;

Result Body
Validation Request

The validation request is received only by partners who have the External Validation feature enabled on their PayBill or BuyGoods (Till Number) and require validating a payment before M-PESA completes the transaction. You will first receive a validation request to validate on your Validation URL.



The Confirmation and Validation result posted on your URLs after payment will have the structure below:

{    
   "TransactionType": "Pay Bill",
   "TransID":"RKTQDM7W6S",
   "TransTime":"20191122063845",
   "TransAmount":"10"
   "BusinessShortCode": "600638",
   "BillRefNumber":"invoice008",
   "InvoiceNumber":"",
   "OrgAccountBalance":""
   "ThirdPartyTransID": "",
   "MSISDN":"25470****149",
   "FirstName":"John",
   "MiddleName":""
   "LastName":"Doe"
}


Validation Response

After receiving the validation request, you are required to process it and respond to the API call and inform M-PESA either to accept or reject the payment. To accept, you send the below JSON making sure the value of ResultCode is 0 (zero), but the value of ResultDesc is Accepted.

{    
   "ResultCode": "0",
   "ResultDesc": "Accepted",
}


To reject a transaction, you send the same JSON above, but with the ResultCode set as C2B00011 (or any other value from the error table below), BUT NOT 0. The ResultDesc should be set as Rejected as shown below:

{    
   "ResultCode": "C2B00011",
   "ResultDesc": "Rejected",
}


Result Error Codes

ResultCode

ResultDesc

C2B00011

Invalid MSISDN

C2B00012

Invalid Account Number

C2B00013

Invalid Amount

C2B00014

Invalid KYC Details

C2B00015

Invalid Shortcode

C2B00016

Other Error

Results Parameter Definition
Name

Description

Type

Sample Values

TransactionType

The transaction type specified during the payment request.

String

Buy Goods or Pay Bill

TransID

This is the unique M-Pesa transaction ID for every payment request. This is sent to both the call-back messages and a confirmation SMS sent to the customer.

Alpha-numeric

LHG31AA5TX

TransTime

This is the Timestamp of the transaction, normally in the format of YEAR+MONTH+DATE+HOUR+MINUTE+SECOND (YYYYMMDDHHMMSS) Each part should be at least two digits apart from the year which takes four digits.

Time

YYYYMMDDHHmmss e.g. 20170813154301

TransAmount

This is the amount transacted (normally a numeric value), money that the customer pays to the Shortcode. Only whole numbers are supported.

Numeric

100

BusinessShortCode

This is the organization's shortcode (Paybill or Buygoods - a 5 to 6-digit account number) used to identify an organization and receive the transaction.

String

Shortcode (5 to 6 digits) e.g. 654321

BillRefNumber

This is the account number for which the customer is making the payment. This is only applicable to Customer PayBill Transactions

String

An alpha-numeric value of up to 20 characters.

OrgAccountBalance

The current utility account balance of the payment-receiving organization shortcode. For validation requests, this field is usually blank whereas, for the confirmation message, the value represents the new balance after the payment has been received.

Decimal

30671

ThirdPartyTransID

This is a transaction ID that the partner can use to identify the transaction. When a validation request is sent, the partner can respond with ThirdPartyTransID and this will be sent back with the Confirmation notification

String

1234567890

MSISDN

This is a masked mobile number of the customer making the payment.

Numeric

25470****149

FirstName

The customer's first name is as per the M-Pesa register. This parameter can be empty.

String

John

MiddleName

The customer's middle name is as per the M-Pesa register. This parameter can be empty.

String

Doe


LastName

The customer's last name is as per the M-Pesa register. This parameter can be empty.

String







NB: Data minimization is a requirement from the data protection office not to share customers’ personal information without their consent.

Validation Response - Expected from your validation URL.

Name

Description

Type

ResultCode

A code indicating whether to complete the transaction. 0(Zero) always means complete. Other values mean canceling the transaction, which also determines the customer notification SMS type.

Alpha-numeric

ResultDesc

Short validation result description

String

ThirdPartyTransID

An optional value that can be used to identify the payment during a confirmation callback. If a value is set, it would be passed back in a confirmation callback.

String



Confirmation acknowledgment - Expected from your Confirmation URL.

Name

Description

Type

ResultCode

A code indicating the receipt status of the confirmation callback. Always 0(zero).

Number

ResultDesc

A short confirmation receipt description. Usually “Success”.

String

--------------------


Business To Customer (B2C)
Transact between an M-Pesa short code to a phone number registered on M-Pesa
POST
https://sandbox.safaricom.co.ke/mpesa/b2c/v3/paymentrequest
B2C API is an API used to make payments from a Business to Customers (Pay Outs), also known as Bulk Disbursements. B2C API is used in several scenarios by businesses that require to either make Salary Payments, Cashback payments, Promotional Payments(e.g. betting winning payouts), winnings, financial institutions withdrawal of funds, loan disbursements, etc.

Each scenario has its unique characteristics, but all lie under the B2C API category. Below is the B2C flow of transactions.


 

B2C API transaction process flow
The Merchant (Partner) sets all the required parameters the request and sends it to: https://sandbox.safaricom.co.ke/mpesa/b2c/v3/paymentrequest
API Management platform receives the request validates, authorizes and authenticates the partner to access the API, sends to M-PESA and an acknowledgement back to the Merchant(Partner).
M-PESA receives the request, validates the initiator details and processes the request.
M-PESA then sends the response back to the Merchant (partner) via the callback URL specified in your request.
M-PESA sends an SMS notification to the customer on the payments received.
NOTE: For you to use this API on production you are required to apply for a Bulk Disbursement Account and get a Short code, you cannot do this payment from a Pay Bill or Buy Goods (Till Number). To apply for a Bulk disbursement account follow this link. https://www.safaricom.co.ke/business/sme/m-pesa-payment-solutions

Important Information
Initiator Username: this is the API operator's username as set on the portal when the user was created. For Sandbox users, the username is already created and assigned to them and is available on the test credentials page  as InitiatorName.

Initiator Password: this is the password assigned to the API operator after being created by the Business Administrator. For Sandbox users, this is available as InitiatorPassword on the test credentials page . Note: the password should be limited to specific special characters such as '#', '&', '%' and '$'. Other characters might cause issues, and the password may not be accepted. For example, using a '(' or ')' character will not be accepted. In addition, '@' is not a special character on M-Pesa; it is treated as a normal character.

Public Key Certificate: this is the certificate used to encrypt the Initiator's plaintext password for use in the API calls. This is provided for both Sandbox and Production clients on the portal. You need to learn how to encrypt using your API language to be able to make API calls or find a way to encrypt beforehand and set the password as a static variable on the API call. The test credentials section offers the capability to encrypt your password.

Request Body
{    
   "OriginatorConversationID": "feb5e3f2-fbbc-4745-844c-ee37b546f627",
   "InitiatorName": "testapi",
   "SecurityCredential":"EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..",
   "CommandID":"BusinessPayment",
   "Amount":"10"
   "PartyA":"600996",
   "PartyB":"254728762287"
   "Remarks":"here are my remarks",
   "QueueTimeOutURL":"https://mydomain.com/b2c/queue",
   "ResultURL":"https://mydomain.com/b2c/result",
   "Occassion":"Christmas"
}
Request Parameter Definition
Name

Description

Parameter Type

Sample Values

OriginatorConversationID

This is a unique string you specify for every API request you simulate.

String

16740-34861180-1

InitiatorName

This is an API user created by the Business Administrator of the M-PESA Bulk disbursement account that is active and authorized to initiate B2C transactions via API.

String

initiator_1

John_Doe

John Doe

SecurityCredential

This is the value obtained after encrypting the API initiator password. The password on Sandbox has been provisioned on the simulator. However, on production the password is created when the user is being created on the M-PESA organization portal.

Alpha-numeric

32SzVdmCvjpmQfw3X2RK8UAv7xuhh304dXxFC5+3l

slkk2TDJY/Lh6ESVwtqMxJzF7qA==

CommandID

This is a unique command that specifies B2C transaction type.

SalaryPayment: This supports sending money to both registered and unregistered M-Pesa customers.
BusinessPayment: This is a normal business to customer payment, supports only M-PESA registered customers.
PromotionPayment: This is a promotional payment to customers. The M-PESA notification message is a congratulatory message. Supports only M-PESA registered customers.
Alphanumeric

SalaryPayment
BusinessPayment
PromotionPayment
Amount

The amount of money being sent to the customer.

Number

30671

PartyA

This is the B2C organization shortcode from which the money is sent from.

Number

Shortcode (5-6 digits) e.g. 123454

PartyB

This is the customer mobile number to receive the amount. - The number should have the country code (254) without the plus sign.

Phone number

Customer mobile number: 254722000000

Remarks

Any additional information to be associated with the transaction.

String

Sentence of up to 100 characters.

QueueTimeOutURL

This is the URL to be specified in your request that will be used by API Proxy to send notification incase the payment request is timed out while awaiting processing in the queue.

URL

https://ip or domain:port/path

ResultURL

This is the URL to be specified in your request that will be used by M-PESA to send notification upon processing of the payment request.

URL

https://ip or domain: port/path

Occassion

Any additional information to be associated with the transaction.

Alpha-numeric

Sequence of characters up to 100

Response Body
This is a synchronous notification sent out as soon as the request has been authorized, authenticated and accepted for processing. The response parameters are defined below.

{    
 "ConversationID": "AG_20191219_00005797af5d7d75f652",    
 "OriginatorConversationID": "16740-34861180-1",    
 "ResponseCode": "0",    
 "ResponseDescription": "Accept the service request successfully."
}
Response Parameter Definition
Name

Description

Parameter Type

Sample Value

OriginatorConversationID

This is a global unique identifier for the transaction request returned by the API proxy upon successful request submission.

String

AG_2376487236_126732989KJHJKH

ConversationID

This is a global unique identifier for the transaction request returned by the M-PESA upon successful request submission.

String

236543-276372-2

ResponseDescription

This is the description of the request submission status.

String

Accept the service request successfully

Error Response Body
This is a synchronous notification sent out as soon as the request has failed to go through. The response parameters are defined below

{    
   "requestId": "11728-2929992-1",
   "errorCode": "401.002.01",
   "errorMessage": "Error Occurred - Invalid Access Token - BJGFGOXv5aZnw90KkA4TDtu4Xdyf"
}
Error Response Parameter Definition
Name

Description

Parameter Type

Possible Values

requestId

This is a unique requestID for the payment request

String

16813-15-1

errorCode

This is a predefined code that indicates the reason for a request failure. This is defined in the Response Error Details below. The error codes map to specific error messages as illustrated in the Response Error Details below.

String

404.001.04

errorMessage

This is a short descriptive message of the failure reason.

String

Invalid Access Token
Results Body
Below is a sample results notification sent when a B2C payment request was not successful. Always note the ResultCode and ResultDesc whenever you receive an error. Follow this link for detailed error listing.

{
 "Result": {
    "ResultType": 0,
    "ResultCode": 2001,
    "ResultDesc": "The initiator information is invalid.",
    "OriginatorConversationID": "29112-34801843-1",
    "ConversationID": "AG_20191219_00006c6fddb15123addf",
    "TransactionID": "NLJ0000000",
    "ReferenceData": {
      "ReferenceItem": {
          "Key": "QueueTimeoutURL",
          "Value": "https:\/\/internalsandbox.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"
        }
    }
 }
}
Results Parameter Definition
The below parameters will be returned whether the request was successful or not.

Parameter

Description

Element Type

Sample Value

Result

This is the root parameter that encloses the entire result message.

JSON Object

"Result":{ }

ConversationId

This is a global unique identifier for the transaction request returned by the M-PESA upon successful request submission.

String

236543-276372-2

OriginatorConversationID

This is a global unique identifier for the transaction request returned by the API proxy upon successful request submission.

String

AG_2376487236_126732989KJHJKH

ResultDesc

This is a message from the API that gives the status of the request processing and usually maps to a specific result code value.

String



Service request is has been accepted successfully
Initiator information is invalid
ResultType

This is a status code that indicates whether the transaction was already sent to your listener. Usual value is 0.

Number

0

ResultCode

This is a numeric status code that indicates the status of the transaction processing. 0 means success and any other code means an error occurred or the transaction failed.

Number

0, 2001


TransactionID

This is a unique M-PESA transaction ID for every payment request. Same value is sent to customer over SMS upon successful processing.

String

LHG31AA5TX


Successful B2C Result
{    
   "Result": {
      "ResultType": 0,
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.", 
      "OriginatorConversationID": "10571-7910404-1",
      "ConversationID": "AG_20191219_00004e48cf7e3533f581",
      "TransactionID": "NLJ41HAY6Q",
      "ResultParameters": {
         "ResultParameter": [
          {
             "Key": "TransactionAmount",
             "Value": 10
          },
          {
             "Key": "TransactionReceipt",
             "Value": "NLJ41HAY6Q"
          },
          {
             "Key": "B2CRecipientIsRegisteredCustomer",
             "Value": "Y"
          },
          {
             "Key": "B2CChargesPaidAccountAvailableFunds",
             "Value": -4510.00
          },
          {
             "Key": "ReceiverPartyPublicName",
             "Value": "254708374149 - John Doe"
          },
          {
             "Key": "TransactionCompletedDateTime",
             "Value": "19.12.2019 11:45:50"
          },
          {
             "Key": "B2CUtilityAccountAvailableFunds",
             "Value": 10116.00
          },
          {
             "Key": "B2CWorkingAccountAvailableFunds",
             "Value": 900000.00
          }
        ]
      },
      "ReferenceData": {
         "ReferenceItem": {
            "Key": "QueueTimeoutURL",
            "Value": "https:\/\/internalsandbox.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"
          }
      }
   }
}
Successful Results Parameter Definition
Name

Description

Parameter Type

Sample Value

ResultParameters

This is a JSON object that holds more details for the transaction.

JSON Object

"Result":{

          "ResultParameters":{
}
}

ResultParameter

This is a JSON array within the ResultParameters that holds additional transaction details as JSON objects.

JSON Object



        "ResultParameters":{
        "ResultParameter":[
]
}}

TransactionReceipt

This is a unique M-PESA transaction ID for every payment request. The same value is sent to a customer over SMS upon successful processing. It is usually returned under the ResultParameter array.

String

LHG31AA5TX

TransactionAmount

This is the amount that is transacted. It is also returned under the ResultParameter array.

Number

100

B2CWorkingAccountAvailableFunds

This is the available balance of the Working account under the B2C shortcode used in the transaction.

Decimal

2000.0

B2CUtilityAccountAvailableFunds

This is the available balance of the Utility account under the B2C shortcode used in the transaction.

Decimal

23654.5


TransactionCompletedDateTime

This is the date and time that the transaction completed M-PESA.

String

01.08.2018 16:12:12


ReceiverPartyPublicName

This is the name and phone number of the customer who received the payment.

String

254722000000 - Safaricom PLC


B2CChargesPaidAccountAvailableFunds

This is the available balance of the Charges Paid account under the B2C shortcode used in the transaction.

Decimal

236543.9


B2CRecipientIsRegisteredCustomer

This is a key that indicates whether the customer is a M-PESA registered customer or not.

Errors
Error

Possible Cause

Mitigation

500.003.1001 Internal Server Error

Server failure	
Make sure everything on your side is correctly set up as per the API and you are calling the correct endpoints plus your server is running as expected

400.003.01 Invalid Access Token

Might be using a wrong or expired access token

Regenerate a new token and use it before expiry, if you are copy-pasting manually make sure you’ve pasted the correct access token.

400.003.02 Bad Request

The server cannot process the request because something is missing

Make sure everything on your side is correctly set up as per the API documentation.

500.003.03 Error Occurred: Quota Violation

You are sending multiple requests that violate M-PESA transaction per second speed

For testing, send a reasonable number of requests if possible one request at a time.

500.003.02 Error Occurred: Spike Arrest Violation

Your endpoints constantly generate a lot of errors that lead to a spike that affects our M-PESA performance

Make sure your endpoints/server is running and responding as expected by M-PESA and accessible over the internet.

404.003.01 Resource not found

The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.

Make sure you are calling the correct M-PESA API endpoint.

404.001.04 Invalid Authentication Header

All M-PESA APIs on the Daraja platform are POST except Authorization API which is GET. If you’ve possibly misplaced the headers you will get the error.

All M-PESA API requests on the Daraja platform are POST requests except Authorization API which is a GET request.

400.002.05 Invalid Request Payload

Your request body is not properly drafted

Make sure you are submitting the correct request payload as shown in the sample request body for all the APIs, avoid typo errors.


----------------------


Transaction Status
Check the status of a transaction
POST
https://sandbox.safaricom.co.ke/mpesa/transactionstatus/v1/query
Check the status of a transaction.

Request Body
{    
   "Initiator":"testapiuser",
   "SecurityCredential":"ClONZiMYBpc65lmpJ7nvnrDmUe0WvHvA5QbOsPjEo92B6IGFwDdvdeJIFL0kgwsEKWu6SQKG4ZZUxjC",
   "Command ID": "TransactionStatusQuery",
   "Transaction ID": "NEF61H8J60",
   "OriginatorConversationID":"AG_20190826_0000777ab7d848b9e721",
   "PartyA":"600782",
   "IdentifierType":"4",
   "ResultURL":"http://myservice:8080/transactionstatus/result",
   "QueueTimeOutURL":"http://myservice:8080/timeout",
   "Remarks":"OK",
   "Occasion":"OK",
}
Request Parameter Definition
Name

Description

Type

Sample Values

CommandID

Takes only the 'TransactionStatusQuery' Command ID.

String

TransactionStatusQuery

PartyA

Organization/MSISDN receiving the transaction

Numeric

Shortcode (6-9 digits) MSISDN (12 Digits)

IdentifierType

Type of organization receiving the transaction

Numeric

4 – Organization shortcode

 

Remarks

Comments that are sent along with the transaction

String

A sequence of characters up to 100

Initiator

The name of the initiator initiating the request.

Alpha-Numeric

This is the credential/username used to authenticate the transaction request

SecurityCredential

Encrypted credential of the user getting transaction status

String

Encrypted password for the initiator to authenticate the transaction request

QueueTimeoutURL

The path that stores information of timeout transaction

URL

https://ip:port or domain:port/path

TransactionID

Unique identifier to identify a transaction on Mpesa

Alpha-Numeric

LXXXXXX1234

ResultURL

The path that stores information of a transaction.

URL

https://ip:port/path or domain:port/path

Occasion

Optional parameter

String

A sequence of characters up to 100

Originator ConversationID

This is a global unique identifier for the transaction request returned by the API proxy upon successful request submission. If you don’t have the M-PESA transaction ID you can use this to query.

String

AG_20190826_0000777ab7d848b9e721

Response Body
{
    "OriginatorConversationID": "1236-7134259-1",
    "ConversationID": "AG_20210709_1234409f86436c583e3f ",
    "ResponseCode": "0"
    "ResponseDescription": "Accept the service request successfully."
}
Response Parameter Definition
Name

Description

Parameter Type

Sample Value

OriginatorConversationID

The unique request ID for tracking a transaction

Alpha-Numeric

Alpha-Numeric String of less than 20 characters e.g: 1236-7134259-1

ConversationID

The unique request ID returned my M-PESA for each request made

Alpha-Numeric

Alpha Numeric String of less than 20 characters e.g: AG_20210709_1234409f86436c583e3f

ResponseCode

The numeric status code indicates the status transaction processing. 0 means success and any other code means an error occurred or the transaction failed. Success submission message or an error description

Number

0 or 1 or or 2001 or 21

ResponseDescription

Response description message

String

Accept the service request  successfully

Results Body
{
   "Result": {
   "ConversationID":"AG_20180223_0000493344ae97d86f75",
   "OriginatorConversationID":"3213-416199-2",
   "ReferenceData": 
 {
    "ReferenceItem": 
 {
    "Key":"Occasion",
  }
  },
    "ResultCode": 0
     "ResultDesc":"The service request is processed successfully.",
    "ResultParameters": 
  {
      "ResultParameter": 
 [
 {
    "Key":"DebitPartyName",
    "Value":"600310 - Safaricom333",
 },
 {
    "Key":"DebitPartyName",
    "Value":"254708374149 - John Doe",
 },
 {
    "Key":"OriginatorConversationID",
    "Value":"3211-416020-3",
 },
 {
  "Key":"InitiatedTime",
    "Value":"20180223054112",
 },
 {
    "Key":"DebitAccountType",
    "Value":"Utility Account",
 },
 {
    "Key":"DebitPartyCharges",
    "Value":"Fee For B2C Payment|KES|22.40",
 },
 {
    "Key":"TransactionReason",
 },
 {
    "Key":"ReasonType",
    "Value":"Business Payment to Customer via API",
 },
 {
    "Key":"TransactionStatus",
   "Value":"Completed",
 },
 {
    "Key":"FinalisedTime",
    "Value":"20180223054112",
   },
 {
    "Key":"Amount",
    "Value":"300",
 },
 {
    "Key":"ConversationID",
    "Value":"AG_20180223_000041b09c22e613d6c9",
 },
 {
    "Key":"ReceiptNo",
    "Value":"MBN31H462N",
 }
 ]
 },
    "ResultType":0,
    "TransactionID":"MBN0000000",
 }
}
Results Parameter Definition
Name

Description

Type

Sample Values

ConversationID

The unique identifier generated by M-PESA for a request.

String

AG_20180223_0000493344ae97d86f75

OriginatorConversationID

The unique identifier of the request message. This is auto-generated by M-PESA for third-party/Organizations. Its value comes from the response message. It can be used to check the status of the transaction.

String

3213-416199-2

ReferenceData

It is used to carry some reference data that M-PESA need not analyze but need to record into the transaction log.

ReferenceData

n/a

ReferenceItem

it is used to carry some reference data that MM needs not analyze but needs to record in the transaction log.

ParameterType [1..unbounded]

n/a

ResultCode

It indicates whether M-PESA processes the request successfully or not. The max length is 10.

String

0

ResultDesc

Its value is a description of the parameter Result Code. The max length is 1024.

String

The service request is processed successfully.

ResultParameters

It is used to carry specific parameters for reversals API.

n/a

n/a

Key

It indicates a parameter name.

String

DebitPartyName

Value

It indicates a parameter value.

String

600310 - Safaricom333

ResultType

0: completed 1: waiting for further messages.

Integer

0

 

TransactionID

It’s only for transactions. When the request is a transaction request, M-PESA will generate a unique identifier for the transaction.

String

MBN0000000

Errors
Error

Possible Cause

Mitigation

500.003.1001 Internal Server Error

Server failure	
Make sure everything on your side is correctly set up as per the API and you are calling the correct endpoints plus your server is running as expected

400.003.01 Invalid Access Token

Might be using a wrong or expired access token

Regenerate a new token and use it before expiry, if you are copy-pasting manually make sure you’ve pasted the correct access token.

400.003.02 Bad Request

The server cannot process the request because something is missing

Make sure everything on your side is correctly set up as per the API documentation.

500.003.03 Error Occurred: Quota Violation

You are sending multiple requests that violate M-PESA transaction per second speed

For testing, send a reasonable number of requests if possible one request at a time.

500.003.02 Error Occurred: Spike Arrest Violation

Your endpoints constantly generate a lot of errors that lead to a spike that affects our M-PESA performance

Make sure your endpoints/server is running and responding as expected by M-PESA and accessible over the internet.

404.003.01 Resource not found

The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.

Make sure you are calling the correct M-PESA API endpoint.

404.001.04 Invalid Authentication Header

All M-PESA APIs on the Daraja platform are POST except Authorization API which is GET. If you’ve possibly misplaced the headers you will get the error.

All M-PESA API requests on the Daraja platform are POST requests except Authorization API which is a GET request.

400.002.05 Invalid Request Payload

Your request body is not properly drafted

Make sure you are submitting the correct request payload as shown in the sample request body for all the APIs, avoid typo errors.


