fbpx

SIGN IN YOUR ACCOUNT TO HAVE ACCESS TO DIFFERENT FEATURES

FORGOT YOUR PASSWORD?

FORGOT YOUR DETAILS?

AAH, WAIT, I REMEMBER NOW!
QUESTIONS? CALL: 0721606035
  • LOGIN

BILTMAP LIMITED

BILTMAP LIMITED

We are a top Digital Agency and web design company in Kenya that provides best ICT solutions, products, and services using ultra-modern technologies.

T (+254) 721 606 035
Email: sales@biltmap.com

BILTMAP LIMITED
AMBASSADOR COURT, JAKAYA KIKWETE ROAD.

Open in Google Maps
  • Home
  • About Us
  • What We Do
  • Blog
  • Contact Us
FREEQUOTE
  • Home
  • Mobile
  • Archive from category "Mobile"
January 1, 2021

Category: Mobile

Using Instagram For Restaurant Marketing

Thursday, 19 March 2020 by admin
instagram

As a restaurant owner, we hope you can smell the fragrance of opportunity that these numbers are bringing to you. An opportunity for cost-effective advertising, to connect and engage with your current and potential customers in a language they speak. So it is clear as a restaurant business you have to be on Instagram! Let us help you understand how to use it to maximize your marketing efforts and eventually profits.

Flaunt your chef: Chefs are cool. Your customers and followers love to see a real person who works up the magic to create those foodgasmic dishes that your restaurant serves. Share behind the scenes pictures of your restaurant’s kitchen on your Instagram account. Your Instagram community will gobble down your staff pics as readily as they gobble your food.

Plan and project an authentic journey of your restaurant: Instagrammers love authenticity so stay true to your brand identity. Try to maintain consistency with your restaurant’s theme, food category and customer preferences. A healthy food restaurant has no business posting a pic which gives a beer and pizza lover kind of vibe. They also love a brand that values their opinions. We suggest creating a weekly Instagram marketing plan in advance. Mondays can be quirky question day, “Which is your favourite dish on our menu?”, you can devote posts to Throwback Thursdays or Fun Fridays, Saturdays can be for contests.

Special of the day pics never fail: We can’t overstate this recommendation. Put up a pic of the specials. It seems so simple, right? You will be surprised at how many customers come and order the special that same evening. This also allows you to measure if your social media efforts are paying up. You can put a call to action like a coupon code along with your specials picture, and observe how many customers use it. Don’t forget to use an intriguing caption and relevant hashtags, though.

speacial pics

Add a sprinkle of Influencer Marketing: There is a famous saying by chef Julia Child: “People who love to eat are always the best people.” If that is the case Food bloggers are rockstars indeed. You can invite a food blogger for a free meal to your restaurant, or pay them per Instagram post for some authentic publicity. Food lovers trust this source of information and a good review or even a mere mention of your restaurant by a famous food blogger can give your marketing efforts a tremendous boost. Search for social media influencers that are relevant to your restaurant business, check if their posts are engaging. Connecting with them is easy, they are usually just an instant message away.

content

User-generated content is Instagram gold: There are a million ways you can do this. Put up a pic of a new dish that has just been added to your restaurant’s menu, now ask Instagram users to ‘Name the dish’. Ask Instagrammers to take a picture of their meal taken at the restaurant and post it along with an actionable hashtag (preferably a restaurant name hashtag), hold a contest around it and award the winner with a free meal. Add your Instagram account name and hashtags on the restaurant menu, this will act as a simple nudge, a gentle reminder to share their photos online. Integrate user reviews and ratings in the menu itself, customers love social proof when ordering food.

Be #hashtagwise and time it right: Hashtags can be tricky but if used strategically they can bear real rewards for your business’s bottom line. You might have to do a lot of A/B testing before getting the #hashtag game right. We suggest you try to create a perfect mixture of hashtags, the time-tested classic ones like #foodie, #foodgasm, #foodporn, #foodaddict, #instafood, #yummy along with newer unique hashtags centred around your restaurant or a current event like #glutenfreeweek or #vegandesserts. Always add your restaurant’s name as a consistent hashtag in all your posts, it helps enhance brand recall. Another important factor to remember is the time to post on Instagram. For example, the best time to reach dinner crowds would be to post around 5­6 pm when most people leave their offices and are making dinner plans.

