Android PG SDK Integration

Step 1: Android PG SDK setup

Install PhonePe PG SDK using Android Studio. To add the SDK to the android app please follow the steps given below:

  1. Add the below code to 'repositories' section of your project level build.gradle file
// Top-level build file where you can add configuration options common to all sub-projects/modules.

allprojects {
   repositories {
       google()
       maven {
            url  "https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-snapshots"
       }
   }
}
//https://dash.readme.com/project/phonepe-docs/v1/docs/android-pg-sdk-integration Top-level build file where you can add configuration options common to all sub-projects/modules.

allprojects {
   repositories {
       google()
       maven {
            url  "https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-android"
       }
   }
}
  1. Add the below line to the 'dependencies' section of your app build.gradle.
implementation 'phonepe.intentsdk.android.snapshot:IntentSDK:[email protected]
implementation 'phonepe.intentsdk.android.release:IntentSDK:[email protected]

🚧

For, SDK version 1.6.8

We have compileSdkVersion: 28, minSdkVersion: 21, targetSdkVersion: 28

  1. Add meta-data in <application> tag of AndroidManifest.xml file.
<!-- Keep it true in UAT environment--> 
<meta-data
   android:name="com.phonepe.android.sdk.Debuggable"
   android:value="true"/>

<!-- Keep it true in UAT environment--> 
<meta-data
   android:name="com.phonepe.android.sdk.isUAT"
   android:value="true"/> 

<!-- The value will be the MID-->
<meta-data
   android:name="com.phonepe.android.sdk.MerchantId"
   android:value="MID"/>

<!-- For UAT, App Id is not required. 
Make sure to add the following and you get the APP Id for Production after UAT Sign-off -->
<meta-data
  android:name="com.phonepe.android.sdk.AppId"
  android:value="<your app id given by PhonePe>"/>
<!-- Keep it false in production environment--> 
<meta-data
   android:name="com.phonepe.android.sdk.Debuggable"
   android:value="false"/>

<!-- Keep it false in production environment-->
<meta-data
   android:name="com.phonepe.android.sdk.isUAT"
   android:value="false"/> 

<!-- Get the App Id from PhonePe-->
<meta-data
  android:name="com.phonepe.android.sdk.AppId"
  android:value="<your app id given by PhonePe>"/>

👍

Post UAT Sign-Off, get the App Id from PhonePe for Production

Share us with the Android signature using the below code in your android application(Production).
String string_signature = PhonePe.getPackageSignature()

Step 2: SDK Initialization

  1. Initialize the PhonePe SDK in an Activity that gets launched before a user selects the PhonePe option on your checkout screen.

🚧

Note: Don't initialize in the Application class of your project.

PhonePe.init(this)
  1. Get a list of UPI Apps installed on the user’s device:
try {
    List<UPIApplicationInfo> upiApps = PhonePe.getUpiApps();
} catch (PhonePeInitException exception) {
    exception.printStackTrace();
}

UPIApplicationInfo Model

public class UPIApplicationInfo {
    String packageName;
    String applicationName;
    Long version;
}
  1. Show your custom UI containing the list of apps obtained from step 2. Make Sure packageName is accessible when the user selects any of the UPI Application.

Step 3: Server-Side Setup

  1. Use the below PhonePe Pay API endPoint value for the debit request.
String apiEndPoint = "/pg/v1/pay";
  1. Construct the request body and encode it using Base64.
HashMap<String, Object> data = new HashMap();
data.put("merchantTransactionId",txnId);        //String. Mandatory
data.put("merchantId", merchantId);             //String. Mandatory
data.put("merchantUserId", "u123");             //String. Conditional 
// merchantUserId - Mandatory if paymentInstrument.type is: PAY_PAGE, CARD, SAVED_CARD, TOKEN.
// merchantUserId - Optional if paymentInstrument.type is: UPI_INTENT, UPI_COLLECT, UPI_QR.
data.put("amount",200);                         //Long. Mandatory
data.put("mobileNumber","7908834635");          //String. Optional
data.put("callbackUrl","https://webhook.site/callback-url");    //String. Mandatory

