SDK Integration

Step 1: SDK Installation and Setup

Install PhonePe 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.

buildscript {
   repositories {
       google()
       jcenter()
   }
   dependencies {
       classpath 'com.android.tools.build:gradle:3.1.4'
       // NOTE: Do not place your application dependencies here; they belong
       // in the individual module build.gradle files
   }
}

allprojects {
   repositories {
       google()
       jcenter()
       maven {

url  "https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-android"
       }
   }
}

task clean(type: Delete) {
   delete rootProject.buildDir
}
  1. Add the below line to the 'dependencies' section of your app build.gradle.
implementation 'phonepe.intentsdk.android.release:IntentSDK:1.6.4'
implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
  1. Add below line inside application tag of your AndroidManifest.xml file
<!-- Keep it false in production environment--> 
<meta-data
   android:name="com.phonepe.android.sdk.Debuggable"
   android:value="true"/>

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

<!-- Get the App Id from PhonePe-->
<meta-data
  android:name="com.phonepe.android.sdk.AppId"
  android:value="<your app id given by PhonePe>"/>
  1. You should call this function in an Activity which get's launched before a user selects the PhonePe option on your checkout page. (ideally before 4-5 seconds of PhonePe pay option selection). Don't initialize in the Application class of your project
PhonePe.init(this)
  1. Code to display the PhonePe option only when the customer has the PhonePe app installed on his mobile device:
try {
    PhonePe.isUPIAccountRegistered(new ShowPhonePeCallback() {
        @Override
        public void onResponse(boolean show) {
            Log.d(TAG, "onResponse: "+show);
            Toast.makeText(MainActivity.this, show? "YES":"NO", Toast.LENGTH_SHORT).show();
        }
    });
} catch (PhonePeInitException e) {
    e.printStackTrace();
}

Step 2: Accept Payment API initialization

App Side:

  1. To initialize the PhonePe SDK, use below classes:
    Object: TransactionRequest
    TransactionRequest object is used to access payment gateway services like initiating the transaction, receiving the server to server callbacks etc. Here is the following code snippet:
Map<String, String> headers = new HashMap();
headers.put("X-CALLBACK-URL","https://www.demoMerchant.com");  // Merchant server URL
headers.put("X-CALL-MODE","POST");
TransactionRequest debitRequest = new TransactionRequestBuilder()
    .setData(base64Body)
    .setChecksum(checksum)
    .setUrl(apiEndPoint)
    .setHeaders(headers)
    .build();
//For Intent SDK call below function 
try {
    startActivityForResult(PhonePe.getTransactionIntent(
    /* Context */ this, debitRequest),DEBIT_REQUEST_CODE);
} catch(PhonePeInitException e){
}
  1. Override onActivityResult to listen to the debit result:
private static int DEBIT_REQUEST_CODE = 777;
 
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 
    if (requestCode == DEBIT_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.*/
    
    }   
}

Server side:

  1. Save the below Assigned apiEndPoint value at your server for the debit request.
String apiEndPoint = "/v4/debit";
  1. Construct the request body and encode in Base 64 at your server as follows:
HashMap<String, Object> data = new HashMap<>();
data.put("merchantId", “UATMERCHANT”); //String. Mandatory
data.put("transactionId", “TX123456789”); //String. Mandatory. 
data.put("amount", 100); //Long. Mandatory
data.put("merchantOrderId", “OD1234”); //String. Mandatory
data.put("message", “Payment for order placed 001234”); //String. Optional
data.put("mobileNumber", “9xxxxxxxxx”); //String. Optional
 
// transactionId length should be less than 38 characters.
// merchantOrderId length should be less than 48 characters.
// Put more info as intimated. Nesting is allowed
 
String base64Body = Base64(new GSON().toJson(data));
  1. Select one of the API keys and Salt index. Refer this link for salt key value and salt index credentials. Construct the checksum at your server as follows:
String checksum = sha256(base64Body + apiEndPoint + salt) + ### + saltIndex;

Step 3: Handling callback from PhonePe

In order to receive server to server callbacks from PhonePe server we recommend merchants to pass X-CALLBACK-URL and X-CALL-MODE in the headers of the Accept Payment 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. Based on payment status response, handling can be built at merchants end

  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":"eyJzdWNjZXNzIjp0cnVlLCJjb2RlIjoiUEFZTUVOVF9TVUNDRVNTIiwibWVzc2FnZSI6IllvdXIgcGF5bWVudCBpcyBzdWNjZXNzZnVsLiIsImRhdGEiOnsidHJhbnNhY3Rpb25JZCI6IlRYMzIzMjE4NDk2NDQyMzQiLCJtZXJjaGFudElkIjoiTTIzMDYxNjA0ODMyMjA2NzU1NzkxNDAiLCJwcm92aWRlclJlZmVyZW5jZUlkIjoiUDE4MDYxNTEzMjMwOTM5MDA1NTQ5NTciLCJhbW91bnQiOjEwMDAsInBheW1lbnRTdGF0ZSI6IkNPTVBMRVRFRCIsInBheVJlc3BvbnNlQ29kZSI6IlNVQ0NFU1MiLCJwYXltZW50TW9kZXMiOlt7Im1vZGUiOiJBQ0NPVU5UIiwiYW1vdW50IjoxMDAwLCJ1dHIiOiI4MTY2MjY1MjE2MTYifV0sInRyYW5zYWN0aW9uQ29udGV4dCI6e319fQ"
}
{ 
    "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 Accept Payment 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":{  
      "transactionId":"TX32321849644234",
      "merchantId":"UATMERCHANT",
      "providerReferenceId":"P1806151323093900554957",
      "amount":1000,
      "paymentState":"COMPLETED",
      "payResponseCode":"SUCCESS",
      "paymentModes":[  
         {  
            "mode":"ACCOUNT",
            "amount":1000,
            "utr":"816626521616"
         }
      ],
      "transactionContext":{  
      }
   }
}
  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 callbacks

Server to Server callbacks

Check Transaction Status API

Action

RESULT_OK

Success / Failure

Success / Failure

Take the decision based on response.

RESULT_CANCELLED

Success / Failure

Success / Failure

Take the decision based on response.

RESULT_CANCELLED

X

Payment Pending

Temporarily 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_CANCELLED

X

Internal Server Error
Timed Out

Call Check Transaction Status API - Take decisions based on the response received.


Step 4: 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.