Word of caution though this is not an overnight success kind of social media platform, in our opinion no platform is. Instagram efforts reap benefits slowly, but it is worth the wait. Most restaurant businesses are using Instagram for unabashed, in your face kind of advertising. Remember the golden rule of Instagram is not to advertise but ENGAGE.

Read more
  • Published in Mobile, Networking, Technology
No Comments

Safaricom Daraja API Tutorial

Saturday, 22 August 2015 by admin
Guide-to-Mpesa-integration

Generate Token

This API generates the tokens for authenticating your API calls. This is the first API you need to engage within the set of APIs available as all the other APIs require the information from this API to work.

The API works as below:

  1. 1. Get the Base-64 encoding of Consumer Key + “:” + Consumer Secret (note the full colon in the encoding and without the quotes)
  2. 2. Create a GET request and set an Authentication header with the value as Basic + encoded value from above step e.g. using the Consumer Credentials above, the header will beAuthorization: Basic
  3. 3. Send the request to the endpoint https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials. The raw request will look similar to the following :
    GET /oauth/v1/generate?grant_type=client_credentials HTTP/1.1
    Host: sandbox.safaricom.co.ke
    Authorization: Basic U1BMd0xkMnVBM29ub1BSWENKRjZiV3FXR3hOdkE4Qlo6NldPZ2hNQUdUdUVZS2pYMw==
    Content-Type: application/json
    
  4. 4. You will get a response in the sample format shown below. This shows your token and how long it will take before it expires.
    {
    	"access_token": "[access_token]",
    	"expires_in": "3599"
    }
    

Once generated, you somehow need to keep track of the timeout period so it does not expire unknowingly. This means you need to either generate a new token for every request you make or keep a timer variable somewhere and keep checking it. That’s up to you. But know that when you get the “Invalid Access Token” error, your Auth token has expired or is not set. Get a new one.

Register URL

The first API we shall look at is the Register URL API under Consumer to Business (C2B) APIs. It is the first half of the C2B API for receiving payment notifications to your paybill. This API enables you to register the callback URLs via which you shall receive payment notifications for payments to your paybill/till number. The URLs are used by the C2B payment simulation API for sending the transaction details to you.

There are two URLs required for RegisterURL API: Validation URL and Confirmation URL. The reason for two of them is due to the nature of C2B API calls. Below is a flowchart of the C2B process:

C2B Flow

C2B transaction flow

The process is explained as below:

  1. A customer sends a payment request to your paybill from their phone
  2. M-Pesa receives the request and validates it internally first
  3. M-Pesa then checks if you have enabled External Validation for the paybill receiving the request
  4. If External Validation is enabled:
    1. M-Pesa first sends a Validation request to the Validation URL registered in the system (3rd party) with the payment details.
    2. The 3rd Party validates the request and sends an appropriate response to M-Pesa. This response must be received within a given time period or M-Pesa marks the endpoint system as unreachable. The response informs M-Pesa to either complete or cancel the payment:
    3. M-Pesa receives the response and processes the transaction accordingly:
    4. If you had chosen 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.
    5. If you had chosen to cancel the payment, M-Pesa simply cancels the transaction and no other request is sent. The transaction is then complete
  5. 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.
  6. 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 -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.
  7. If no URLs are registered in the system, M-Pesa automatically completes the request.
  8. M-Pesa then sends an SMS notification to both the customer and paybill owner with the results of the transaction as usual.
  9. When the external notifications fail to be sent, you can check on the M-Pesa Org portal and cross-check against received callbacks. The portal has all the payments ever made available, whether you received the callback or not. Manual, but necessary once in a while.

For the two URLs, below are some pointers. These will also apply to the Callback URLs we shall use later on in other APIs:

  1. – Use publicly available (Internet-accessible) IP addresses or domain names.
  2. – Do not use the words MPesa, M-Pesa, Safaricom or any of their variants in either upper or lower cases in your URLs, the system filters these URLs out and blocks them. Of course, any Localhost URL will be refused.
  3. – Do not use public URL testers e.g. ngrok, mockbin or requestbin especially on production, they are also usually blocked by the API.
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 to the M-Pesa Support or API Support team if they need their transactions validated before execution.

The request structure will be as shown below:

// URL
[POST] https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl

// HEADERS
Host: sandbox.safaricom.co.ke
Authorization: Bearer [access token]
Content-Type: application/json

