React Native SDK Integration (Standard)

The steps to integrate the PhonePe Payment Gateway with the React Native platform. We provide a plugin/bridge to integrate our SDK.

The minimum supported versions

  • React-Native Version: 0.72.3
  • Latest React-Native SDK Version: 2.0.1

We can implement with the below 3 steps:

  1. Add the Plugin to the React Native project
  2. Add the native configuration (Android/iOS)
  3. Integrate the Plugin to the React Native project
  1. Add Plugin in React-Native Project/App
  2. Android – Add the native configuration in the Android Studio project
  3. iOS – Add the native configuration in the Xcode project
  4. Integrating Plugin in React-Native Project/App
    1. Init Method
    2. Start The PG transaction
    3. Helper Methods (For Android and iOS)
    4. Helper Methods (Only Android Specific)
      1. Get Package Signature for Android
      2. Get UPI Apps for Android
  5. Parameters
  6. Server Side Implementation
  7. React Native Sample App

Add Plugin in React-Native Project/App

  1. Add PhonePe Payment Dependency in React-Native project , go to root folder and install ‘react-native-phonepe-pg’ in node_modules

Android

Add the native configuration in the Android Studio project

  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-android"
       }
   }
}
  1. Build/Sync gradle:
    Go to the android folder inside your app & sync/build gradle (by typing ./gradlew build on the command line/ terminal)

iOS

Add the native configuration in the Xcode project

1. In your Info.plist under the iOS Xcode project, create or append a new Array type node LSApplicationQueriesSchemes to append the following values:
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>ppemerchantsdkv1</string>
    <string>ppemerchantsdkv2</string>
    <string>ppemerchantsdkv3</string>
    <string>paytmmp</string>
    <string>gpay</string>
</array>

For example, we have used: iOSIntentIntegration. (You can create your own identifier for your app)

URLScheme should match the below conditions

  • Only Alphabets (lower and upper case) and numbers are allowed.
  • We can allow special characters only like dot and Hyphen
  • The name should always start with alphabets.

The schema should be correct to redirect the app otherwise it will not redirect back to the merchant app.

  1. For iOS dependency
cd ios
pod install
  1. For Monitoring Transaction State and getting callback from the PhonePe consumer app, add these lines in your AppDelegate.m, inside openURL:(NSURL *) url
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
  [userInfo setObject:options forKey:@"options"];
  [userInfo setObject:url forKey:@"openUrl"];
  [[NSNotificationCenter defaultCenter] postNotificationName: @"ApplicationOpenURLNotification" object:nil userInfo:userInfo];
  return YES;
}

Integrating Plugin in React-Native Project/App

  1. import the package in your js/typescript code
import PhonePePaymentSDK from 'react-native-phonepe-pg' 
  1. Call the PhonePe methods as below

Init Method (Initialisation of SDK)

Initialize the init method before starting the transaction.

 /**
   /**
    * This method is used to initiate PhonePe Payment sdk.
    * Provide all the information as requested by the method signature.
    * Params:
    * - environment: This signified the environment required for the payment sdk
    * possible values: SANDBOX or PRODUCTION
    * if any unknown value is provided, PRODUCTION will be considered as default.
    * - merchantId: The merchant id provided by PhonePe at the time of onboarding.
    * - appId: It is optional, if you have received it from the PhonePe team, kindly pass it within the method. Otherwise pass it as 'null'.
    * - enableLogging: If you want to enable SDK log
    * - enabled = YES
    * - disable = NO
    * - Return: Boolean (TRUE -> SUCCESS).
    * - SUCCESS: TRUE
    * - FAILURE: FALSE
    * - in iOS = False 
    * - in Android = Error in case of invalid arguments ex: "Invalid environment or merchantId!"
   */
  init(
    environment: string,
    merchantId: string,
    appId: string | null,
    enableLogging: boolean | false
    ):Promise<any>;
 
Example:-
 
  PhonePePaymentSDK.init(
		environmentForSDK,
    merchantId,
    appId,
    isDebuggingEnabled
  	).then(result => {
  	// handle promise
	})

Start The PG transaction

/**
    * This method is used to initiate PhonePe B2B PG Flow.
    * Provide all the information as requested by the method signature.
    * Params:
    * - body : The request body for the transaction as per the developer docs.
    * Make sure the request body is base64encoded
    * - checkSum: checksum for the particular transaction as per the developer docs.
    * - packageName: @Optional(for iOS) in case of android if intent url is expected for specific app.
    * - appSchema: Your custom URL Schemes, as per the developer docs.
    * Return: Will be returning a dictionary / hashMap
    * {
    * status: String, // string value to provide the status of the transaction
    * // possible values: SUCCESS, FAILURE, INTERRUPTED
    * error: String // if any error occurs
    * }
    */
