Mpesa OAUTH API Integration Step by step using C Sharp (C#)

Job Masai
8 min readNov 5, 2017

--

Recently,one of the largest Mobile Money operators in Kenya i.e Safaricom, released a faster and a simpler REST api (http://developer.safaricom.co.ke/) which users can quickly plug it on their applications reducing the integration nightmares which had been experienced by many partners over the past few months.

This process is now streamlined and developers/partners are now able to integrate their applications with just few setups on their applications.More possibilities exist for the new api and only sky is the limit on what you can achieve with the new api.

This first guide starts with the OAUTH API(https://developer.safaricom.co.ke/oauth/apis/get/generate-1) which as a developer you are required to generate a token which is required as part of the HTTP Header when making an API Request to other subsequent API Resources i.e B2C,B2B etc.

OAUTH API Dash Board

To get started with the OAUTH API,i am using the following tools and technologies:-
1.Visual Studio 2013
2.A good understanding of C#
3.Rest Sharp (Rest Sharp is a
Simple REST and HTTP API Client for .NET which we will use to send our api request to the provided safaricom oauth endpoint.More is found on the following link: http://restsharp.org/)
N.B.You can use any of your preferred method for making http request.

As part of your HTTP Request,the token you generate is valid for a period of one hour.This means that you can save the token generated in a data store somewhere where you can use it on your application .

OAUTH ENDPOINT URL :

https://sandbox.safaricom.co.ke/oauth/v1/generate

To get started,click visual studio and select New Project.Once you click on the New Project link,a window opens up which shows you several projects you can create.For our case,we are going to create a c# console application.On the “Templates” menu section,select “Visual C#”. On your right side,select Console Application and give it a name of your choice and click okay.

Once this is done,your project files are created and you can now get started on your development.On your newly created project,select the Program.cs file which is where we will be doing our development.

Points to note:

To prepare the token generation process,you are required to get the following from your Safaricom developer portal:-
1.Consumer Key
2.Consumer Secret.
The above two credentials will be used as part of our http header values for Basic Authorization.This means you are required to add them as part of your header request every time you are making an api call to safaricom endpoints.
From your developer account found here (https://developer.safaricom.co.ke/user/me/apps),ensure you have an already created and approved application.If you don't have it already created,kindly create it.

Once its created and approved,click on your newly created application.Upon clicking the application from your account,you will see couple of options as shown below.

App Keys

Our main interest is the “KEYS” option.Here you will see your application keys,both consumer key and consumer secret.Copy them somewhere as we will be using them on our application.Once all this is done,lets head back to our C# console application we created earlier.

Few things to note concerning the information provided above:-
1)We have managed to get our application consumer keys.
2)We have our OAUTH Api which we will be using to generate our token.
3)We have managed to set up a console application which we will develop our small application.
4)We have a brief understanding of Rest Sharp.If you have not checked it,i recommend first you check
rest sharp on how make HTTP POST and HTTP GET online .

Once all this is done,lets get back to our visual studio application we created earlier.First thing is to install Rest Sharp on our application.From your visual studio application ,right click your project name and select Manage Nugget Packages.A window will open and from the left portion,select online option.Far right from the selected option,their is an option which reads “search online”. From the search option,enter the name Restsharp” and the package name will be shown on your open window.Select “Install” Option and wait as Rest Sharp installs on your application.Once done, click okay and now we can see our newly installed package.To check if it has been installed,expand the references section of your solution and see if the package is listed as part of references.

After installing the package,its now the time to do our first development.On your Program.cs file,create a static method which we will call on our main method.
Give it a name of your choice and assign a return type of type string.I have already created my method as shown below:-

static string GenerateSafaricomToken(string consumerKey,string consumerSecret,string grantType)

{
string token = string.Empty;
//demo purposes only
return token;

}

As you can see above,our method contains parameters which we will parse when sending request to the oauth api end point.Since we have our ready installed package restsharp on our application,we need to import its namespace on our program by importing the namespace like “using RestSharp;” .

After importing the namespace,we are now able to use the access the classes which have been referenced on restsharp package.On our method which we have created above,create a new instance of RestClient as shown below:

RestClient restClient = new RestClient
{
BaseUrl = new Uri(“https://sandbox.safaricom.co.ke"),
Authenticator = new HttpBasicAuthenticator(consumerKey, consumerSecret)
};

The authenticator has several ways to send authorization request but for safaricom we are required to send Basic Header Authorization.

The next part is to construct our request body to add the http web request method we are going to use i.e GET request and also give it the actual api method for generating the token.i.e “/oauth/v1/generate” which will act as our resource url .For this ,create a new instance of RestRequest which is found in the RestSharp Package.
Below code shows how to do that using RestSharp:-

RestRequest request = new RestRequest(“/oauth/v1/generate”, Method.GET);Below code shows how to do that using RestSharp:-

Next part is to add our request parameters as required in the api documentation on safaricom developer portal as shown in the link below:-
(“https://developer.safaricom.co.ke/oauth/apis/get/generate-1”)

Our rest client already has this option already included on the RestRequest object above.For this we need to use the method which is found in our request object which we will add our request parameters.The following code below show us how to add the request parameters as part of our api call.

request.AddParameter(“grant_type”, “client_credentials”, ParameterType.QueryString);
NB.The AddParameter is found on our rest request object we created above.

Once done,the next part is our final section where we pass our object to make the api call over the internet.(You need to have internet as part of this guide :)-).

This is the section we compose everything and we send our request to the token generator api .This method is found on our RestClient object we created initially i.e

RestClient restClient = new RestClient
{
BaseUrl = new Uri(“https://sandbox.safaricom.co.ke"),
Authenticator = new HttpBasicAuthenticator(consumerKey, consumerSecret)
};

The object has a method called “Execute” which accepts an object of type RestRequest which we created earlier.i.e

RestRequest request = new RestRequest(“/oauth/v1/generate”, Method.GET);

Below is our line of code which makes the final api request with the provided methods above:-

IRestResponse restResponse = restClient.Execute(request);

Few things to note,the above method accepts our rest request parameter which contains the method to invoke and also the http method request type .ie Get.The rest of authentication details and base url are bundled on our rest client object.The method above also returns a response of type “IRestResponse” which acts as a container of the data send back from the api.

Once that is done,we can check the kind of response generated by using the restResponse object above.The content message is available by checking the “restResponse.Content” method .This will contain the response which has been generated back by safaricom endpoint if all goes well on our API call process.The string which is returned contains a json content which you can deserialize to get the values and save them on your data store.

The code below shows how to read back the response returned back from safaricom api:-

Api Response
if (restResponse != null)
{
token = restResponse.Content;
}
return string.Empty;

On the above code,we are checking if our response object is null before processing the response.If its not null,we proceed to get the actual content which was returned back to us.
If the api request was successful,you will get the following response as token from the content method which was send back to us:_

{
"access_token": "hPHtU6TVSg9EP74AtMStXNWTnMgt",
"expires_in": "3599"
}
Nb:The token generated changes after every hour and above is a sample of how the token was generated during the demo.
The token has been modified for security issues.

In case of wrong credentials,you will get the following response:-

{
"requestId": "21604-273291-1",
"errorCode": "400.008.01",
"errorMessage": "Invalid Authentication passed"
}

After all said and done,this is the full method which we have created above:-

RestClient restClient = new RestClient
{
Authenticator = new HttpBasicAuthenticator(consumerKey, consumerKey),
BaseUrl = new Uri("https://sandbox.safaricom.co.ke"),


};

RestRequest request = new RestRequest("/oauth/v1/generate", Method.GET);

request.AddParameter("grant_type", "client_credentials", ParameterType.QueryString);


IRestResponse restResponse = restClient.Execute(request);


if (restResponse != null && !string.IsNullOrEmpty(restResponse.Content))
{


return restResponse.Content;

}

return string.Empty;

After getting your response,you can create now a class which contains the two properties for a successful response i.e

public class TokenResponse
{
[JsonProperty(“access_token”)]
public string AccessCode { get; set; }
[JsonProperty(“expires_in”)]
public int ExpiryDate { get; set; }
}

You can deserialize the token response by using any of your preferred method of deserialization.For my end am using NewtonSoft package(“https://www.newtonsoft.com/json”) to deserialize my response received.If the request was successful,your deserialized object will contain the values received from the api .If it doesn’t return a response,you can know definitely the api returned an error and you can check your response.content and see the kind of message which was received.

Below is a sample of how i have deserialized my response :-

TokenResponse tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(restResponse.Content);

If all is successful,i can be sure that my “tokenResponse” will not be null and i can go ahead and save the token in my data store.

Next part we will cover B2B,B2C and C2B Integration.

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

Happy Coding…..

--

--

Job Masai

Am software developer committed in making world a better place by using technology to develop solutions with great ROI and a positive impact.