PaymentInstrument mPaymentInstrument = new PaymentInstrument();
mPaymentInstrument.setType("UPI_INTENT");           // Intent flow. ENUM. Mandatory
mPaymentInstrument.setTargetApp("<Package name of the UPI App to be opened>");  //String. Mandatory
data.put("paymentInstrument",mPaymentInstrument);   //OBJECT. Mandatory

DeviceContext mDeviceContext = new DeviceContext();
mDeviceContext.setDeviceOs("ANDROID");          // ENUM. Mandatory
data.put("deviceContext",mDeviceContext);   //OBJECT. Mandatory

String base64Body = Base64(new GSON().toJson(data));
HashMap<String, Object> data = new HashMap();
data.put("merchantTransactionId",txnId);
data.put("merchantId", merchantId);
data.put("merchantUserId", "U2110261608294150408317");
data.put("amount",300);
data.put("redirectUrl","https://mykewlapp.com/redirect");
data.put("redirectMode","POST");
data.put("callbackUrl","https://webhook.site/callback-url");

CardsPaymentInstruments mPaymentInstrument = new CardsPaymentInstruments();
mPaymentInstrument.setType("CARD"); // Card Flow
mPaymentInstrument.setAuthMode("3DS"); 

ExpiryDetails mExpiryDetails = new ExpiryDetails();
mExpiryDetails.setMonth("06");
mExpiryDetails.seYear("2025");
         
NewCardDetails mNewCardDetails = new NewCardDetails();
mNewCardDetails.setEncryptedCardnNumber("<Encrypted card number>");
mNewCardDetails.setCardHolderName("Carlos Sainz");
mNewCardDetails.setEncryptedKeyId(69213);
mNewCardDetails.setExpiry(mExpiryDetails);
mNewCardDetails.setCvv("420");
         
mPaymentInstrument.setCardDetails(mNewCardDetails); 
data.put("paymentInstrument",mPaymentInstrument);

String base64Body = Base64(new GSON().toJson(data));
HashMap<String, Object> data = new HashMap();
data.put("merchantTransactionId",txnId);
data.put("merchantId", merchantId);
data.put("merchantUserId", "U2110261608294150408317");
data.put("amount",300);
data.put("redirectUrl","https://mykewlapp.com/redirect");
data.put("redirectMode","POST");
data.put("callbackUrl","https://webhook.site/callback-url");

CardsPaymentInstruments mPaymentInstrument = new CardsPaymentInstruments();
mPaymentInstrument.setType("SAVED_CARD"); // SAVED_CARD Flow
mPaymentInstrument.setAuthMode("3DS"); 

SavedCardDetails mSavedCardDetails = new SavedCardDetails();
mSavedCardDetails.setCardId("<Card Id>");
mSavedCardDetails.setCvv("420");
         
mPaymentInstrument.setCardDetails(mSavedCardDetails); 
data.put("paymentInstrument",mPaymentInstrument);
String base64Body = Base64(new GSON().toJson(data));
HashMap<String, Object> data = new HashMap();
data.put("merchantTransactionId",txnId);
data.put("merchantId", merchantId);
data.put("merchantUserId", "U2110261608294150408317");
data.put("amount",300);
data.put("redirectUrl","https://mykewlapp.com/redirect");
data.put("redirectMode","POST");
data.put("callbackUrl","https://webhook.site/callback-url");

NetbankingPaymentInstruments mPaymentInstrument = new NetbankingPaymentInstruments();
mPaymentInstrument.setType("NET_BANKING");  // NET_BANKING Flow
mPaymentInstrument.setBankId("SBIN");           // Bank Id of the Bank selected by the user.

