OPay Android SDK

All payment solutions offered by OPay readily available in your clients' hands.

Download

Prerequisites

OPay SDK will allow your Android application to:

  • Launch full-screen activities to collect payment details, shipping address, and shipping method.
  • Accept card, reference code, installment payment readily available from OPay.

Make sure you have an active OPay merchant account, or create account.

To avoid any conflicts and have a seamless integration, make sure you have the following compatibility list satisfied.

itemcompatible versionReferences
Android SDK Platform5.0 (API level 21) and aboveAndroid developers' guide
Android Gradle Plugin4.1.3Android developers' guide
Gradle6.5 and above (gradle-6.5-bin.zip)gradle.org

How Android SDK Plugin Looks Like

How Android SDK Plugin Looks Like step one

How Android SDK Plugin Looks Like step two

How Android SDK Plugin Looks Like step three

Download and test OPay demonstrative application.


How it works

...

On this page we will walk you through Android SDK integration steps:

  1. Initialize and configure Android SDK.
  2. Present Payment options and collect you client's payment data.
  3. OPay Android SDK plugin will send payment request to OPay.
  4. Return payment processing information to our Android SDK plugin.
  5. Within your Android application, inform your client with the payment result.

SDK Integration

You can integrate OPay android SDK in two different ways, manual and automatic integrations. This section describes both integration methods.

Please note that you only need to follow ONLY one method as per your personal convenience.

Option 1: Manual Integration

  1. DownloadOPay Android SDK.
  2. Copy the downloaded aar file to your project' libs folder.
  3. Android Copy Lib
  4. Configure your module Gradle build file by inserting the below repositories block inside the android block
  5. allprojects{
        repositories {
            mavenCentral()
            flatDir {
                dirs 'libs'
            }
        }
    }
  6. Configure the below dependency (that are NOT already supported in your dependencies block) to your project, specify a dependency configuration such as implementation in the dependencies block of your build.gradle file.
  7. implementation(name: 'cashier-sdk-1.1.2', ext: 'aar')
  8. If your gradle version great than 7.0, you should add the aar file like bellow:
    implementation files('libs/cashier-sdk-1.1.2.aar')
    insted of the implementation way on step 4:
    implementation(name: 'cashier-sdk-1.1.2', ext: 'aar')
    You can find more detail information on Google official document psd-add-aar-jar-dependency

Option 2: Auto Integration

  1. Configure the below dependency to your build.gradle file.
  2. implementation 'team.opay.sdk:cashier-sdk:1.1.2'
  3. Configure your module Gradle build file by inserting the below repositories block inside the android block
  4. maven {
          url 'http://arifactory.opayride.com/nexus/content/repositories/public/'
          credentials {
               username = 'merchant'
               password = 'merchant'
          }
    }

SDK API hooks

After integrating OPay SDK, now it's time to know how to use our SDK API hooks to:

  1. Toggle between Sandbox (testing) and Production environment.
  2. Create payment order.
  3. Handling payment result.
  4. Order status query.

Setup SDK Environment

During the development and integration phase, you may use our SDK in testing mode be setting the sandBox to true:

PaymentTask.Companion.setSandBox(true);
PaymentTask.sandBox = false

Once you are done with your testing and your application is now ready for production, you can toggle false the sandBox variable:

PaymentTask.Companion.setSandBox(false);
PaymentTask.sandBox = false

Create Payment Order

Your app cart item should implement PayInput object, the below table illustrates the values that should be passed through your PayInput object.

ParametertypeRequiredDescription
publickeyStringrequiredYour OPay merchant account public key.
merchantIdStringrequiredYour OPay account merchant ID.
merchantNameStringrequiredMerchant Name to be displayed in cashier checkout form.
referenceStringrequiredPayment reference number in your system.
countryCodeStringrequiredCountry code (EG).
currencyStringrequiredCurrency type (EGP).
payAmountLongrequiredpayment total amount.
productNameStringrequiredName of Product/Service to be purchased.
productDescriptionStringrequiredDescription of Product/Service to be purchased.
callbackUrlStringoptionalIf you have sent callbackUrl through API, OPay will send callback notification to this callbackUrl. If you didn't send callbackUrl through API, you need to configure webhook url on the merchant dashboard, and OPay will send callback notification to this webhook url. See callback here
expireAtIntegerrequiredPayment expiration time in minutes.
payMethodStringoptionalThe preferred payment method to be presented to your customer. See available options here. If not set, all supported payment methods will be available to your customer to choose from.
userInfo
JSON Object
userIdStringoptionalthe customer user id
userNameStringoptionalthe customer user name
userMobileStringoptionalthe customer user mobile
userEmailStringoptionalthe customer user email

Create PayInput **PayInput** object is given below.

