为 pay u 与 android 集成生成哈希时无效的哈希

invalid hash while generating hash for pay u integration with android

我在将 pay u 支付网关与我的 android 应用程序集成时遇到问题。当我为给定参数生成哈希并在我的应用程序中使用它时,我在自己的服务器上生成哈希,api 表示无效哈希请帮助我生成哈希

我的php代码是:

 <?php
// Merchant key here as provided by Payu
$MERCHANT_KEY = "0MQaQP";

// Merchant Salt as provided by Payu
$SALT = "13p0PXZk";

// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in";

$action = '';
$make_op=array();
$posted = array();
if(!empty($_POST)) {
    //print_r($_POST);
  foreach($_POST as $key => $value) { 
    //echo " key-".$key."  value-".$value."\n";
    $posted[$key] = $value; 

  }
}

$formError = 0;

if(empty($posted['txnid'])) {
  // Generate random transaction id
  $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
  $txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) 
{
  if(
          empty($posted['key'])
          || empty($posted['txnid'])
          || empty($posted['amount'])
          || empty($posted['firstname'])
          || empty($posted['email'])          
          || empty($posted['productinfo'])
          || empty($posted['surl'])
          || empty($posted['furl'])       
  ) {
    $formError = 1;
    echo "in if block";
  } 
  else {
    //$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]'));
    $hashVarsSeq = explode('|', $hashSequence);
    $hash_string = '';  
    foreach($hashVarsSeq as $hash_var) 
    {
            //echo $hash_var;
      $hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
      $hash_string .= '|';
    }

    $hash_string .= $SALT;


    $hash = strtolower(hash('sha512', $hash_string));
    //echo "hash string==".$hash_string;
    //echo $hash;
    $action = $PAYU_BASE_URL . '/_payment';
  }
  $make_op['payment_related_details_for_mobile_sdk_hash']=$hash;
  $make_op['message']="successfully generated hash";  
  $make_op['status']=0;  

  echo json_encode($make_op);
} elseif(!empty($posted['hash'])) 
{
    echo "Hash is present";
    echo $posted['hash'];
    $hash = $posted['hash'];
    $action = $PAYU_BASE_URL . '/_payment';
    $make_op['payment_related_details_for_mobile_sdk_hash']=$hash;  
    $make_op['message']="successfully generated hashs"; 
    $make_op['status']=0;   
  echo json_encode($make_op);
}

?>