data.put("paymentInstrument",mPaymentInstrument);
String base64Body = Base64(new GSON().toJson(data));
{
  "merchantId": "MERCHANTUAT",
  "merchantTransactionId": "transaction_123",
  "merchantUserId": "90223250",
  "amount": 1000,
  "mobileNumber": "9999999999",
  "callbackUrl": "https://webhook.site/callback-url",
  "paymentInstrument": {
    "type": "UPI_INTENT",
    "targetApp": "com.phonepe.app"
  },
  "deviceContext": {
    "deviceOS": "ANDROID"
  }
}
ewogICJtZXJjaGFudElkIjogIk1FUkNIQU5UVUFUIiwKICAibWVyY2hhbnRUcmFuc2FjdGlvbklkIjogInRyYW5zYWN0aW9uXzEyMyIsCiAgIm1lcmNoYW50VXNlcklkIjogIjkwMjIzMjUwIiwKICAiYW1vdW50IjogMTAwMCwKICAibW9iaWxlTnVtYmVyIjogIjk5OTk5OTk5OTkiLAogICJjYWxsYmFja1VybCI6ICJodHRwczovL3dlYmhvb2suc2l0ZS9jYWxsYmFjay11cmwiLAogICJwYXltZW50SW5zdHJ1bWVudCI6IHsKICAgICJ0eXBlIjogIlVQSV9JTlRFTlQiLAogICAgInRhcmdldEFwcCI6ICJjb20ucGhvbmVwZS5hcHAiCiAgfSwKICAiZGV2aWNlQ29udGV4dCI6IHsKICAgICJkZXZpY2VPUyI6ICJBTkRST0lEIgogIH0KfQ==
  1. Select one of the salt keys and saltIndex. Refer link link for salt & index credentials. Use these values to construct the checksum as follows:
String checksum = sha256(base64Body + apiEndPoint + salt) + ### + saltIndex;
  1. Pass on these values to your Android app in an API.

Step 4: Payment using the SDK

  1. Use the B2BPGRequestBuilder to construct B2BPGRequest from the data obtained from your server as mentioned in Step-3.
B2BPGRequest b2BPGRequest = new B2BPGRequestBuilder()
    .setData(base64Body)
    .setChecksum(checksum)
    .setUrl(apiEndPoint)
    .build();
  1. Define an intent request code for initiating a PhonePe transaction.
private static int B2B_PG_REQUEST_CODE = 777;
  1. Initiate payment using any UPI app.
//For SDK call below function 
try {
    startActivityForResult(PhonePe.getImplicitIntent(
    /* Context */ this, b2BPGRequest, “input package name of upi app to be opened”),B2B_PG_REQUEST_CODE);
} catch(PhonePeInitException e){
}
  1. Override onActivityResult to receive a callback once the PhonePe app exits.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 
    if (requestCode == B2B_PG_REQUEST_CODE) {
      
      /*This callback indicates only about completion of UI flow.
            Inform your server to make the transaction
            status call to get the status. Update your app with the
            success/failure status.*/
    
    }   
}

Step 5: Handling callback from PhonePe