startTransaction(
body: string,
checkSum: string,
packageName: string | null,
appSchema: string | null
):Promise;

Example:

PhonePePaymentSDK.startTransaction(body, checkSum, packageName, appSchema).then( a => { console.log(a) })

Helper Methods (Only Android Specific)

Get Package Signature for Android
/**
   * This method is called to get package signature while creation of AppId in @Android only.
   * Return: String
   *  Non empty string -> app package signature
   *  NOTE :- In iOS, it will send null.
   */
 getPackageSignatureForAndroid(): Promise<string>;
 
Example:
  if(Platform.OS === 'android'){
     PhonePePaymentSDK.getPackageSignatureForAndroid().then(packageSignture => {
        ToastAndroid.show(packageSignture,ToastAndroid.LONG)
     })
  }

Parameters

KeysData TypePossible Values
environmentString1. SANDBOX
2. PRODUCTION
merchantIdStringAdd the Merchant ID provided by the Integration Team
appIdStringIt is optional, if you have received it from the PhonePe team, kindly pass it within the method. Otherwise pass it as ‘null’
enableLogsBoolShow the logs in the console in the SDK
1. true
2. false
bodyStringbase64String request body
appSchemaString[Only for iOS]Your App URL Scheme – To return the UI control back to the merchant app.
checksumStringChecksum for the particular transaction. Refer
apiEndPointStringThe API endpoint for the PG transaction. Refer
packageNameString[Only for Android]The Package name of the UPI app selected by the user.

Server Side Implementation

Step 1. Save the below-assigned value on your server
String apiEndPoint = "/pg/v1/pay";
Step 2. Construct the request body and encode it in Base 64 at your server as per the platform (Android/iOS):

For PG Pay API (Standard Checkout), refer to this Link.

Sample PAyload
{
  "merchantId": "MERCHANTUAT",
  "merchantTransactionId": "MT7850590068188104",
  "merchantUserId": "MUID123",
  "amount": 10000,
  "callbackUrl": "https://webhook.site/callback-url",
  "mobileNumber": "9999999999",
  "paymentInstrument": {
    "type": "PAY_PAGE"
  }
}

Convert the JSON Payload to Base64 Encoded Payload

The above JSON request payload should be converted to the Base64 Encoded Payload and then the request should be sent in the below format.

Sample REQuest
 
{
  "request": "ewogICJtZXJjaGFudElkIjogIk1FUkNIQU5UVUFUIiwKICAibWVyY2hhbnRUcmFuc2FjdGlvbklkIjogIk1UNzg1MDU5MDA2ODE4ODEwNCIsCiAgIm1lcmNoYW50VXNlcklkIjogIk1VSUQxMjMiLAogICJhbW91bnQiOiAxMDAwMCwKICAicmVkaXJlY3RVcmwiOiAiaHR0cHM6Ly93ZWJob29rLnNpdGUvcmVkaXJlY3QtdXJsIiwKICAicmVkaXJlY3RNb2RlIjogIlJFRElSRUNUIiwKICAiY2FsbGJhY2tVcmwiOiAiaHR0cHM6Ly93ZWJob29rLnNpdGUvY2FsbGJhY2stdXJsIiwKICAibW9iaWxlTnVtYmVyIjogIjk5OTk5OTk5OTkiLAogICJwYXltZW50SW5zdHJ1bWVudCI6IHsKICAgICJ0eXBlIjogIlBBWV9QQUdFIgogIH0KfQ=="
}
Step 3. Checksum Calculation

Select one of the salts shared with you and note its index. Construct the X-verify at your server as follows:

String checksum = sha256(base64Body + apiEndPoint + salt) + ### + saltIndex;
Step 4. Check the payment status

Once the payment is completed, please call the Check Transaction Status API to validate the response received via the App. You can call the Check Transaction Status at regular intervals to fetch the response from the PhonePe server in case a response is not received in the application even after 10 minutes of initiating the application.

Step 5. Handling Payment Status

The payment status can be Successful, Failed, Pending or any of the codes. For Pending, you should retry until the status changes to Successful or Failed.

React Native Sample App

Refer to the Sample App to test the Plugin and use in your React Native platform – Link