Africa\'s Talking
Android How to Integrate payments on Android using Africa's Talking...

How to Integrate payments on Android using Africa’s Talking Payment API

-

- Advertisment -

Payment is one of the most used integrations in modern application development. Without it, we would not be able to finance our business and enable our customers to get the services they require from us.

There are many available API’s that can help us achieve this, including Daraja API that enables you to accept payment through Lipa na Mpesa. One limitation of this API is that you can only receive payment using Lipa Na Mpesa. To overcome this, let’s introduce Africa’s Talking API.

Africa’s Talking Payment APIs enables you to seamlessly receive payments from payment providers (such as Consumer-to-Business mobile payments), as well as initiate payments going out to your customers (such as Business-to-Consumer mobile payments). Not only can you receive payment from mobile payment but also from Banks!

In this article, we will be focusing on Mobile Checkout and how to receive payment from customers using mobile money.

Prerequisites

  1. You should have an Africa’s talking developer account. If you don’t have one, you can get it from here.
  2. You should have the knowledge of developing android apps with Kotlin.

Let’s get started.

The Sandbox

Africa’s Talking provides a sandbox where we can develop and test our implementation of their payment API. To get started, let’s create a payment product that we will be using to receive payment from the user. The product name will be used when creating a  payment request. Enter the product name e.g. Apewe Fish and press submit.

Payment Product

The last thing we need to set-up is the payment channel; this will act as your business number or pay bill number. To set it up, click on the three dots on your product and click add channel. After you have added a channel click submit.

Payment channel

A callback URL is used to notify us when the user has authorized the payment or not. Africa’s Talking API uses Notification to notify you when something has occurred. In the case of payment, they use Payment Notification. We will cover this in the next part of our subsequent article.

Let’s now generate an API key that helps Africa’s Talking authenticate requests that you make to their APIs. To generate the API key head over to the Settings section of the Dashboard, enter your account password and an API key will be generated for you.

Kotlin Code

Let’s get started with adding Africa’s Talking SDK to our project.

maven {
    url  "http://dl.bintray.com/africastalking/java"
}
build.gradle(Project)

To add the library name and version. Add the following line of code under dependencies.

implementation 'com.africastalking:core:3.4.4'
build.gradle(Module)

To begin using the SDK, we need to initialize it. The initialization function accepts two parameters i.e. USER_NAME and API_KEY. As we are using SANDBOX, the username will be “sandbox” and API_KEY you can generate it here.

val USER_NAME = "sandbox"
val API_KEY = "YOUR_API_KEY"

AfricasTalking.initialize(USER_NAME, API_KEY)
SDK Initialization

After initializing the SDK, we get a payment service that will be used to start our mobile checkout process.

payment = AfricasTalking.getService(AfricasTalking.SERVICE_PAYMENT)
Payment Service

The mobile checkout function accepts five parameters, product name, phone number, currency code, amount metadata and provider channel.

val productName = "Apewe Fish" 

val phoneNumber = "+254790689212"

val currencyCode = "KES"

val amount = 100f

val metadata = HashMap<string, string="">()
        metadata["someKey"] = "someValue"

val providerChannel = "11001"</string,>
Checkout Variables 
  • Product name is the name of the payment product you created. e.g. “Apewe Fish.”
  • Phone Number should be in the international format, e.g. +254790689—
  • Currency Code should be 3-Letter ISO currency Code, e.g.  KES.
  • The amount should be a floating-point variable.
  • Metadata should be any information that you seek to send with the payment request that will be included in the final payment notification.
  • Provider Channel the business number of pay bill number of the product you want to receive payment from, e.g. 11001.

Payment Request

To start the payment request, we pass the required values to the mobile checkout function and wait to receive the payment API response.

try {
  val response: CheckoutResponse = payment.mobileCheckout(productName, phoneNumber, currencyCode, amount, metadata,providerChannel)
  
  val jsonObject = JSONObject(response.toString())

  if (jsonObject.getString("status") == "PendingConfirmation") {
    Toast.makeText(this, "Success, pending confirmation", Toast.LENGTH_SHORT).show()
    Log.d("PAYMENT RESPONSE", response.toString())
      
  } else {
    Toast.makeText(this, "Failed: ${jsonObject.getString("description")}", Toast.LENGTH_SHORT).show()
    Log.d("PAYMENT RESPONSE", response.toString())
  }

  catch (ex: Exception) {
    Toast.makeText(this, ex.localizedMessage, Toast.LENGTH_SHORT).show()
  }

}
Mobile Checkout 

The API response is a JSON object that contains;  status, description, transaction id and provider channel.

status shows the status of the request which are “PendingConfirmation”, “InvalidRequest”, “NotSupported” and “Failed”.

description show a detailed description of the payment request.

When we receive a “PendingConfirmation” response, we know our request is successful, and we are only waiting for the confirmation from the user; otherwise, our request failed due to some reason you can find out more on the description.

After a successful full request, a prompt will be initiated in the user mobile phone with the details of the payment, including name and channel id for confirmation.

Testing Code in Sandbox

Africa’s Talking provides a Phone Simulator that we can use to test our code in the sandbox before proceeding to live. Using the sandbox prevents us from incurring any cost associated with our payment.

To set up the simulator click, here and enter the mobile phone you will be using to test your code.

After configuring the simulator, run the code on your physical device and see what happens in the simulator.

After a Successful request, a confirmation prompt is displayed for the user to confirm the payment. Once the user confirms the payment, the transaction is done and can be viewed in the transactions part of your Payment Product.

Conclusion

Africa’s Talking provides a seamless payment API that enables developers to receive payment from Mobile and also Banks. This removes the need for using various APIs to tackle payment. With them, all is covered in one single API.

Bonus Thoughts

  • Never Store your API Keys on your application or Repository. There are many ways of storing your API key. You can find some insights here.
  • You can develop and deploy your callback URL using NodeJs and Deploy it in Firebase Cloud Functions. To find more about Notification Callbacks proceed to Africa’s Talking Payment Notification page.

Find code here

Happy Coding!!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Posts

Building Application using Node.js HTTPS Module and Africa’s Talking SMS API

Introduction For a long time, HTTP (Hypertext Transfer Protocol) was responsible for communication between a client application and a server...

Building an Exam Enrollment and Grade Notification System using Africa’s Talking SMS Shortcode API in Django

Introduction This article explores the application of SMS shortcodes to create transparency and improve the quality of education in learning...

Build a user account management system using USSD and SMS API in Go

Introduction We will be learning how to use both the Africastalking SMS and USSD api by building an application where...

Date & Time Analysis With R

One will learn how to analyse dates and time; reproducing date-related columns from a date and also format dates and time. In application, one will learn how to plot simple and multiple time series data using the R language.
- Advertisement -

Two Factor Authentication With PHP and Africa’s Talking SMS API

Two factor authentication is an additional layer of security used to ensure only authenticated users gain access to an online account. because Passwords are historically weak, and can be easily stolen, it can't alone be the way that users access their accounts.

Building a masked number system using Spring Boot, Android and Voice Apis from Africa’s Talking

Introduction In this walk through we shall be building a platform to enable a hypothetical company have their agents call...
- Advertisement -

You might also likeRELATED
Recommended to you