"Some error occurred" in PayUMoney payment gateway while integrating in android

15.1k Views Asked by At

I have verified account of PayUMoney. While clicking on paynow button in sandbox mode it says "some error occurred". I used pnp sdk.

This code is for onclick on paynow button.

payNowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            userAddress = address_line1.get(0) + "," + address_line2.get(0) + "," + address_pincode.get(0)
                    + "," + address_taluka + "," + address_district + "," + address_state;
            if (payment_type.equals("online")) {
                launchPayUMoneyFlow();
            } else if (payment_type.equals("cod")) {
                launchNormalFlow();
            }

        }
    });

This is hash calculation function

public static String hashCal(String str) {
    byte[] hashseq = str.getBytes();
    StringBuilder hexString = new StringBuilder();
    try {
        MessageDigest algorithm = MessageDigest.getInstance("SHA-512");
        algorithm.reset();
        algorithm.update(hashseq);
        byte messageDigest[] = algorithm.digest();
        for (byte aMessageDigest : messageDigest) {
            String hex = Integer.toHexString(0xFF & aMessageDigest);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex);
        }
    } catch (NoSuchAlgorithmException ignored) {
    }
    return hexString.toString();
}

The following function will call when response received from PayUMoney

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result Code is -1 send from Payumoney activity
    Log.d("MainActivity", "request code " + requestCode + " resultcode " + resultCode);
    if (requestCode == PayUmoneyFlowManager.REQUEST_CODE_PAYMENT && resultCode == RESULT_OK && data !=
            null) {
        TransactionResponse transactionResponse = data.getParcelableExtra(PayUmoneyFlowManager
                .INTENT_EXTRA_TRANSACTION_RESPONSE);

        ResultModel resultModel = data.getParcelableExtra(PayUmoneyFlowManager.ARG_RESULT);

        // Check which object is non-null
        if (transactionResponse != null && transactionResponse.getPayuResponse() != null) {
            if (transactionResponse.getTransactionStatus().equals(TransactionResponse.TransactionStatus.SUCCESSFUL)) {
                //Success Transaction
            } else {
                //Failure Transaction
            }

            // Response from Payumoney
            String payuResponse = transactionResponse.getPayuResponse();

            // Response from SURl and FURL
            String merchantResponse = transactionResponse.getTransactionDetails();

            new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setMessage("Payu's Data : " + payuResponse + "\n\n\n Merchant's Data: " + merchantResponse)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }).show();

        } else if (resultModel != null && resultModel.getError() != null) {
            Log.d(TAG, "Error response : " + resultModel.getError().getTransactionResponse());
        } else {
            Log.d(TAG, "Both objects are null!");
        }
    }
}

LaunchPayUMoneyFlow is function where all processing is happen.

String txnId="";

private void launchPayUMoneyFlow() {

    PayUmoneyConfig payUmoneyConfig = PayUmoneyConfig.getInstance();

    //Use this to set your custom text on result screen button
    payUmoneyConfig.setDoneButtonText("");

    //Use this to set your custom title for the activity
    payUmoneyConfig.setPayUmoneyActivityTitle("TEST GATEWAY");

    PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder();

    try {
        amount = Double.parseDouble(final_total);

    } catch (Exception e) {
        e.printStackTrace();
    }
    txnId = System.currentTimeMillis() + "";
    String phone = userMobile;
    String productName = product_name;
    String firstName = userName;
    String email = "[email protected]";
    String udf1 = order_id;
    String udf2 = billingInfo;
    String udf3 = userAddress;
    String udf4 = userUID;
    String udf5 = request_time;
    String udf6 = "";
    String udf7 = "";
    String udf8 = "";
    String udf9 = "";
    String udf10 = "";

    AppEnvironment appEnvironment = AppEnvironment.SANDBOX;
    builder.setAmount(amount)
            .setTxnId(txnId)
            .setPhone(phone)
            .setProductName(productName)
            .setFirstName(firstName)
            .setEmail(email)
            .setsUrl(appEnvironment.surl())
            .setfUrl(appEnvironment.furl())
            .setUdf1(udf1)
            .setUdf2(udf2)
            .setUdf3(udf3)
            .setUdf4(udf4)
            .setUdf5(udf5)
            .setUdf6(udf6)
            .setUdf7(udf7)
            .setUdf8(udf8)
            .setUdf9(udf9)
            .setUdf10(udf10)
            .setIsDebug(false)
            .setKey("KEYHERE")
            .setMerchantId("MERCHANTIDHERE");

    try {
        mPaymentParams = builder.build();

generateHashFromServer(mPaymentParams);

    } catch (Exception e) {
        // some exception occurred
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        payNowButton.setEnabled(true);
    }
}


/**
 * This method generates hash from server.
 *
 * @param paymentParam payments params used for hash generation
 */