In order to receive server to server callback from the PhonePe server, we recommend merchants to pass callbackUrl in the request body of the PAY API. Before considering this response you need to validate the checksum and amount parameter. This will provide the payment status response as success/failure only.

  1. After the transaction is complete:
    Once the transaction is complete, you will get a Base64 Encoded JSON response along with the headers with checksum value. Find the below code snippet:
{
"response":"ewogICJzdWNjZXNzIjogdHJ1ZSwKICAiY29kZSI6ICJQQVlNRU5UX1NVQ0NFU1MiLAogICJtZXNzYWdlIjogIllvdXIgcGF5bWVudCBpcyBzdWNjZXNzZnVsLiIsCiAgImRhdGEiOiB7CiAgICAibWVyY2hhbnRJZCI6ICJNRVJDSEFOVFVBVCIsCiAgICAibWVyY2hhbnRUcmFuc2FjdGlvbklkIjogIjEzMWJlN2RmLWE1NjItNGQxMy05OGZkLTIwOTYxMDYzNzZmZiIsCiAgICAidHJhbnNhY3Rpb25JZCI6ICJUMjIwMzA5MTMyMzM2MjYyNzIzNjEyNyIsCiAgICAiYW1vdW50IjogMTAwLAogICAgInN0YXRlIjogIkNPTVBMRVRFRCIsCiAgICAicmVzcG9uc2VDb2RlIjogIlBBWU1FTlRfU1VDQ0VTUyIsCiAgICAicGF5bWVudEluc3RydW1lbnQiOiB7CiAgICAgICJ2cGEiOiBudWxsLAogICAgICAibWFza2VkQWNjb3VudE51bWJlciI6ICJYWFhYWFhYWFhYODkwMTI1IiwKICAgICAgImlmc2MiOiAiQUFCRjAwMDkwMDkiLAogICAgICAidXRyIjogIjIwNjg1MDY3OTA3MiIsCiAgICAgICJ1cGlUcmFuc2FjdGlvbklkIjogbnVsbAogICAgfQogIH0KfQ=="
}
{ 
    "headers": { 
        "x-verify":"2abaa82a4810c57dcd6aa52680dd772173b1e40770afe028131f31ddbe5487a8###1"
    }
}
  1. To calculate the checksum in the server to server callback response. Find the code snippet
Content-Type       application/json
X-VERIFY           SHA256(response + salt key) + ### + salt index
  1. To validate the amount, the merchant needs to compare the amount parameter received in the server to server callback response with the amount parameter passed in the Pay API

  2. You need to validate the X-verify. Once both checksum and the amount parameters are validated, order can be fulfilled based on the response. Note that completion of a transaction does not imply that payment is successful. Payment can be in a successful or failed state which needs to be derived from JSON response. Here is the code snippet:

{
  "success": true,
  "code": "PAYMENT_SUCCESS",
  "message": "Your payment is successful.",
  "data": {
    "merchantId": "MERCHANTUAT",
    "merchantTransactionId": "131be7df-a562-4d13-98fd-2096106376ff",
    "transactionId": "T2203091323362627236127",
    "amount": 100,
    "state": "COMPLETED",
    "responseCode": "PAYMENT_SUCCESS",
    "paymentInstrument": {
      "vpa": null,
      "maskedAccountNumber": "XXXXXXXXXX890125",
      "ifsc": "AABF0009009",
      "utr": "206850679072",
      "upiTransactionId": null
    }
  }
}
  1. When the back button is pressed by customer, SDK will return a UI callback to the App.You should take action as mentioned below
UI callbacksServer to Server callbacksCheck Transaction Status APIAction
RESULT_OKSuccess / FailureSuccess / FailureTake the decision based on response.
RESULT_CANCELLEDSuccess / FailureSuccess / FailureTake the decision based on response.
RESULT_CANCELLEDXPayment PendingTemporarily Mark transaction as payment failure.
Timeout is 10 minutes.
Call Check Transaction Status API after 10 to 15 minutes.
If response is failure then mark as failure transaction in the system.
If the response is successful then process the Refund.
RESULT_CANCELLEDXInternal Server Error
Timed Out
Call Check Transaction Status API - Take decisions based on the response received.

Step 6: Validating the X-verify

Once the response is received, you need to validate the X-verify in order to ensure that the response received is not tampered with. In order to validate the X-verify, please follow the below steps:

  • Generate the checksum by using a SHA256 of the encoded body received in the response, salt key and salt index
  • The salt we would use will be appended with ### to the checksum value in the checksum attribute. Upon receiving this payload, you need to look at the salt_index in the checksum attribute after ### delimiter and use the appropriate salt_index to be able to calculate checksum at their end for the said payload. If it doesn't match, then you need to abort the request.
  • Salts are already pre-shared with you at the time of onboarding
  • If the value of any parameter is null, it will not be included in the calculation of the checksum.

What’s Next