// BODY
{
	"ShortCode": "601426",
	"ResponseType": "[Cancelled/Completed]",
	"ConfirmationURL": "[confirmation URL]",
	"ValidationURL": "[validation URL]"
}

The other parameters are:

Shortcode
This is your C2B-enabled paybill number/till number, which you expect to receive payment notifications about.
Response Type
This is the default action value that determines what M-Pesa will do in the scenario that your Validation 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.

Then a success response will look like the one below:

{
	"ConversationID": "",
	"OriginatorCoversationID": "",
	"ResponseDescription": "success"
}

Anything else other than the above means there is an error, check error description and fix it if it’s your error. I will cover some common errors encountered on the portal later on in a different section as I compile them one by one from the APIs.

Unfortunately, there is no way to check which URLs are currently registered on the system, or whether the URLs were actually registered in the first place. You can only confirm by performing C2B requests and checking if the registered endpoints are hit or not. Otherwise you can get in touch with the support team and enquire which URLs are currently under your paybill on the system

Also, it is good to know the relationship between shortcodes and the URLs. One paybill can only have one pair of URLs under it, but the same pair of URLs can be used by multiple paybill numbers for transaction notifications. That means it will be up to you to differentiate requests for different paybills.

NB: For this API,and the C2B API below, please test using your own test paybill assigned to you. Most probably, by the time you register your URLs with my paybill above, then get down to testing on the C2B section, someone else will have overwritten your URLs with their own URLs. Then you will be left scratching your head as to why “M-Pesa is not calling my endpoints”.

And that’s pretty much it for Register URL API.

C2B API

This API is used to simulate payment requests from clients and to your API. It basically simulates a payment made from the client phone’s STK/SIM Toolkit menu, and enables you to receive the payment requests in real time. It is the second half of the Register URL API covered above, and requires the URLs registered by the previous API to work. Hopefully you have gone through the previous section to understand how the C2B payment process works, as both are tied to each other. If not, please do, I can wait…

Welcome back. Moving on, the basic C2B request looks like the sample below:

// URL
[POST] https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate

// HEADERS
Host: sandbox.safaricom.co.ke
Authorization: Bearer [access token]
Content-Type: application/json

// BODY
{
    "ShortCode": "601426",
    "CommandID": "CustomerPayBillOnline",
    "Amount": "100",
    "Msisdn": "254708374149",
    "BillRefNumber": "account"
}

These are explained below:

Shortcode
This is your paybill number/till number, which you expect to receive payments notifications about.
CommandID
This is a transaction type identifier, which Identifies the type of C2B transaction being made. There are two options: CustomerPayBillOnline and CustomerBuyGoodsOnline. CustomerPayBillOnline is used when simulating Pay Bill requests, which the customer does by going to the M-PESA -> Lipa na M-PESA -> Pay Bill option on mobile, and uses a Paybill/Store number. Thus it requires an Account number/Bill reference number for it to be valid. CustomerBuyGoodsOnline is used for Buy Goods simulation, which is when a customer goes to M-PESA -> Lipa na M-PESA -> Buy Goods and Services on their mobile phones and uses a Till number. This does not require a paybill number, and putting one actually causes the request to fail. Beware that you cannot use a Till number with CustomerPayBillOnline command ID and you cannot use a Pay Bill/Store number with CustomerBuyGoodsOnline Command ID. As of now, I can only see the paybill number provided on the portal, there is no Till number, so the CustomerBuyGoodsOnline command ID might not work as expected, and you might not receive callbacks if you use it since the payment might automatically fail on the backend. But am still going to provision for it here.
Msisdn
This is the test phone number of the virtual customer paying to your paybill. Use the one given in your test credentials section (Test MSISDN) to test. Testing using your own phone numbers will not work with this API since the numbers need to be registered on the testbed first. The number should either begin with 07XX or 2547XX (for now). International numbers are not supported.
BillRefNumber
This simulates the account number that a user would have entered when making a Pay Bill request. This parameter is only required for CustomerPayBillOnline transaction type. It is sent as part of the validation and confirmation requests to you (3rd party) to validate and confirm. It has a maximum of 20 characters.

After sending the request, and assuming you have all the correct details, the success response should be the acknowledgement below:

{
	"ConversationID": "AG_20180324_000066530b914eee3f85",
	"OriginatorCoversationID": "25344-885903-1",
	"ResponseDescription": "Accept the service request successfully."
}

