Few months ago,we looked on how to integrate mpesa oauth api using c#.The guide looked on how to integrate mpesa oauth api as part of the api parameters required to generate token for accessing other api resources.If you did not go through the previous guide,i prefer you have a look at it here:-https://sandekennedy.com/mpesa-oauth-api-integration-step-by-step-using-c-sharp-c/

On this guide,we are going to look on how to integrate mpesa B2C api to help you understand how to utilize B2C api as part of your service offerings.Before integrating the api, you need to understand why you need this particular api.B2C Api enables one to move funds from one company paybill or till number to a customer registered mpesa account.

A good example is when you hear a conversation which ends with “{ — to mpesa}. This will include several words like Account to mpesa for most banks,withdraw to mpesa etc.You can add anything on the list.All this refers to moving funds from a company paybill/till to a recipient mpesa account.Below is a small conversation between two users (John Doe and Jane Doe) to help you understand B2C.

John Doe:Hey Jane,i got this crazy idea of our new product.
Jane Doe:Ah,whats the new idea this time?.
John Doe:Its a new lending product we have been discussing over the last few months.
Jane Doe:(hmm). But the market….….
John Doe:No,Its going to change how people get loans over internet.
Jane Done.(Hmm). Well,i see .
John Doe:It’s going to revolutionize the lending industry……We are going to add machine learning and artificial intelligence to disburse loans to users on our platform using mobile mobile money (silence)…and that’s our secret sauce!.
Jane Doe:Sounds interesting!. How do we go about it?.
John Doe:We are going to get two paybills from safaricom to disburse loans.One for loan repayments and another for disbursements.
Jane Doe:Perfect deal!.Am in.
John Doe:Its a deal!.

(Two weeks later in the news)
*********Duo launches Nextgen lending app!. Partners with ABC Company to offer real time loans.******** (The story is on a lighter note.)

At this stage,i presume you have clearly identified the use case for B2C Api and C2B API.To disburse funds,you need B2C.To receive funds ,you need to have C2B API integrated on your platform.

To get started ,you need to have at-least a good mastery of the following tools/technologies:-

Visual Studio (Version of your choice,here i am using VS 2013)
A good understanding of C# Programming language
A good understanding of consuming REST api.

On your visual studio,create a new web forms project by clicking File ->New Project->Visual C#->Asp.Net Web Forms Application then give it a name of your choice.

N.B.Their is no limit of the type of project you can create.You can create console,mvc app etc based on your preference as long as it can consume resource over the internet.

Once that’s done,open your default.aspx.cs form which appears on your right side of your newly created project.

The above screenshot represents the file we are going to work with through out the integration process.Once opened,its now time to get our hands ready for actual development.Before we write our code,we need to get the actual B2C Api endpoint we are integrating.The api endpoint can be found from the following linkhttps://developer.safaricom.co.ke/b2c/apis/post/paymentrequest .

The endpoint contains all parameters required to initiate a B2C Request from our application.Make sure you read carefully to understand the parameters and what they mean.If you don’t understand what any of each parameters mean,kindly ask questions on the the comments section below.

