Android Payments SDK Integration Guide
Posted by Sam Francisco, Harold Calayan • Friday September 23, 2016 02:39 PM

The PayMaya Android Payments SDK allows your app to accept payments from your customers using any MasterCard and Visa card (credit, debit, or prepaid) while giving you the control and flexibility of the payment user experience.

 


Contents

 

Prerequisites

Overview

Integration

Using Payments

      Initialize Environment

      Setup Card Object

      Initialize Paymaya Payment

      Execute to get Payment Token

Testing Your Payment Token

      Without Backend Integration

      With Backend Integration

Summary

 

Prerequisites

 

Compatibility

 

  • JDK 7 or higher
  • Android Studio 1.3 or higher
  • Android OS version 4.1 (API level 16) or higher

 

API Keys

 

To use the PayMaya Android Payments SDK, you need to have a different set of API keys for each environment (Sandbox and Production).

 

  • Sandbox

 

Sandbox credentials are useful for testing application integration. All transactions and money flow made in this environment are only simulated and should not reflect in your production records. The following sandbox API keys can be used for testing purposes:

 

Public-facing API Key: pk-N6TvoB4GP2kIgNz4OCchCTKYvY5kPQd2HDRSg8rPeQG

 

Secret API Key: sk-9lRmFTV8BIdxoXWm5liDAlKF0yL4gZzwmDQAmnvxWOF

 

  • Production

 

Upon successful integration testing, you can then request for your production credentials. Once received, just change your SDK initialization to use production environment to start accepting live transactions.

 

There are two (2) required fields in HTTP Basic Authentication, the username and password. API keys act as the "username" while passwords are set to blank ("").

 

Overview

 

Checkout Overview

Figure 1 - Overview of the PayMaya Payments SDK flow

 

You can easily integrate the PayMaya Payments SDK to your Android app in just 3 steps:

 

  1. Setup a Card object by entering your customer's card information.
  2. Initialize PayMayaPayment by supplying your Client Key and the Card object created in step 1.
  3. Execute Payments to get a Payment Token.

 

Please note that using Payments does not involve the actual payment process. It only gives your app a Payment Token which you will use for the actual payments. The Payment Token is a secured version of your customer's card information.

 

Integration

 

Grab the latest SDK via Gradle:
compile 'com.paymaya:sdk-android:0.8.0'

 

Your app/build.gradle file should look like the following:

apply plugin: 'com.android.application'

android {
    ...
}

dependencies {
    compile 'com.paymaya:sdk-android:0.8.0'
    // your may have other dependencies here
}

Using Payments

 

Initialize Environment

We need to tell the SDK what environment are we going to use (Sandbox or Production).

PayMayaConfig.setEnvironment(PayMayaConfig.ENVIRONMENT_SANDBOX);
// Use the following for Production:
// PayMayaConfig.setEnvironment(PayMayaConfig.ENVIRONMENT_PRODUCTION);

 

Setup Card Object

To setup a card object, simply instantiate a Card by supplying your customer's card information.

String cardNumber = "1234567812345678";
String expiryMonth = "12";
String expiryYear = "2020";
String cvc = "123";

Card card = new Card(cardNumber, expiryMonth, expiryYear, cvc);

 

Initialize PayMayaPayment

After having the Card object setup, we will now initialize PayMayaPayment.

String PUBLIC_FACING_API_KEY = "";
payMayaPayment = new PayMayaPayment(PUBLIC_FACING_API_KEY, card);

 

Execute to get Payment Token

Getting a Payment Token needs to be run in the background. You can choose which Android background processing technique you want to use. For this example, we will use AsyncTask.

 

You might encounter error scenarios when you get a Payment Token. These scenarios may include that your Public-facing API Key is invalid. For these cases, we throw a PayMayaPaymentException that contains a message of what went wrong.

public void onPaymentsButtonClick(Card card) {
   new AsyncTask() {
      private String exceptionMessage;
      
      @Override
      protected PaymentToken doInBackground(Void... params) {
         try {
            return payMayaPayment.getPaymentToken();
         }
         catch (PayMayaPaymentException e) {
            exceptionMessage = e.getMessage();
            return null;
         }
      }
      
      @Override
      protected void onPostExecute(PaymentToken paymentToken) {
         if (null == exceptionMessage) {
            Log.d("paymaya", paymentToken.getPaymentTokenId() + " date: " + paymentToken.getCreatedAt().toString());
            return null;
         }
         
         Log.w("paymaya","Error: " + exceptionMessage);
      }
      
   }.execute();
}

 