The above response shows that your request has been accepted, and will be processed. The two ‘ConversationID’s are unique identifiers of your transaction’s journey on M-Pesa. M-Pesa itself processes transaction in <~8 seconds, thus, adding 1-2 seconds of network delays and communication, it should take no more than 10 seconds for the validation/confirmation request to hit your endpoint. If it is consistently above that, please check for network or processing delays around your system.

For those who have enabled External Validation, you will first receive a validation request on your Validation URL to validate the request. That request will have the structure below:

NB: For those unfamiliar with callbacks, all API callbacks from transactional requests are POST requests, do not expect GET requests for callbacks. Also, the data is not formatted into application/x-www-form-urlencoded format, it is application/json, so do not expect the data in the usual POST fields/variables of your language, read the results directly from the incoming input stream.

[POST] https://yourdomain.co.ke/your/validation/url

// HEADERS
Content-Type: application/json

// BODY
{
    "TransactionType": "",
    "TransID": "LHG31AA5TX",
    "TransTime": "20170816190243",
    "TransAmount": "200.00",
    "BusinessShortCode": "601426",
    "BillRefNumber": "account",
    "InvoiceNumber": "",
    "OrgAccountBalance": "",
    "ThirdPartyTransID": "",
    "MSISDN": "254708374149",
    "FirstName": "John",
    "MiddleName": "",
    "LastName": "Doe"
}
TransID
This is M-Pesa’s unique transaction identifier for your transaction. This can be used for searching for the transaction later on using the Transaction Query API.
TransTime
Simply the time the transaction was completed on M-Pesa in the format YYYYMMddHHmmss (https://en.wikipedia.org/wiki/Date_format_by_country).
TransAmount
The amount transacted by the customer when paying to your paybill/till.
BusinessShortCode
The shortcode to which the customer paid to. This can be used to differentiate payments to different paybills via the same notification URLs.
BillRefNumber
The account number the customer entered on their phone when making the payment. Applicable to PayBill requests.
MSISDN
The phone number from which the payment was made.
FirstName, MiddleName, LastName
The names of the customer under whom the MSISDN above is registered. The First Name and Last Name are usually mandatory. The Middle Name is optional.

After receiving the request, you are supposed to process it and respond to the API call with either an accept or reject response. To accept, you send the below JSON making sure the value of ResultCode is 0 (zero, must be a literal Integer, not a String like “0”), but the value of ResultDesc can be any alphanumeric value.

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

To reject a transaction, you send the same JSON above, but with the value of ResultCode being any integer EXCEPT 0, as shown below

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

So, basically, sending a ResultCode value of 0 means you accept the transaction, and sending anything else rejects the transaction. Values below 0 are not accepted, and also constitute a rejection.

If transaction has been accepted, M-Pesa will complete the transaction and send a Confirmation request to you. This will have the same structure and values as the Validation request JSON above. This also applies for those who have disabled External Validation. You may respond to the Confirmation request with the JSON below. If you cancel the transaction, no Confirmation will be sent to you. Beware that you cannot cancel a transaction after the Confirmation request has been sent to you. Confirmation marks the completion of the transaction on M-Pesa.

	{
		"C2BPaymentConfirmationResult": "Success"
	}

That marks the end of the C2B transaction. If you find out that M-Pesa is not getting to you, or that your systems are not receiving payment notifications, you can always fall back to the M-Pesa Org Portal to confirm the transactions were received and processed as required.

Caveat: please disconnect your shortcode from the old Soap API before using it on the new API if you are planning to migrate the shortcode. The settings from the old API could really mess up your integration in the new API. Make sure to delete the registered C2B URLs from the old System by placing a request with the Support team to have them deleted. This will also apply to the Lipa Na M-Pesa API.
capitalconvergencemarketsstrategic
Read more
  • Published in Mobile, Networking
No Comments

Mpesa Integration B2B

Friday, 21 August 2015 by admin
Guide-to-Mpesa-integration
NB:
As of January 2019, the B2B API has been disabled on the Daraja API. Thus this section is here for historical purposes only. The test API requests will most probably not work if tried out. The main way left to perform B2B transfers is now via the M-Pesa Org portal or via the API at proxyapi.co.ke

The Business to Business (B2B) API enables a Business or Organization to perform transactions between each other. The transaction flow is the same as the B2C API transaction flow, but this time the Credit Party is another Business/Company/Organization. It requires the same credentials and information as the B2C API.

Currently the B2B API allows an organization to perform 5 types of transfers:

  • Business Pay Bill: This is a transfer of funds from one Organization’s Working Account to another Organization’s Utility Account.
  • Business Buy Goods: A transfer of funds from one Organization’s Working Account to another Organization’s Merchant Account.
  • Disburse Funds To Business: A transfer of funds from one Organization’s Utility Account to another Organization’s Working Account.
  • Business To Business Transfer: A transfer of funds from one Organization’s Working Account to another Organization’s Working Account.
  • Merchant To Merchant Transfer: A transfer of funds from one Organization’s Merchant Account to another Organization’s Merchant Account.

For any two shortcodes to perform B2B transactions between themselves, they both need to have the B2B product assigned to them, otherwise the transaction request will fail. The B2B request structure is as shown below:

// URL
[POST] https://sandbox.safaricom.co.ke/mpesa/b2b/v1/paymentrequest

// HEADERS
Host: sandbox.safaricom.co.ke
Authorization: Bearer [access token]
Content-Type: application/json

// BODY
{
	"Initiator": "apitest361",
	"SecurityCredential": "[encrypted password]",
	"CommandID": "[CommandID]",
	"SenderIdentifierType": "4",
	"RecieverIdentifierType": "4",
	"Amount": "100000",
	"PartyA": "601426",
	"PartyB": "254708374149",
	"AccountReference": "",
	"Remarks": "",
	"QueueTimeOutURL": "https://peternjeru.co.ke/safdaraja/api/callback.php" ,
	"ResultURL": "https://peternjeru.co.ke/safdaraja/api/callback.php"
}

These are explained below:

Initiator
The username of the API operator as assigned on the M-Pesa Org Portal.
SecurityCredential
The password of the API operator encrypted using the public key certificate provided.
CommandID
This specifies the type of transaction being performed. There are five allowed values on the API: BusinessPayBill, BusinessBuyGoods, DisburseFundsToBusiness, BusinessToBusinessTransfer or MerchantToMerchantTransfer.
SenderIdentifierType, RecieverIdentifierType
This is the type of Identity performing the transaction. An organization’s Identity type for a shortcode (identity being used in the request) is 4, thus for both the above parameters, the value will always be 4 for B2B transfers (NB: you cannot use Till numbers in B2B transfers).
PartyA
This is the identifier of the Debit party of the transaction, in this case the debit party being the Organization and the identifier being the Shortcode of the organization.
PartyB
This is the identifier of the Credit party of the transaction, here the credit party being another organization and the identifier being the other org’s shortcode.
AccountReference
This is a custom value that may represent an account or unique value item being paid for. It is only required for the BusinessPayBill Command ID.
Remarks
A very short description of the transaction from your end, or just a minimum of 2 characters.
ResultURL
This is the callback URL where the results of the transaction will be sent. Please visit the API Apps section to understand how this is used if you are not familiar with it.
QueueTimeOutURL
This is the callback URL used to send an error callback when the transaction was not able to be processed by M-Pesa within a stipulated time period.

Once sent, you shall expect a success acknowledgement response from the API informing you that your request was accepted. The response format is as below:

{
    "ConversationID": "AG_20180326_00005ca7f7c21d608166",
    "OriginatorConversationID": "12363-1328499-6",
    "ResponseCode": "0",
    "ResponseDescription": "Accept the service request successfully."
}

From here, process is the same as the B2C flow. A sample success B2B callback is shown below:

{
    "Result":
    {
        "ResultType":0,
        "ResultCode":0,
        "ResultDesc":"The service request has been accepted successfully.",
        "OriginatorConversationID":"8551-61996-3",
        "ConversationID":"AG_20170727_00006baee344f4ce0796",
        "TransactionID":"LGR519G2QV",
        "ResultParameters":
        {
            "ResultParameter":
            [
                {
                    "Key":"InitiatorAccountCurrentBalance",
                    "Value":"{ Amount={BasicAmount=46713.00, MinimumAmount=4671300, CurrencyCode=KES
                    }}"
                },
                {
                    "Key":"DebitAccountCurrentBalance",
                    "Value":"{Amount={BasicAmount=46713.00, MinimumAmount=4671300, CurrencyCode=KES}}"
                },
                {
                    "Key":"Amount",
                    "Value":10
                },
                {
                    "Key":"DebitPartyAffectedAccountBalance",
                    "Value":"Working Account|KES|46713.00|46713.00|0.00|0.00"
                },
                {
                    "Key":"TransCompletedTime",
                    "Value":20170727102524
                },
                {
                    "Key":"DebitPartyCharges",
                    "Value":"Business Pay Bill Charge|KES|77.00"
                },
                {
                    "Key":"ReceiverPartyPublicName",
                    "Value":"603094 - Safaricom3117"
                },
                {
                    "Key":"Currency",
                    "Value":"KES"
                }
            ]
        },
        "ReferenceData":
        {
            "ReferenceItem":
            [
                {
                    "Key":"BillReferenceNumber",
                    "Value":"aaa"
                },
                {
                    "Key":"QueueTimeoutURL",
                    "Value":"https://internalsandbox.safaricom.co.ke/mpesa/b2bresults/v1/submit"
                }
            ]
        }
    }
}

