SDK Integration (Android)

SDK Setup

Step 1: Android PG SDK setup

  1. Add the below code to ‘repositories’ section of your project level build.gradle file
 //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 level build.gradle file.
implementation 'phonepe.intentsdk.android.release:IntentSDK:3.1.0'

For PhonePe’s SDK,

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

Step 2: SDK Initialization

  1. Initialize the SDK on launch of your checkout activity. This needs to be done before calling any method of PhonePe SDK.
//Java

import com.phonepe.intent.sdk.api.PhonePeKt;

boolean result = PhonePeKt.init(
    this, //context
    "MID", //merchantId
    PhonePeEnvironment.SANDBOX, //phonePeEnvironment
    false, //enableLogging
    null //appId
);

 if(result){
  // Good to go
 }
 else {
  // Some error occurred in SDK. Report it to PhonePe Integration team.
  // NOTE: SDK is not in the state to use. Hence, no other method should be called.
}
Parameter NameTypeDescription
contextObjectPass your activity context
merchantIdStringThe merchantId shared by PhonePe
phonePeEnvironmentEnumValues Allowed:
PhonePeEnvironment.SANDBOX (For PreProd)
PhonePeEnvironment.RELEASE (For Prod)
enableLoggingBoolean[Optional Parameter]
– True (To enable the SDK logs)
– False (To disable the SDK logs)
Note: In Prod, make sure to set as False.
appIdString[Optional Parameter]
– Can be passed as null or “” also.

Payment Flow

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", “M2306160483220675579140”); //String. Mandatory
data.put("transactionId", “TX123456789”); //String. Mandatory. 
data.put("amount", 100); //Long. Mandatory
data.put("merchantUserId", “U123456789”); //String. Mandatory.
data.put("merchantOrderId", “OD1234”); //String. Mandatory
data.put("message", “Payment for order placed 001234”); //String. Optional
data.put("mobileNumber", “9xxxxxxxxx”); //String. Optional
data.put("email", “amit***75@gmail.com”); //String. Optional
data.put("shortName",  “Amit”); //String. Optional
data.put("subMerchant", “DemoMerchant”); //String. ONLY if a submerchant id has been allocated to you.

//Note : Used only for Open Intent flow.
data.put("paymentScope", "ALL_UPI_APPS"); // String. Mandatory

// 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));
Parameter NameTypeDescriptionMandatory
merchantIdStringUnique MerchantID assigned to the merchant by PhonePeYes
transactionIdStringUnique TransactionID generated by the merchant to track request to PhonePe
transactionId length should be less than 38 characters.
Yes
merchantUserIdStringUnique UserID generated by merchant. This is used to pre-login users authenticated on PhonePe. Un-authenticated users are redirected to PhonePe login page. Conversions are higher when this is provided. Avoid passing email/mobile number.Yes
amountLongTransaction amount in PaiseYes
merchantOrderIdStringOrderID generated by the merchant
merchantOrderId length should be less than 48 characters.
No
subMerchantStringTag to categorize merchant transaction.
Skip this field if you don’t have multiple merchants tagged under one merchant id
No
mobileNumberStringMobile number of the userNo
messageStringShort message. This message is displayed to the user on completion of payment.No
emailStringEmail address of the userNo
shortNameStringUser’s name pre-filled for registration purpose.No
  1. Select one of the API keys shared with you and note it’s 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;

App Side

  1. Collect Base64 encoded payload, checksum, apiEndPoint and transactionId from your server.
  2. a. Initiate the payment process as follows:
TransactionRequest debitRequest = new TransactionRequestBuilder()
	.setData(base64Body)
	.setChecksum(checksum)
	.setUrl(apiEndPoint)
	.build();

//For Intent SDK call below fuction 

try {
    startActivityForResult(PhonePe.getTransactionIntent(/* Context */ this, debitRequest),DEBIT_REQUEST_CODE);
} catch(PhonePeInitException e){
}

//For open Intent call below function, Other flows will remain as it is.  

try {
    startActivityForResult(PhonePe.getImplicitIntent(/* Context */ this, debitRequest),DEBIT_REQUEST_CODE);
} catch(PhonePeInitException e){
}
  1. b. For server to server callback option, refer to below
Map<String, String> headers = new HashMap();
headers.put("X-CALLBACK-URL","https://www.demoMerchant.com");  // Merchant server URL
headers.put("X-CALL-MODE","POST");
headers.put("X-PROVIDER-ID","M2401563246873249082352"); // ONLY if x-provider-id has been allocated to you.
TransactionRequest debitRequest = new TransactionRequestBuilder()
	.setData(base64Body)
	.setChecksum(checksum)
	.setUrl(apiEndPoint)
	.setHeaders(headers)
	.build();

//For Intent SDK call below fuction 

try {
    startActivityForResult(PhonePe.getTransactionIntent(
    /* Context */ this, debitRequest),DEBIT_REQUEST_CODE);
} catch(PhonePeInitException e){
}

//For open Intent call below function, Other flows will remain as it is.  

try {
    startActivityForResult(PhonePe.getImplicitIntent(/* Context */ this, debitRequest),DEBIT_REQUEST_CODE);
} catch(PhonePeInitException e){
}

If you get a blank screen with “Load more”, refer Troubleshooting.

  1. Override onActivityResult to listen to 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.*/
    }   
}
  • Inform your server about the completion of the transaction flow from your app.
  • Your server should check the status with server to server callback or make the Check Transaction Status API call to the PhonePe server to check the transaction status(Even for RESULT_CANCELED).
  • App should get the transaction status from the backend.
  • Based on the result inform the user about the success or failure status of the transaction.

SDK Methods

Check Availability

Request Payload:

//Sample JSON Payload
{
    "merchantId": "MID",
    "mobileNumber": "993XXXXXXX",
    "merchantUserId": "User_1234"
}

//Sample Code
JSONObject data = new JSONObject();
try {
    data.put("merchantId", merchantId);
    data.put("merchantUserId", merchantUserId);
    data.put("mobileNumber", mobileNumber);
} catch (JSONException e) {
    e.printStackTrace();
}

Base64 Encoded Payload:

String base64Body = Base64.encodeToString(data.toString().getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP);

Api End Point:

String apiEndPoint = "/v3/availabilitycheck"

Checksum Calculation:

String payloadChecksum = SHA256(base64Body + apiEndPoint + salt) + "###" + saltIndex

Pass the request into check availability method:

AvailabilityCheckRequest availabilityCheckRequest = new AvailabilityCheckRequest.AvailabilityCheckRequestBuilder()
        .setChecksum(payloadChecksum)
        .setData(base64Body)
        .build();

try {
    PhonePe.checkAvailability(availabilityCheckRequest, new CheckPhonePeAvailabilityCallback() {
        @Override
        public void onResponse(boolean show, @NonNull final String responseCode) {
            // check responseCode and show for results
        }
    });
} catch (PhonePeInitException e) {
    e.printStackTrace();
}

Sample Response:

//For Success
isAvailable: true, responseCode: "SUCCESS"

//For Failure
isAvailable: false, responseCode: "PHONEPE_APP_NOT_INSTALLED"