让哈希不匹配付钱给你钱Swift 3

时间:2017-05-24 11:54:48

标签: ios swift

我是Swift的新手,我正在快速整合PayUmoney IOS SDK,我遇到了麻烦当我正在进行实时显示哈希不匹配(Hash mismatch1)如果我正在测试它显示无效的商家密钥{ {3}}我从2个星期来到这里做了很多事情并没有得到任何解决方案,任何人都可以帮助它真棒。以下是我的代码,谢谢你。

var params : PUMRequestParams = PUMRequestParams.shared()
var utils : Utils = Utils()

    params.environment = PUMEnvironment.test;
    params.firstname = txtFldName.text;
    params.key = "bZf4AOjj";
    params.merchantid = "5745303";  
    params.logo_url = ""; 
    params.productinfo = "Product Info";
    params.email = txtFldEmail.text;  
    params.phone = ""; 
    params.surl = "https://www.payumoney.com/mobileapp/payumoney/success.php";
    params.furl = "https://www.payumoney.com/mobileapp/payumoney/failure.php";

    if(params.environment == PUMEnvironment.test){
        generateHashForProdAndNavigateToSDK()
    }
    else{
        calculateHashFromServer()
    }
    // assign delegate for payment callback.
    params.delegate = self;
}

func generateHashForProdAndNavigateToSDK() -> Void {
    let txnid = params.txnid!

    let hashSequence : NSString = "\(params.key)|\(txnid)|\(params.amount)|\(params.productinfo)|\(params.firstname)|\(params.email)|||||||||||2uIsGhXWVw" as NSString
    let data :NSString = utils.createSHA512(hashSequence as String!) as NSString
    params.hashValue = data as String!;
    startPaymentFlow();
}

// MARK:HASH CALCULATION

func prepareHashBody()->NSString{
    return "SHA-512key=\(params.key!)&amount=\(params.amount!)&txnid=\(params.txnid!)&productinfo=\(params.productinfo!)&email=\(params.email!)&firstname=\(params.firstname!)" as NSString;
}

func calculateHashFromServer(){
    let config = URLSessionConfiguration.default // Session Configuration
    let session = URLSession(configuration: config) // Load configuration into Session
    let url = URL(string: "https://test.payumoney.com/payment/op/v1/calculateHashForTest")!
    var request = URLRequest(url: url)
    request.httpBody = prepareHashBody().data(using: String.Encoding.utf8.rawValue)
    request.httpMethod = "POST"

    let task = session.dataTask(with: request, completionHandler: {
        (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]{

                    print(json)
                    let status : NSNumber = json["status"] as! NSNumber
                    if(status.intValue == 0)
                    {
                        self.params.hashValue = json["result"] as! String!
                        OperationQueue.main.addOperation {
                            self.startPaymentFlow()
                        }
                    }
                    else{
                        OperationQueue.main.addOperation {
                            self.showAlertViewWithTitle(title: "Message", message: json["message"] as! String)
                        }
                    }
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    })
    task.resume()
} 

2 个答案:

答案 0 :(得分:2)

你好Vinny做webview它为我工作。之前我也使用过这个PayUmoney IOS SDK,但面对如此多的问题所以基于objective-c我做了这个,所以我认为它对你有用。创建一个弱的var webview并创建类UIwebviewdelegate

class PayumoneyViewController: UIViewController, UIWebViewDelegate, UIAlertViewDelegate {

@IBOutlet weak var Webview: UIWebView!

以及在凭证下使用的测试

//test
var merchantKey = "40747T"
var salt = "ur salt"
var PayUBaseUrl = "https://test.payu.in"

直播

//Production

var merchantKey = “xxxxxx”
var salt = “xxxxx”
var PayUBaseUrl = "https://secure.payu.in"
let productInfo = “Myapp” //It can be Project name or anything else
let firstName = “Santoshi”  //Details of user whose is purchasing order
let email = “santoshi@app.com"  //Details of user whose is purchasing order
let phone = "xxxxxxxxx" //Details of user whose is purchasing order
let sUrl = "www.google.com"   //By this URL we match whether payment got success or failure
let fUrl = "www.google.com"   //By this URL we match whether payment got success or failure
let service_provider = "payu_paisa"
var txnid1: String! = ""    //Its an unique id which can give order a specific order number.
let totalPriceAmount = "1.0"

上面的viewdidload就是这样的

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(true)

    initPayment()

}

override func viewWillDisappear(_ animated: Bool) {

    super.viewWillDisappear(true)


}

在viewdidload中这样做

override func viewDidLoad() {
    super.viewDidLoad()

Webview.delegate = self

    // Do any additional setup after loading the view.
}

创建付款并生成哈希密钥

func initPayment() {


    txnid1 = “Myapp\(String(Int(NSDate().timeIntervalSince1970)))"

    //Generating Hash Key
    let hashValue = String.localizedStringWithFormat("%@|%@|%@|%@|%@|%@|||||||||||%@",merchantKey,txnid1,totalPriceAmount,productInfo,firstName,email,salt)
    let hash = self.sha1(string: hashValue)

    let postStr = "txnid="+txnid1+"&key="+merchantKey+"&amount="+totalPriceAmount+"&productinfo="+productInfo+"&firstname="+firstName+"&email="+email+"&phone="+phone+"&surl="+sUrl+"&furl="+fUrl+"&hash="+hash+"&service_provider="+service_provider


    let url = NSURL(string: String.localizedStringWithFormat("%@/_payment", PayUBaseUrl))
    let request = NSMutableURLRequest(url: url! as URL)

    do {
        let postLength = String.localizedStringWithFormat("%lu",postStr.characters.count)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Current-Type")
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.httpBody = postStr.data(using: String.Encoding.utf8)
        Webview.loadRequest(request as URLRequest)
    }

    catch let error as NSError
    {

        print(error)

    }
}

最后这样做

func sha1(string:String) -> String {
    let cstr = string.cString(using: String.Encoding.utf8)

    let data = NSData(bytes: cstr, length: string.characters.count)
    var digest = [UInt8](repeating: 0, count:Int(CC_SHA512_DIGEST_LENGTH))
    CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
    let hexBytes = digest.map { String(format: "%02x", $0) }
    return hexBytes.joined(separator: "")
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    let requestURL = self.Webview.request?.url
    let requestString:String = (requestURL?.absoluteString)!
    if requestString.contains("https://www.payumoney.com/mobileapp/payumoney/success.php") {
        print("success payment done")
    }else if requestString.contains("https://www.payumoney.com/mobileapp/payumoney/failure.php") {
        print("payment failure")
    }
}

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    let requestURL = self.Webview.request?.url
    print("WebView failed loading with requestURL: \(requestURL) with error: \(error.localizedDescription) & error code: \(error)")

    if error._code == -1009 || error._code == -1003 {
        showAlertView(userMessage: "Please check your internet connection!")
    }else if error._code == -1001 {
        showAlertView(userMessage: "The request timed out.")
    }

}

func showAlertView(userMessage:String){

}

答案 1 :(得分:-3)

我遇到了同样的问题,我已经解决了这个问题。 在我的代码中,此行生成可选值 - > let hashSequence:NSString =“(params.key!)|(txnid)|(params.amount!)|(params.productinfo!)|(params.firstname!)|(params.email!)|||||| |||||(params.merchantid!)“as NSString

从值中删除可选项。