Some new elements descriptions:

ReceiverPartyPublicName
The Shortcode + Registered Name of the organization being credited in the transaction.
DebitPartyCharges
How much the debit party is being charged for the transfer.

For an unsuccessful transaction, the response format will be the same as the B2C callback, and follows the same rules.

That is pretty much B2B in a nutshell.

capitalmarkets
Read more
  • Published in Mobile
No Comments

Lipa Na M-Pesa Online API

Friday, 07 August 2015 by admin
Guide-to-Mpesa-integration

The Lipa na M-Pesa (LNM) API is a C2B API designed to utilize the new feature introduced by Safaricom known as STK Push. This feature allows the transaction initiation to be moved from the paying customer’s side to the payee Organization’s side. This eliminates the hustle of having to remember business paybill numbers and account numbers for customers, and allows them to simply confirm the current transaction by entering their M-Pesa PIN on their mobile phone. This is done via the STK Push prompt which appears on a customer’s phone that asks them to enter their PIN. For businesses, this API enables them to preset all the correct info in the payment request and greatly reduce chances of wrong payments being sent to their systems. It is a C2B transaction, but with the initiator being the organization instead of the customer. Here, the organization has the option of presetting all required variables in the request before sending the request, thus this API has no Validation-Confirmation process of it’s own unlike the previous C2B API (but is still affected by any previous C2B integrations done on the shortcode being used in the request, especially Validation/Confirmation). It’s process is explained below together with a flow chart:

STK Push Flow

STK Push transaction flow

  1. The Business sets the data in the request and sends it
  2. The API receives the request and validates it internally first, then sends you an acknowledgement response.
  3. The API then sends an STK Push request to the target customer’s mobile phone. The customer’s phone has to be online and unlocked to receive the request.
  4. The customer confirms the payment amount via the message displayed on-screen, then either enters the PIN or cancels the request accordingly.
  5. The API receives the customer’s response. If the response is a negative, it cancels the transaction and sends a corresponding callback to the initiating 3rd party via the predefined callback URL in the initial request, with the info on why the transaction was cancelled. The possible negative responses could be due to the following scenarios:
    • An invalid PIN entered by the customer
    • Timeout due to customer not entering the PIN within a given time period (usually 1 min 30 secs)
    • The customer’s SIM card not having the STK applet on it
    • A literal request cancellation by the user on their phone
    • Another STK transaction is already underway on the customer’s phone (no more than one request can be processed at the same time on the same phone)
  6. If the PIN is correct, it means the customer accepted the request. The API forwards the transaction to M-Pesa.
  7. M-Pesa automatically processes the request, then sends the response back to the API system which then forwards it to you via the callback URL specified in your initial request. Here, the callback can also either be a success or failure, just like a normal C2B transaction.
  8. There are no repeat calls for failed callbacks, thus if the API is unable to send the callback to you, you have the Transaction Status Query API to confirm the status of the request, or also confirm via the M-Pesa Org. portal.