PayInput payInput=new PayInput("OPAYPUB123456",//public key
    "256612345678901",//merchantID
    "TEST 123",//merchant name
    "a2b050zzzz",//reference, reference unique
    "EG", //uppercase//country
    10000,//amount
    "EGP", //uppercase //currency
    "test",//ProductName
    "testtest",//ProductDescription
    "http://www.baidu.com",//callback Url
    "BankCard",//Payment Type
    30,//expire at
    "110.246.160.183",// user ip
    new UserInfo("UserId","UserName","UserPhone","Email")
);
val payInput = PayInput(
    publickey = "{PublicKey}",
    merchantId = "256612345678901",
    merchantName = "TEST 123",
    reference = "12347544444555666",
    countryCode = "EG", // uppercase
    currency = "EGP", // uppercase
    payAmount = 10000,
    productName = "",
    productDescription = "",
    callbackUrl = "http://www.callbackurl.com",
    userClientIP = "110.246.160.183",
    expireAt = 30,
    paymentType = "", // optional
    userInfo = UserInfo(
        //optional
        userId = "userid001",
        //optional
        userName = "David",
        //optional
        userMobile = "201066668888",
        //optional
        userEmail = "[email protected]",
    )
)

After initiating the required PayInput data, you need to call PaymentTask(this).createOrder to start creating an order. Code example as follows:

new PaymentTask(this).createOrder(
    payInput,((status, orderInfoHttpResponse) -> {
        switch (status) {
            case LOADING:
                break;
            case CANCEL:
                break;
            case SUCCESS:
                break;
        }
        return Unit.INSTANCE;
    })
);
PaymentTask(this).createOrder(payInput, callback = { status, response ->
    when (status) {
        Status.ERROR -> { // error
            Toast.makeText(this, response.message,
            Toast.LENGTH_SHORT).show()
        } else -> {

        }
    }
})

Once CreateOrder is called, user will be redirected to finish payment. You need to override the callback listener in case of error. The callback will only return the CreateOrder error. If you do not add a callback, error toast will pop up.

Sample CreateOrder error response

{
    "code": "00001",
    "message": "order already exist",
    "data": null
}

Handling Payment Result

Once the payment has been completed by your client, OPay server will respond back to the SDK to let you know the payment processing result. To get this result information, you will need to rewrite the onActivityResult method in the Activity or Fragment, and call the following methods. :

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PaymentTask.REQUEST_PAYMENT) {
        if (resultCode == PaymentTask.RESULT_PAYMENT) {
            WebJsResponse response = (WebJsResponse) data.getExtras().getSerializable(PaymentTask.RESPONSE_DATA);
            switch (response.getOrderStatus()) {
                case PaymentStatus.INITIAL: {
                    Log.e("", response.getOrderStatus());
                    break;
                }
                case PaymentStatus.SUCCESS: {
                    Log.e("", response.getOrderStatus());
                    break;
                }
                case PaymentStatus.FAIL: {
                    Log.e("", response.getOrderStatus());
                    break;
                }
                case PaymentStatus.PENDING: {
                    Log.e("", response.getOrderStatus());
                    break;
                }
            }
        }
    }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PaymentTask.REQUEST_PAYMENT){
            if (resultCode == PaymentTask.RESULT_PAYMENT){
                 val response = data?.getSerializableExtra(PaymentTask.RESPONSE_DATA) as WebJsResponse?
                 when(response?.orderStatus){
                     PaymentStatus.INITIAL ->{}
                     PaymentStatus.PENDING ->{}
                     PaymentStatus.SUCCESS ->{}
                     PaymentStatus.FAIL ->{}
                     PaymentStatus.CLOSE ->{}
                }
            }
        }
    }
}

Due to network and any other issues, the order status may not be timely. It is highly recommended to call order status inquiry to ensure the accuracy.

Order Query Status

Due to network and any other issues, the order status may not be timely. It is highly recommended to call order status inquiry to ensure the integrity of your data. To that end, You will need to create CashierStatusInput object that contains the following request parameters:

ParametertypeRequiredDescription
publickeyStringrequiredYour OPay merchant account public key.
merchantIdStringrequiredYour OPay account merchant ID.
referenceStringrequiredPayment reference number in your system.
countryCodeStringrequiredCountry code (EG).
CashierStatusInput statusInput = new CashierStatusInput(
    "{PublicKey}",
    "256621050820270",
    "12347544444555666",
    "",
    "EG"
);
val input = CashierStatusInput(
    privateKey = "{PublicKey}",
    merchantId = "256612345678901",
    reference = "12347544444555666",
    countryCode = "EG"
)

After creating the CashierStatusInput object, you need to call the PaymentTask( activity ).getCashierStatus() method to query order status and process the subsequent logic according to the response object returned.

new PaymentTask(this).getCashierStatus(statusInput, (status, response) -> {
    if(status == Status.SUCCESS){
        //data
        OrderInfo orderInfo = (OrderInfo)response.getData();
    }else if(status == Status.ERROR){
        Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
    }else{

    }
    return null;
});
PaymentTask(this).getCashierStatus((input, callback = { status, response ->
    when (status) {
        Status.SUCCESS -> {
            val data = response.data as OrderInfo
            // data
       }
        Status.ERROR -> {
            Toast.makeText(this, response.message, Toast.LENGTH_SHORT).show()
        }else -> {

        }
    }
})

Response data format is as follows:

{
    "code": "00000",
    "message": "SUCCESSFUL",
    "data":{
        "reference":"1001000",
        "orderNo":"10212100000034000",
        "status":"SUCCESS",
        "vat":{
          "total":10000,
          "currency":"EGP",
          "rate":100,
          "currencySymbo":"ج.م"
        },
        "failureReason":null,
        "silence":"Y"
    }
}