我的androidActivity发送数据的代码是:

   public void generateHashFromServer(PaymentParams mPaymentParams)
    {
        nextButton.setEnabled(false); // lets not allow the user to click the button again and again.
        // lets create the post params
        Log.e("Demo","In genrate hash from Server");

        StringBuffer postParamsBuffer = new StringBuffer();
        postParamsBuffer.append(concatParams(PayuConstants.KEY, mPaymentParams.getKey()));
        postParamsBuffer.append(concatParams(PayuConstants.AMOUNT, mPaymentParams.getAmount()));
        postParamsBuffer.append(concatParams(PayuConstants.TXNID, mPaymentParams.getTxnId()));
        postParamsBuffer.append(concatParams(PayuConstants.EMAIL, null == mPaymentParams.getEmail() ? "" : mPaymentParams.getEmail()));
        postParamsBuffer.append(concatParams(PayuConstants.PRODUCT_INFO, mPaymentParams.getProductInfo()));

        postParamsBuffer.append(concatParams(PayuConstants.SURL, mPaymentParams.getSurl()));
        postParamsBuffer.append(concatParams(PayuConstants.FURL, mPaymentParams.getFurl()));
        //postParamsBuffer.append(concatParams(PayuConstants.HASH, mPaymentParams.getHash()));
        postParamsBuffer.append(concatParams(PayuConstants.FIRST_NAME, null == mPaymentParams.getFirstName() ? "" : mPaymentParams.getFirstName()));
        postParamsBuffer.append(concatParams(PayuConstants.UDF1, mPaymentParams.getUdf1() == null ? "" : mPaymentParams.getUdf1()));
        postParamsBuffer.append(concatParams(PayuConstants.UDF2, mPaymentParams.getUdf2() == null ? "" : mPaymentParams.getUdf2()));
        postParamsBuffer.append(concatParams(PayuConstants.UDF3, mPaymentParams.getUdf3() == null ? "" : mPaymentParams.getUdf3()));
        postParamsBuffer.append(concatParams(PayuConstants.UDF4, mPaymentParams.getUdf4() == null ? "" : mPaymentParams.getUdf4()));
        postParamsBuffer.append(concatParams(PayuConstants.UDF5, mPaymentParams.getUdf5() == null ? "" : mPaymentParams.getUdf5()));
        postParamsBuffer.append(concatParams(PayuConstants.USER_CREDENTIALS, mPaymentParams.getUserCredentials() == null ? PayuConstants.DEFAULT : mPaymentParams.getUserCredentials()));

        // for offer_key
        if(null != mPaymentParams.getOfferKey())
            postParamsBuffer.append(concatParams(PayuConstants.OFFER_KEY, mPaymentParams.getOfferKey()));
        // for check_isDomestic
        if(null != cardBin)
            postParamsBuffer.append(concatParams("card_bin", cardBin));
        Log.e("Demo","postParamsBuffer ="+postParamsBuffer.toString());

        String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString();
        // make api call
        Log.e("Demo","postParams ="+postParams);
        GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask();
        getHashesFromServerTask.execute(postParams);
    }



    class GetHashesFromServerTask extends AsyncTask<String, String, PayuHashes>{

        @Override
        protected PayuHashes doInBackground(String ... postParams) {
            PayuHashes payuHashes = new PayuHashes();
            try {
    //  URL url = new URL(PayuConstants.MOBILE_TEST_FETCH_DATA_URL);
    //  URL url = new URL("http://10.100.81.49:80/merchant/postservice?form=2");;

                //URL url = new URL("https://payu.herokuapp.com/get_hash");
                URL url = new URL("http://vasatech.in/er_app/PayUMoney/PayUMoney_test.php");

                // get the payuConfig first
                String postParam = postParams[0];

                byte[] postParamsByte = postParam.getBytes("UTF-8");

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length));
                conn.setDoOutput(true);
                conn.getOutputStream().write(postParamsByte);

                InputStream responseInputStream = conn.getInputStream();
                StringBuffer responseStringBuffer = new StringBuffer();
                byte[] byteContainer = new byte[1024];
                for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
                    responseStringBuffer.append(new String(byteContainer, 0, i));
                }

                Log.e("response",responseStringBuffer.toString());
                JSONObject response = new JSONObject(responseStringBuffer.toString());

                Log.e("response",response.toString());

                Iterator<String> payuHashIterator = response.keys();
                while(payuHashIterator.hasNext()){
                    String key = payuHashIterator.next();
                    switch (key){
                        case "payment_hash":
                            payuHashes.setPaymentHash(response.getString(key));
                            break;
                        case "get_merchant_ibibo_codes_hash": //
                            payuHashes.setMerchantIbiboCodesHash(response.getString(key));
                            break;
                        case "vas_for_mobile_sdk_hash":
                            payuHashes.setVasForMobileSdkHash(response.getString(key));
                            break;
                        case "payment_related_details_for_mobile_sdk_hash":
                            payuHashes.setPaymentRelatedDetailsForMobileSdkHash(response.getString(key));
                            break;
                        case "delete_user_card_hash":
                            payuHashes.setDeleteCardHash(response.getString(key));
                            break;
                        case "get_user_cards_hash":
                            payuHashes.setStoredCardsHash(response.getString(key));
                            break;
                        case "edit_user_card_hash":
                            payuHashes.setEditCardHash(response.getString(key));
                            break;
                        case "save_user_card_hash":
                            payuHashes.setSaveCardHash(response.getString(key));
                            break;
                        case "check_offer_status_hash":
                            payuHashes.setCheckOfferStatusHash(response.getString(key));
                            break;
                        case "check_isDomestic_hash":
                            payuHashes.setCheckIsDomesticHash(response.getString(key));
                            break;
                        default:
                            break;
                    }                    
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return payuHashes;


 }

我正在使用 pay u 演示代码进行 android 集成,但我不知道我是否使用那里的服务器生成哈希,然后它给出正确的哈希,他们说他们将 MD5 与 SHA512 结合使用,我尝试了同样的方法,但它是错误的hash...请帮我解决这个问题

嘿伙计,你好像在使用自己的服务器,但你需要在 php 端使用你的 live salt 和商家密钥,看看这个解决方案

您没有使用 Salt & key 从服务器

生成 hash

在服务器端生成哈希的示例代码:

    <?php

