PayUMoney Integration In Android

Introduction

This article demonstrates how to integrate PayUMoney SDK in Android application. With the help of this SDK, the Android application would be able to make electronic payments through Debit card, Credit card, and Netbanking.

Transaction status

A transaction can have different states. Some of them are as follows.

  • Not Started
  • Initiated
  • Under Dispute
  • Refunded
  • Bounced
  • Failed
  • Completed

Integrating SDK in Android Project

  • Click "Project Structure" under "File" menu.
  • Click on "+" button to add new module.
  • Select "Import Gradle Project".

    Android

  • Browse and select "PayUMoney SDK".

For adding this as dependency in your project, please follow the steps given below.

  • Click on File->Project Structure.
  • Select your project and go to "Dependencies" tab.
  • Click "+" on the top right corner and select "Module dependency".
  • Select "PayUMoney".

Now, we need to contact PayUMoney for getting our Merchant Id and Key.

In our application, there will be one button for initiating the payment. On click of that button, we need to call the PayUMoney SDK with some parameters, as given below.

Parameter Required Value
key Yes Merchant key from PayUMoney
Txnid Yes Unique id
Amount Yes Amount to be collected from user
ProductInfo Yes Description about product
FirstName Yes First name of user
Email Yes Email id o f the user
phone Yes Phone number of the user
Udf1   User defined field 1
Udf2   User defined field 2
Udf3   User defined field 3
Udf4   User defined field 4
udf5   User defined field 5
SURL yes Success url to be called after payment success
FURL yes Failure url to be called after payment Failure
hash yes Hash or Checksum =sha512(key|txnid|amount|productinfo|firstname|email |udf1|udf2|udf3|udf4|udf5|salt) (SALT will be provided by PayUmoney)

Udf1 to udf5 are user defined fields; these can have any values if the user wants to post any additional data.

Hash Calculation 

  1. String hashSequence = key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|salt;   

The following function will calculate the hash code.

  1. public static String hashCal(String str) {  
  2.     byte[] hashseq = str.getBytes();  
  3.     StringBuilder hexString = new StringBuilder();  
  4.     try {  
  5.         MessageDigest algorithm = MessageDigest.getInstance("SHA-512");  
  6.         algorithm.reset();  
  7.         algorithm.update(hashseq);  
  8.         byte messageDigest[] = algorithm.digest();  
  9.         for (byte aMessageDigest : messageDigest) {  
  10.             String hex = Integer.toHexString(0xFF & aMessageDigest);  
  11.             if (hex.length() == 1) {  
  12.                 hexString.append("0");  
  13.             }  
  14.             hexString.append(hex);  
  15.         }  
  16.     } catch (NoSuchAlgorithmException ignored) {  
  17.     }  
  18.     return hexString.toString();  
  19. }   

On the "Pay Money" button click of your application, please write the following code.

  1. PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();  
  2. builder.setAmount(getAmount())  
  3.         .setTnxId(getTxnId())  
  4.         .setPhone("9895473514")  
  5.         .setProductName("ice cream")  
  6.         .setFirstName("pranav")  
  7.         .setEmail("pranav@techniche.co")  
  8.         .setsUrl("https://www.payumoney.com/mobileapp/payumoney/success.php")  
  9.         .setfUrl("https://www.payumoney.com/mobileapp/payumoney/failure.php")  
  10.         .setUdf1("")  
  11.         .setUdf2("")  
  12.         .setUdf3("")  
  13.         .setUdf4("")  
  14.         .setUdf5("")  
  15.         .setIsDebug(true)//should be false in production  
  16.         .setKey("dRQuiA")  
  17.         .setMerchantId("4928174");// Debug Merchant ID  
  18. PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();  
  19. calculateServerSideHashAndInitiatePayment(paymentParam);   

Here, we are calculating the hash code from the Server itself.

  1. private void calculateServerSideHashAndInitiatePayment(final PayUmoneySdkInitilizer.PaymentParam paymentParam) {  
  2.     // Replace your server side hash generator API URL  
  3.     String url = "https://test.payumoney.com/payment/op/calculateHashForTest";  
  4.     Toast.makeText(this"Please wait... Generating hash from server ... ", Toast.LENGTH_LONG).show();  
  5.     StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {  
  6.         @Override  
  7.         public void onResponse(String response) {  
  8.             try {  
  9.                 JSONObject jsonObject = new JSONObject(response);  
  10.                 if (jsonObject.has(SdkConstants.STATUS)) {  
  11.                     String status = jsonObject.optString(SdkConstants.STATUS);  
  12.                     if (status != null || status.equals("1")) {  
  13.                         String hash = jsonObject.getString(SdkConstants.RESULT);  
  14.                         Log.i("app_activity""Server calculated Hash :  " + hash);  
  15.                         paymentParam.setMerchantHash(hash);  
  16.                         PayUmoneySdkInitilizer.startPaymentActivityForResult(MyActivity.this, paymentParam);  
  17.                     } else {  
  18.                         Toast.makeText(MyActivity.this,  
  19.                                 jsonObject.getString(SdkConstants.RESULT),  
  20.                                 Toast.LENGTH_SHORT).show();  
  21.                     }  
  22.                 }  
  23.             } catch (JSONException e) {  
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.     }, new Response.ErrorListener() {  
  28.         @Override  
  29.         public void onErrorResponse(VolleyError error) {  
  30.             if (error instanceof NoConnectionError) {  
  31.                 Toast.makeText(MyActivity.this,  
  32.                         MyActivity.this.getString(R.string.connect_to_internet),  
  33.                         Toast.LENGTH_SHORT).show();  
  34.             } else {  
  35.                 Toast.makeText(MyActivity.this,  
  36.                         error.getMessage(),  
  37.                         Toast.LENGTH_SHORT).show();  
  38.             }  
  39.         }  
  40.     }) {  
  41.         @Override  
  42.         protected Map<String, String> getParams() throws AuthFailureError {  
  43.             return paymentParam.getParams();  
  44.         }  
  45.     };  
  46.     Volley.newRequestQueue(this).add(jsonObjectRequest);  
  47. }   

Here, we are calling PayUmoneySdkInitilizer.startPaymentActivityForResult(MyActivity.this, paymentParam); to perform the transaction.

And after the payment is completed, the onActivityResult method will be called. There, we can show the response to the user.

  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  2.     if (requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {  
  3.         if (resultCode == RESULT_OK) {  
  4.             Log.i(TAG, "Success - Payment ID : " + data.getStringExtra(SdkConstants.PAYMENT_ID));  
  5.             String paymentId = data.getStringExtra(SdkConstants.PAYMENT_ID);  
  6.             showDialogMessage("Payment Success Id : " + paymentId);  
  7.         } else if (resultCode == RESULT_CANCELED) {  
  8.             Log.i(TAG, "failure");  
  9.             showDialogMessage("cancelled");  
  10.         } else if (resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {  
  11.             Log.i("app_activity""failure");  
  12.             if (data != null) {  
  13.                 if (data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {  
  14.                 } else {  
  15.                     showDialogMessage("failure");  
  16.                 }  
  17.             }  
  18.             //Write your code if there's no result  
  19.         } else if (resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {  
  20.             Log.i(TAG, "User returned without login");  
  21.             showDialogMessage("User returned without login");  
  22.         }  
  23.     }  
  24. }   

Summary

In this article, I have discussed how to integrate PayUMoney SDK in an Android application .