For this API, you shall need your actual production line to test the API. Your line must have the STK applet installed (you can update by dialing *234*1*6# on your handset (as of the day of writing of this tutorial. If the update does not work, or your physical SIM card is more than 3 years old, consider replacing it), and you must be registered on M-Pesa. The funds utilized are automatically refunded at midnight. I suggest using values as low as 1 – 10 shillings to perform your transactions to lengthen the number of tries you make. Also beware, the API does not allow one to perform more than 5 consecutive STK requests without completing them. This is marked as phishing, and will cause your line to be blocked from making any more STK requests over 24 hours.

The LNM request takes the format below:

// URL
[POST] https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest

// HEADERS
Host: sandbox.safaricom.co.ke
Authorization: Bearer [access_token]
Content-Type: application/json

// BODY
{
	"BusinessShortCode": "174379",
	"Password": "MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMTkxMTI0MTkyMjEx",
	"Timestamp": "20191124192211",
	"TransactionType": "[Transaction Type]",
	"Amount": "1000",
	"PartyA": "254708374149",
	"PartyB": "174379",
	"PhoneNumber": "254708374149",
	"CallBackURL": "https://peternjeru.co.ke/safdaraja/api/callback.php"
	"AccountReference": "account",
	"TransactionDesc": "test" ,
}

Some definitions

BusinessShortCode
This is the shortcode of the organization initiating the request and expecting the payment.
Password
This is the Base64-encoded value of the concatenation of the Shortcode + LNM Passkey + Timestamp, e.g. given the test values above, and using a timestamp of 20191124192211, the encoded password will be

MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMTkxMTI0MTkyMjEx

You can use this site to confirm your encoding.

Timestamp
This is the same Timestamp used in the encoding above, in the format YYYMMDDHHmmss.
TransactionType
The type of transaction being performed. These are the same values as the C2B command IDs (CustomerPayBillOnline and CustomerBuyGoodsOnline) and the same rules apply here. For now, only CustomerPayBillOnline is supported.
Amount
Self explanatory.
PartyA
The Debit party of the transaction/the party paying out in the transaction, hereby the phone number of the customer.
PartyB
The credit party of the transaction/the party being paid in the transaction, hereby being the shortcode of the organization. This is the same value as the Business Shortcode
PhoneNumber
Same as PartyA.
CallBackURL
This is the endpoint where you want the results of the transaction delivered. Same rules for Register URL API callbacks apply
AccountReference
This is the value the customer would have put as the account number on their phone if they had performed the transaction via phone.
TransactionDesc
Short description of the transaction. Optional, but element must be present.

After sending a successful transaction, you can expect a response in the below format:

{
    "MerchantRequestID": "25353-1377561-4",
    "CheckoutRequestID": "ws_CO_26032018185226297",
    "ResponseCode": "0",
    "ResponseDescription": "Success. Request accepted for processing",
    "CustomerMessage": "Success. Request accepted for processing"
}

Note the ResponseCode. The value 0 (zero) means the request was accepted successfully. Any other value means there was an error validating your request. Confirm the error on the ResponseDescription and fix it. The CheckoutRequestID is your unique request ID and can be used later for the LNM Transaction Query API.

After sending the callback, and assuming a customer has accepted your request and responded to it, a successful callback will have the structure below:

{
	"Body": 
	{
		"stkCallback": 
		{
			"MerchantRequestID": "21605-295434-4",
			"CheckoutRequestID": "ws_CO_04112017184930742",
			"ResultCode": 0,
			"ResultDesc": "The service request is processed successfully.",
			"CallbackMetadata": 
			{
				"Item": 
				[
					{
						"Name": "Amount",
						"Value": 1
					},
					{
						"Name": "MpesaReceiptNumber",
						"Value": "LK451H35OP"
					},
					{
						"Name": "Balance"
					},
					{
						"Name": "TransactionDate",
						"Value": 20171104184944
					},
					{
						"Name": "PhoneNumber",
						"Value": 254727894083
					}
				]
			}
		}
	}
}

I believe all elements there are already known. I will shift your attention to the ResultCode,which shows the status of the request. The 0 (zero) means a success as usual, anything else will be an error whose description is defined in ResultDesc. The M-Pesa Receipt Number is your unique identifier of the transaction on M-Pesa, and can be used with the Sandbox Transaction Query API.

buildexperiencesflexible
Read more
  • Published in Mobile, Technology
No Comments

Mpesa Integration Reversal API

Friday, 07 August 2015 by admin
Guide-to-Mpesa-integration

According to the documentation, this API enables one to reverse a transaction done. But there are some limitations to this I believe you need to know:

  • You will probably only be able to reverse a transaction where you are the credit party. When you are the debit party, you may not be able to initiate a reversal via API. This means it will be done via the Web portal, and may require manual authorization from the SP side. But if you are allowed to reverse a transaction via API, it may also need to be authorized from the SP side. This means you will only get the callback after the SP has reviewed and completed processing the transaction on their side, which can be a couple of hours. Otherwise you are good
  • Obviously the reversal is dependent on the funds being available in the originally credited account. If there are no funds in the originally credited account, the reversal fails.
  • Charges accrued during the transaction will most probably not be reversed.
  • You cannot reverse a reversal transaction.
  • Any C2B transaction reversal that will cause the customer’s account to exceed the maximum allowed account limit (100K) or Daily transaction limits will be declined. If possible notify the customer beforehand.
  • Not a limitation but a requirement: an initiator needs the Org Reversals Initiator role to be able to perform reversals via API.

The reversal request format is as below:

// URL
[POST] https://sandbox.safaricom.co.ke/mpesa/reversal/v1/request

// HEADERS
Host: sandbox.safaricom.co.ke
Authorization: Bearer [access token]
Content-Type: application/json

// BODY
{
	"Initiator":"apitest361",
	"SecurityCredential":"[encrypted password]",
	"CommandID":"TransactionReversal",
	"TransactionID":"[original trans_id]",
	"Amount":"[trans amount]",
	"ReceiverParty":"601426",
	"RecieverIdentifierType":"4",
	"ResultURL":"https://peternjeru.co.ke/safdaraja/api/callback.php",
	"QueueTimeOutURL":"https://peternjeru.co.ke/safdaraja/api/callback.php",
	"Remarks":"please",
	"Occasion":"work"
}

Important parameters:

TransactionID
This is the M-Pesa Transaction ID of the transaction which you wish to reverse.
Amount
The amount transacted in that transaction to be reversed, down to the cent.
ReceiverParty
Your Org’s shortcode here.

A successful callback will be as shown below:

{
	"Result":
	{
		"ResultType":0,
		"ResultCode":0,
		"ResultDesc":"The service request has been accepted successfully.",
		"OriginatorConversationID":"10819-695089-1",
		"ConversationID":"AG_20170727_00004efadacd98a01d15",
		"TransactionID":"LGR019G3J2",
		"ReferenceData":
		{
			"ReferenceItem":
			{
				"Key":"QueueTimeoutURL",
				"Value":"https://internalsandbox.safaricom.co.ke/mpesa/reversalresults/v1/submit"
			}
		}
	}
}

Note the TransactionID. This is the transaction ID of the reversal request itself, not the original transaction which was being reversed. The reversal request itself gets its own transaction ID.

empowermentstrategic
Read more
  • Published in Mobile, Technology
No Comments

Recent Posts

  • instagram

    Using Instagram For Restaurant Marketing

    As a restaurant owner, we hope you can smell th...
  • Guide-to-Mpesa-integration

    Mpesa Integration B2C

    Also known as the Bulk Payment API, the Busines...
  • Guide-to-Mpesa-integration

    Safaricom Daraja API Tutorial

    Generate Token This API generates the tokens fo...
  • Guide-to-Mpesa-integration

    Mpesa Integration B2B

    NB: As of January 2019, the B2B API has been di...
  • Guide-to-Mpesa-integration

    Lipa Na M-Pesa Online API

    The Lipa na M-Pesa (LNM) API is a C2B API desig...

Recent Comments

    Archives

    • March 2020
    • November 2019
    • August 2015

    Categories

    • Mobile
    • Networking
    • Technology
    • Uncategorized

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org

    Featured Posts

    • instagram

      Using Instagram For Restaurant Marketing

      0 comments
    • Guide-to-Mpesa-integration

      Mpesa Integration B2C

      0 comments
    • Guide-to-Mpesa-integration

      Safaricom Daraja API Tutorial

      0 comments
    • Guide-to-Mpesa-integration

      Mpesa Integration B2B

      0 comments
    • Guide-to-Mpesa-integration

      Lipa Na M-Pesa Online API

      0 comments

    GET A FREE QUOTE

    Please fill this for and we'll get back to you as soon as possible!

    Quick Links

    • Home
    • About Us
    • What We Do
    • Blog
    • Contact Us

    GET IN TOUCH

    T (254) 721606035
    Email: info@biltmap.com

    BILTMAP LIMITED
    4329-00100 Nairobi

    Open in Google Maps

    logo
    • GET SOCIAL

    © 2019 All rights reserved. BILTMAP LIMITED.

    TOP