public void generateHashFromServer(PayUmoneySdkInitializer.PaymentParam paymentParam) {
    RequestQueue queue1 = Volley.newRequestQueue(this);
    String url = "URL GOES HERE"; // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    JSONArray dataArray;
                    JSONObject jsonObject;
                    String merchantHash="";

                    try {
                        jsonObject = new JSONObject(response);
                        //dataArray = jsonObject.getJSONArray(JSON_ARRAY);
                        //Toast.makeText(getApplicationContext(), "m" + jsonObject.getString("result"), Toast.LENGTH_SHORT).show();
                        merchantHash = jsonObject.getString("result");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //setting up response values to the fragment
                    if (merchantHash.isEmpty() || merchantHash.equals("")) {
                        Toast.makeText(FinalCheckoutActivity.this, "Could not generate hash", Toast.LENGTH_SHORT).show();
                    } else {
                        mPaymentParams.setMerchantHash(merchantHash);
                        //Toast.makeText(FinalCheckoutActivity.this, "m:"+mPaymentParams.getParams(), Toast.LENGTH_SHORT).show();
                        //Log.e(TAG, "onPostExecute: "+mPaymentParams.getParams() );
                        PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, FinalCheckoutActivity.this, -1, false);
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplication(), "Error:" + error, Toast.LENGTH_LONG).show();
        }

    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(PayUmoneyConstants.KEY,"KEYHERE" );
            params.put(PayUmoneyConstants.AMOUNT,amount+"" );
            params.put(PayUmoneyConstants.TXNID,txnId);
            params.put(PayUmoneyConstants.EMAIL,userEmail);
            params.put(PayUmoneyConstants.PRODUCT_INFO,product_name);
            params.put(PayUmoneyConstants.FIRSTNAME,userName);
            params.put(PayUmoneyConstants.UDF1,order_id );
            params.put(PayUmoneyConstants.UDF2,billingInfo );
            params.put(PayUmoneyConstants.UDF3,userAddress);
            params.put(PayUmoneyConstants.UDF4,userUID);
            params.put(PayUmoneyConstants.UDF5,request_time);

            return params;
        }
    };
    queue1.add(stringRequest);
}

Execution flow :

  • user clicks on paynow button after selecting online payment as method.
  • launchPayUMoneyFlow() function is executed
  • All parameters attached to PayUmoneySdkInitializer.PaymentParam.Builder
  • Then hash is generated from server and attached with PayUmoneySdkInitializer.PaymentParam.Builder
  • after successful hash creation PayUmoneyFlowManager.startPayUMoneyFlow() will executed.

After execution of PayUmoneyFlowManager.startPayUMoneyFlow() it says "Some error occurred"

Hash generation script

    <?php
$key=$_POST["key"];
$salt="SALTHERE";
$txnId=$_POST["txnid"];
$amount=$_POST["amount"];
$productName=$_POST["productInfo"];
$firstName=$_POST["firstName"];
$email=$_POST["email"];
$udf1=$_POST["udf1"];
$udf2=$_POST["udf2"];
$udf3=$_POST["udf3"];
$udf4=$_POST["udf4"];
$udf5=$_POST["udf5"];

$payhash_str = $key . '|' . checkNull($txnId) . '|' .checkNull($amount)  . '|' .checkNull($productName)  . '|' . checkNull($firstName) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '|||||||'. $salt;


function checkNull($value) {
            if ($value == null) {
                  return '';
            } else {
                  return $value;
            }
      }
$hash = strtolower(hash('sha512', $payhash_str));
$arr['result'] = $hash;
$arr['status']=0;
$arr['errorCode']=null;
$arr['responseCode']=null;
$output=$arr;

echo json_encode($output);
?>

Note : Hash generation script is obtained from PayUMoney technical team. I referred almost all questions on stackoverflow and github. Still getting this error. Few Sources that I referred.

  1. Payu payement error "Some error occurred, Try again!"
  2. 'sorry some error occurred' while integrating PayUMoney payment gateway in Test mode
  3. https://github.com/payu-intrepos/PayUMoney-Android-SDK/issues/3
  4. Android PayUMoney integration error "some error occured"
  5. PayuMoney Integration in Android : Some error occured! Try again
  6. 'sorry some error occurred' while integrating PayUMoney payment gateway in Test mode
  7. Issue in PayUmoney Android integration
3

There are 3 best solutions below

5
On BEST ANSWER

PayU SDK should replace this "Some error occured" with proper error message.

This issue is because your hash is mismatched from PayUServer.

and it is mismatched because of the number of | .

Try replacing this in Php file :

. checkNull($udf5) . '||||||'. $salt
0
On
$retHashSeq = $KEY.'|'.$posted["txnid"].'|'.$posted["amount"].'|'."Product".'|'.$posted["firstname"].'|'.$posted["email"].'|'.$posted["udf1"].'|'.$posted["udf2"].'|'.$posted["udf3"].'|'.$posted["udf4"].'|'.$posted["udf5"].'||||||'.$SALT;
0
On

Late answer but hope this will help others who are still looking for solutions.

Do not change the code PayU team has given you.

For Production,

  1. Just put some valid details in AppPreference.java file.

  2. Now in Server php script replace salt value by your production salt = "xxxxxxx" value.

  3. And, Replace the Hash generation format by below format:

This will work.

$payhash_str = $key . '|' . checkNull($txnId) . '|' .checkNull($amount) . '|' .checkNull($productName) . '|' . checkNull($firstName) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||'. $salt;