function getHashes($txnid, $amount, $productinfo, $firstname, $email, $user_credentials, $udf1, $udf2, $udf3, $udf4, $udf5,$offerKey,$cardBin)
{
      // $firstname, $email can be "", i.e empty string if needed. Same should be sent to PayU server (in request params) also.
      $key = 'gtKFFx';
      $salt = 'eCwWELxi';

      $payhash_str = $key . '|' . checkNull($txnid) . '|' .checkNull($amount)  . '|' .checkNull($productinfo)  . '|' . checkNull($firstname) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '||||||' . $salt;
      $paymentHash = strtolower(hash('sha512', $payhash_str));
      $arr['payment_hash'] = $paymentHash;

      $cmnNameMerchantCodes = 'get_merchant_ibibo_codes';
      $merchantCodesHash_str = $key . '|' . $cmnNameMerchantCodes . '|default|' . $salt ;
      $merchantCodesHash = strtolower(hash('sha512', $merchantCodesHash_str));
      $arr['get_merchant_ibibo_codes_hash'] = $merchantCodesHash;

      $cmnMobileSdk = 'vas_for_mobile_sdk';
      $mobileSdk_str = $key . '|' . $cmnMobileSdk . '|default|' . $salt;
      $mobileSdk = strtolower(hash('sha512', $mobileSdk_str));
      $arr['vas_for_mobile_sdk_hash'] = $mobileSdk;

      $cmnPaymentRelatedDetailsForMobileSdk1 = 'payment_related_details_for_mobile_sdk';
      $detailsForMobileSdk_str1 = $key  . '|' . $cmnPaymentRelatedDetailsForMobileSdk1 . '|default|' . $salt ;
      $detailsForMobileSdk1 = strtolower(hash('sha512', $detailsForMobileSdk_str1));
      $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk1;

      //used for verifying payment(optional)  
      $cmnVerifyPayment = 'verify_payment';
      $verifyPayment_str = $key . '|' . $cmnVerifyPayment . '|'.$txnid .'|' . $salt;
      $verifyPayment = strtolower(hash('sha512', $verifyPayment_str));
      $arr['verify_payment_hash'] = $verifyPayment;

      if($user_credentials != NULL &amp;&amp; $user_credentials != '')
      {
            $cmnNameDeleteCard = 'delete_user_card';
            $deleteHash_str = $key  . '|' . $cmnNameDeleteCard . '|' . $user_credentials . '|' . $salt ;
            $deleteHash = strtolower(hash('sha512', $deleteHash_str));
            $arr['delete_user_card_hash'] = $deleteHash;

            $cmnNameGetUserCard = 'get_user_cards';
            $getUserCardHash_str = $key  . '|' . $cmnNameGetUserCard . '|' . $user_credentials . '|' . $salt ;
            $getUserCardHash = strtolower(hash('sha512', $getUserCardHash_str));
            $arr['get_user_cards_hash'] = $getUserCardHash;

            $cmnNameEditUserCard = 'edit_user_card';
            $editUserCardHash_str = $key  . '|' . $cmnNameEditUserCard . '|' . $user_credentials . '|' . $salt ;
            $editUserCardHash = strtolower(hash('sha512', $editUserCardHash_str));
            $arr['edit_user_card_hash'] = $editUserCardHash;

            $cmnNameSaveUserCard = 'save_user_card';
            $saveUserCardHash_str = $key  . '|' . $cmnNameSaveUserCard . '|' . $user_credentials . '|' . $salt ;
            $saveUserCardHash = strtolower(hash('sha512', $saveUserCardHash_str));
            $arr['save_user_card_hash'] = $saveUserCardHash;

            $cmnPaymentRelatedDetailsForMobileSdk = 'payment_related_details_for_mobile_sdk';
            $detailsForMobileSdk_str = $key  . '|' . $cmnPaymentRelatedDetailsForMobileSdk . '|' . $user_credentials . '|' . $salt ;
            $detailsForMobileSdk = strtolower(hash('sha512', $detailsForMobileSdk_str));
            $arr['payment_related_details_for_mobile_sdk_hash'] = $detailsForMobileSdk;
      }


      // if($udf3!=NULL &amp;&amp; !empty($udf3)){
            $cmnSend_Sms='send_sms';
            $sendsms_str=$key . '|' . $cmnSend_Sms . '|' . $udf3 . '|' . $salt;
            $send_sms = strtolower(hash('sha512',$sendsms_str));
            $arr['send_sms_hash']=$send_sms;
      // }


      if ($offerKey!=NULL &amp;&amp; !empty($offerKey)) {
                  $cmnCheckOfferStatus = 'check_offer_status';
                        $checkOfferStatus_str = $key  . '|' . $cmnCheckOfferStatus . '|' . $offerKey . '|' . $salt ;
                  $checkOfferStatus = strtolower(hash('sha512', $checkOfferStatus_str));
                  $arr['check_offer_status_hash']=$checkOfferStatus;
            }


            if ($cardBin!=NULL &amp;&amp; !empty($cardBin)) {
                  $cmnCheckIsDomestic = 'check_isDomestic';
                        $checkIsDomestic_str = $key  . '|' . $cmnCheckIsDomestic . '|' . $cardBin . '|' . $salt ;
                  $checkIsDomestic = strtolower(hash('sha512', $checkIsDomestic_str));
                  $arr['check_isDomestic_hash']=$checkIsDomestic;
            }



    return $arr;
}