For Sandbox environment, you must only use credit cards from the following link: Credit Cards for Sandbox Testing

 

When using the sandbox SDK, you will be able to debug failed transactions from the Android logs. For the error codes, you can refer the PayMaya Checkout Error Codes document.

 

Testing Your Payment Token

 

It is advised to log your payment token during development if you want to test it.

In here, we provide two (2) ways to test the payment token that you have received from your mobile app.

 

Without Backend Integration

 

To test your payment token without any backend integration, first we will check if you have cURL installed. To do this, open up a command prompt (if using Windows), command line (if using Linux), or Terminal (if using Mac). Type the following and hit enter:

curl --version

 

You will be able to see the cURL version if it is already installed. If not, you will see a message stating that curl is an unknown command.

 

In case you do not have curl installed, you may follow this link on how to install it and go back here once done:

 

If you have cURL installed and you used the Public-facing API Key in the Prerequisites section above, simply copy the following to your command line (replacing "YOUR_PAYMENT_TOKEN" with the payment token you have received in your mobile app), then hit enter:

curl -H "Content-Type: application/json" -H "Authorization: Basic c2stNFd1YjdwSFZpeEhSOGxtN3ZnZHhnTXEyM1RESmNtczhFTUVvYk04MHVvbzo=" -X POST -d '{"paymentTokenId":"YOUR_PAYMENT_TOKEN","totalAmount" : {"amount": 100,"currency": "PHP"},"buyer": {"firstName": "Cza","middleName": "dela","lastName": "Bongat","contact": {"phone": "+63(2)1234567890","email": "paymayabuyer1@gmail.com"},"billingAddress": {"line1": "9F Robinsons Cybergate 3","line2": "Pioneer Street","city": "Mandaluyong City","state": "Metro Manila","zipCode": "12345","countryCode": "PH"}}}' https://api.paymaya.com/sandbox/payments/payments

 

If you used your own Public-facing API Key to request for a payment token on your mobile app, you will have to encode your Secret API Key to base64. You can use this online tool to encode your Secret API Key.

 

Once you have your base64-encoded Secret API Key, replace the header parameter Authorization with your base64-encoded Secret API Key from the curl command above.

 

Once you have received the server's response, you should be able to see something similar to the following:

{
   "id":"5dd0c1e3-db05-403d-8719-59275faefb10",
   "environment":"sandbox",
   "isPaid":true,
   "status":"succeeded",
   "refunded":false,
   "paymentTokenId":"PLSXITXSOGfsu3JBHntZkLe1JSI1o40F19ZFUnLRPSyZUrCeXLBOOt1kWfDjgBWyeYk2uIwS5fnCUlBYCGD4V8pIAtSBblIWVxgWz94ZEVXHnIyS1UpZcmSNDelae7KsqBjsFOZ1iTY7cIz97tw2fP300v59mXqA0tQA",
   "captured":true,
   "balanceTransaction":"txn_167NbiIdRJ2MkNGUwtXNOBkn",
   "failureMessage":null,
   "failureCode":null,
   "amountRefunded":0,
   "customer":null,
   "invoice":null,
   "description":"Charge for test@example.com",
   "dispute":null,
   "metadata":{

   },
   "statementDescriptor":null,
   "fraudDetails":{

   },
   "receiptEmail":null,
   "receiptNumber":null,
   "shipping":null,
   "destination":null,
   "applicationFee":null
}

 

With Backend Integration

 

To test your payment token with your own backend, simply prepare your secret key and follow the steps here: PayMaya Payments API

 

In case you do not have your own backend but want to set it up on your local machine to simulate having a backend securing your secret key, simply follow the steps in the following link and follow its README: PayMaya Payments Skeleton Backend

 

Summary

 

  • Documents in the SDK includes an overview of usage, step-by-step integration instructions, and sample code.
  • A sample app can be downloaded for a hands-on experience.
  • Source code documentation is also available in JavaDoc format.
  • Checkout API Documentation and Payments API Documentation are available which cover error codes and server-side integration instructions.