To get started,we need the following items:-
OAUTH Token (This is a mandatory parameter,check my previous article on how to generate the token.)
Initiator Name (This can be found from your developer account by following this link https://developer.safaricom.co.ke/test_credentials
Security Credential (This is also found on the following link https://developer.safaricom.co.ke/test_credentials).
CommandID (This is necessary as you will need to specify the kind of operation you are actually attempting to do.Check it from the following link: https://developer.safaricom.co.ke/b2c/apis/post/paymentrequest ).

N.B.Security credential is generated by using the password provided to you on your developer password .The password provided is used to generate the security credential by pasting it on the Generate Security Credential textbox found on this link https://developer.safaricom.co.ke/test_credentials

Test Credentials

The security credential is the bottom line string which we will parse as part of the request parameters when invoking the api resource.

Once we have those items ready,its now time to come back to our visual studio project we had created earlier.

On your visual studio,create a new class and give it a name MpesaRequest as shown below:-

Mpesa Request Class.

From the above class,you can see that i have decorated the properties which we will be serializing to send our request in json.From your visual studio package manager console,run this operation to install the package i.e Install-Package Newtonsoft.Json and import newtonsoft namespace in our mpesa request class by declaring the “using statement” . i.e using Newtonsoft.Json;

Once that is done,we are going to create our method which will make the actual api call to safaricom b2c endpoint.For http request,i am using HttpWebRequest class.

B2C Endpoint uses Basic Authorization hence the reason we require the OAUTH token as part of our header parameters.Assumption is hereby made that you have checked my previous article on how to generate the token and that you have successfully generated the token from your developer account.

Once you have all the parameters ready with you,open your code behind section on our default.aspx.cs form and create your method as shown below:-

private B2CResponse ProcessB2CApiRequest(MpesaRequest mpesaRequest, string b2cUrl, string token)
{
if (mpesaRequest == null)
{
return null;
}
string serializedBodyRequest = JsonConvert.SerializeObject(mpesaRequest);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(b2cUrl);
httpRequest.ContentType = “application/json”;
httpRequest.Method = “POST”;
httpRequest.Headers.Add(“Authorization”, “Bearer “ + token);
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(serializedBodyRequest);
streamWriter.Flush();
streamWriter.Close();
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
var result = “”;
using (var responseStream = new StreamReader(httpResponse.GetResponseStream()))
{
result = responseStream.ReadToEnd();
}
B2CResponse b2CResponse = JsonConvert.DeserializeObject<B2CResponse>(result);
if (b2CResponse == null)
{
return null;
}
 return b2CResponse;
}
catch (Exception)
{
 return null;
}
}

Once you have created the above code section,proceed to create an instance of our mpesa request class on our page load event by calling our created method as shown below:-

         MpesaRequest mpesaRequest=new MpesaRequest();

mpesaRequest.PartyB = "{This is the test number provided on your test credentials account}";
mpesaRequest.PartyA = "{Also found on your test account credentials}";
mpesaRequest.InitiatorName = "{Also found on your test account credentials}";
mpesaRequest.SecurityCredential =
"{Add your earlier generated security credential here}";
mpesaRequest.CommandId = "SalaryPayment";
mpesaRequest.Amount = "1000";
mpesaRequest.Remarks = "Testing";
mpesaRequest.QueueTimeOutUrl = "Your callback url where you want to receive payment response incase operation has timed out";
mpesaRequest.ResultUrl = "Your callback url where you want to receive your result.";
mpesaRequest.Occassion = "{Optional parameter}";

string b2cUrl = "https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";
string token = "{This is the token you have generated from your developer test account}";

Ensure you have internet to make the api call.The above method is the one which connects to safaricom b2c endpoint and does the processing of our request.It moves money from the paybill account we have specified (i.e Party A ) to Party B(Our intended recipient).

From your visual studio,add a breakpoint and run the default.aspx page.Once you have run it,your response should appear as below:-

Mpesa B2C Response.

From our callback url we specified,you should receive a complete response with the details about the transaction.If you check the response,you will see the response about the transaction we processed contains a couple of details .The response posted back to our site is of type json so you will deserialize the response by creating a different class which contains all the properties as contained on the response url we specified.Below is our response as posted back from mpesa:-

{"Result":{"ResultType":0,"ResultCode":0,"ResultDesc":"The service request is processed successfully.","OriginatorConversationID":"4164-2622798-2","ConversationID":"AG_20180414_00007f85f308e3e3db37","TransactionID":"MDE61H4CZM","ResultParameters":{"ResultParameter":[{"Key":"TransactionReceipt","Value":"MDE61H4CZM"},{"Key":"TransactionAmount","Value":1000},{"Key":"B2CWorkingAccountAvailableFunds","Value":600000.00},{"Key":"B2CUtilityAccountAvailableFunds","Value":48967.00},{"Key":"TransactionCompletedDateTime","Value":"14.04.2018 13:05:10"},{"Key":"ReceiverPartyPublicName","Value":"254708374149 - John Doe"},{"Key":"B2CChargesPaidAccountAvailableFunds","Value":0.00},{"Key":"B2CRecipientIsRegisteredCustomer","Value":"Y"}]},"ReferenceData":{"ReferenceItem":{"Key":"QueueTimeoutURL","Value":"https:\/\/internalsandbox.safaricom.co.ke\/mpesa\/b2cresults\/v1\/submit"}}}}

As shown on the above response,our transaction was successfully processed.On live environment,this would have meant that we were able to process the request and our recipient received funds on his mpesa account.

After getting the above response,you need to deserialize the full response so that you can get the actual values and save the details on your database.

The response from mpesa is not guaranteed to be successful always based on many cases.In case your request failed,you will receive a different response which contains a description of why the request could not be processed for further analysis.Ensure that your logic caters for all scenarios to ensure you don’t mark transactions as processed without actually receiving the final result on your callback url.

Up-to this far ,we have accomplished our mission of integrating B2C API on our application.Good luck as you integrate the api.

Happy coding.Our next section will cover B2B &C2B Api Integration

For technical support or any other inquiries,feel free to leave a comment below or reach via integrations001@gmail.com