function checkNull($value) {
            if ($value == null) {
                  return '';
            } else {
                  return $value;
            }
      }

$output=getHashes($_POST["txnid"], $_POST["amount"], $_POST["productinfo"], $_POST["firstname"], $_POST["email"], $_POST["user_credentials"], $_POST["udf1"], $_POST["udf2"], $_POST["udf3"], $_POST["udf4"], $_POST["udf5"],$_POST["offerKey"],$_POST["cardBin"]);

echo json_encode($output);

?>

您可以从 url 中找到更多详细信息: PayU Documentation

这是 java 中 pay u 集成的哈希生成:

方法:getHashes()

public String getHashes(String key,String txnid, String amount, String productInfo, String firstname, String email,
String user_credentials, String udf1, String udf2, String udf3, String udf4, String udf5, String offerKey,
String cardBin,String salt) {
JSONObject response = new JSONObject();
try {

//            sha512(key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||SALT)
//            hiESPS|7174761030002574230|12|product_info|firstname|xyz@gmail.com|udf1|udf2|udf3|udf4|udf5||||||xXZAKUi8
String ph = checkNull(key) + "|" + checkNull(txnid) + "|" + checkNull(amount) + "|" + checkNull(productInfo)
+ "|" + checkNull(firstname) + "|" + checkNull(email) + "|" + checkNull(udf1) + "|" + checkNull(udf2)
+ "|" + checkNull(udf3) + "|" + checkNull(udf4) + "|" + checkNull(udf5) + "||||||" + salt;
String paymentHash = getSHA(ph);
response.put("payment_hash", paymentHash);
response.put("get_merchant_ibibo_codes_hash", generateHashString("get_merchant_ibibo_codes", user_credentials,key,salt));
response.put("vas_for_mobile_sdk_hash", generateHashString("vas_for_mobile_sdk", user_credentials,key,salt));
response.put("payment_related_details_for_mobile_sdk_hash",
generateHashString("payment_related_details_for_mobile_sdk", user_credentials,key,salt));

//for verify payment (optional)
if (!checkNull(txnid).isEmpty()) {
response.put("verify_payment_hash",
generateHashString("verify_payment", txnid,key,salt));
}

if (!checkNull(user_credentials).isEmpty()) {
response.put("delete_user_card_hash", generateHashString("delete_user_card", user_credentials,key,salt));
response.put("get_user_cards_hash", generateHashString("get_user_cards", user_credentials,key,salt));
response.put("edit_user_card_hash", generateHashString("edit_user_card", user_credentials,key,salt));
response.put("save_user_card_hash", generateHashString("save_user_card", user_credentials,key,salt));
response.put("payment_related_details_for_mobile_sdk_hash",
generateHashString("payment_related_details_for_mobile_sdk", user_credentials,key,salt));
}

// check_offer_status
if (!checkNull(offerKey).isEmpty()) {
response.put("check_offer_status_hash", generateHashString("check_offer_status", offerKey,key,salt));
}

// check_isDomestic
if (!checkNull(cardBin).isEmpty()) {
response.put("check_isDomestic_hash", generateHashString("check_isDomestic", cardBin,key,salt));
}
}catch (Exception e){

}

return response.toString();

}

private String generateHashString(String command, String var1,String key,String salt) {
return getSHA(key + "|" + command + "|" + var1 + "|" + salt);
}

private String checkNull(String value) {
if (value == null) {
return "";
} else {
return value;
}
}

private String getSHA(String str) {

MessageDigest md;
String out = "";
try {
md = MessageDigest.getInstance("SHA-512");
md.update(str.getBytes());
byte[] mb = md.digest();

for (int i = 0; i < mb.length; i++) {
byte temp = mb[i];
String s = Integer.toHexString(new Byte(temp));
while (s.length() < 2) {
s = "0" + s;
}
s = s.substring(s.length() - 2);
out += s;
}

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return out;

}