Non Seamless Integration Of PayUMoney in Swift

Posted By Aditya Kumar Sharma | 16-Jan-2018

There is number of Payment Gateways available in the market such as PayPal, Zaakpay, CCAvenue, etc. In this, we are going to discuss the payUmoney Payment gateway integration in our iOS app. We will be using Custom browser method which is simplest one.

 

Steps to Integrate payUmoney:

1. Create a new Swift project in xCode.
2. Go to Storyboard and add UIWebView to the View Controller and don’t forget to set its delegate.

 

 

3. Make outlet of the web view to view controller.

    @IBOutlet weak var myWebView: UIWebView!

 

Before proceeding further we have to get a Test Environment and a Production environment, which can be done here:

 

Test Environment: http://test.payumoney.com/

Production Environment: https://www.payumoney.com/

 

After this open View Controller and declare followings on top

 

	//Testing
	//var merchantKey = “xxxx”
	//var salt = “xxxxx”
	//var PayUBaseUrl = "https://test.payu.in"

	//Production

	var merchantKey = “xxxxx”
	var salt = “xxxx”
	var PayUBaseUrl = "https://secure.payu.in"
 

 

here we describing Testing and Production credentials. Further more things to declare are :

    var hashKey: String! = nil
    var totalPriceAmount = String()
    let productInfo = “MyApp” //Project name or anything else
    let firstName = “John”	
    let email = “john@app.com”	
    let phone = “xxxxxxxxx”	
    let successUrl = "https://www.payumoney.com/mobileapp/payumoney/successs.php"   //Success URL 
    let failureUrl = "https://www.payumoney.com/mobileapp/payumoney/failuree.php"   //Failure URL
    let service_provider = "payu_paisa"
    var txnid1: String! = ""	//a unique id for specific order number.
 

Now we to create an unique taxation id and Haskey which would be containing product details(like amount), user details, Success and failure URL. So, now use these methods :

    func initPayment() {
		//Creating taxation id with timestamp
        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)
            myWebView.loadRequest(request as URLRequest)
        } catch let error as NSError {
            print("Error:", 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: "")
    }
    

 

As after Generating hashKey value web view will load the request and then UIWebView delegates method will be called. So we have to handle payment result in webViewDidFinishLoad(_:)

     func webViewDidFinishLoad(_ webView: UIWebView) {
        let requestURL = self.myWebView.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.myWebView.request?.url
        print("WebView failed loading with requestURL: \(requestURL) with error: \(error.localizedDescription) & error code: \(error)")
        
        if error._code == -1009 || error._code == -1003 {
            showAlertView(string: "Please check your internet connection!")
        }else if error._code == -1001 {
            showAlertView(string: "The request timed out.")
        }
    }

    func showAlertView(string: String) {
        let alertController = UIAlertController(title: "Alert", message: string, preferredStyle: UIAlertControllerStyle.alert)
        
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){
            (result : UIAlertAction) -> Void in
            self.performSegue(withIdentifier: "goBackToOrderPage", sender: self)
            //Go back to place order page.
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
 

 

Remember we declared SuccessURL and Failure URL in starting. Now that would be used to compare and get the result whether payment got success or got failed. On Success you should show user, a toast or alert for payment made successfully.

 

 

Thanks

 
Request for Proposal

Recaptcha is required.

Sending message..