Razorpay payement in swift (ios)

Razorpay payement and Verify payment on your server.


SDK: Razorpay Standard SDK 1.2.7
Version: Swift 5.1+

To install razorpay, simply add the following line to your Podfile.

pod 'razorpay-pod'

I was working on one project and for first time i was using razorpay. I go through the razorpay documentation. But, i stuck in getting the below: razorpay_signature , razorpay_payment_id.


{
“razorpay_payment_id”: “pay_29QQoUBi66xm2f”,
“razorpay_order_id”: “order_9A33XWu170gUtm”,
“razorpay_signature”: “9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d”
}

To get the razorpay_signature to verify payment,


razorpay = RazorpayCheckout.initWithKey(razorpayTestKey, andDelegate: self)

change andDelegate to andDelegateWithData.

razorpay = RazorpayCheckout.initWithKey(razorpayTestKey, andDelegateWithData : self)

Now , in viewDidAppear —

orderApiCall() will called. where product data will be got then,
showPaymentForm() will called.
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) orderApiCall() } func orderApiCall() { let url = URL(string: “Url + order”)
let header : HTTPHeaders = [“token”: UserDefaults.standard.string(forKey: “Key”)!]
let parameter: [String: [String]] = [ “id” : [Id], ]
AF.request(url!, method: .post, parameters: parameter ,encoding: URLEncoding.default, headers: header ).responseJSON {
response in
switch response.result
{ case .success: self.productOrderResponseJSON = JSON(response.value!) if self.productOrderResponseJSON[“success”] == true { self.productAmount = Double(self.productOrderResponseJSON[“razorpayOrder”][“amount”].stringValue) ?? 0.0 self.showPaymentForm()

}
else{

}
case .failure(let error):
print(error)
}
}
}

Now we will see showPaymentForm works

public func showPaymentForm(){        razorpay = RazorpayCheckout.initWithKey("razorpayLiveKey", andDelegateWithData: self)                let options: [String:Any] = [                                                    "amount" : String(self.productAmount * 100), 
//mandatory in paise like:- 1000 paise == 10 rs

"description": "Payment for product purchase",
"order_id": self.BookOrderResponseJSON["razorpayOrder"]["razorpay_order_id"].stringValue, "image": UIImage(named: "Logo")!,

"name": "Movies",

"prefill": [
"contact": UserDefaults.standard.string(forKey: "usermobile")!, "email": UserDefaults.standard.string(forKey: "useremail")!, ],
"theme": [
"color": "#F8991F"
]
]
if let rzp = self.razorpay { rzp.open(options)
} else {
print("Unable to initialize")
}
}
fig: showPaymentForm

Handle Success and Errors Events

you can implement onPaymentSuccess and onPaymentError methods of RazorpayPaymentCompletionProtocolWithData.

//RazorpayPaymentCompletionProtocolWithData      
func onPaymentError(_ code: Int32, description str: String, andData response: [AnyHashable : Any]?) {

print("error: ", code)
let storyboard = UIStoryboard(name: "payment", bundle: nil) let razorpayVC = storyboard.instantiateViewController(withIdentifier: "paymentFailedViewController") as! paymentFailedViewController self.present(razorpayVC, animated: false, completion: nil) } func onPaymentSuccess(_ payment_id: String, andData response: [AnyHashable : Any]?) { print("success: ", response) let paymentId = response?["razorpay_payment_id"] as! String let rezorSignature = response?["razorpay_signature"] as! String verifyPayment(paymentId:paymentId,rezorSignature:rezorSignature)
}
}

There are two methods called one for onPaymentSuccess and other foronPaymentError. One onPaymentSuccess there is one more method called i.e. verifyPayment. Which will take paymentId and rezorSignature as parameter and verify payment on your server.

Now we will see verifyPayment works

func verifyPayment(paymentId:String,rezorSignature:String){                let url = URL(string: url+ "/api/verify")                                                                                 let header : HTTPHeaders = ["token": UserDefaults.standard.string(forKey: "Key")!]                    let parameter: [String: String] = [                    "razorpay_order_id": self.productOrderResponseJSON["razorpayOrder"]["razorpay_order_id"].stringValue,                    "razorpay_payment_id":paymentId,                                       "razorpay_signature":rezorSignature                                        ]                                                                                            AF.request(url!, method: .post, parameters: parameter ,encoding: URLEncoding.default, headers: header ).responseJSON {                                                                                                     response in                                                                         switch response.result {                                                                                    case .success:
self.productOrderResponseJSON = JSON(response.value!) if self.productOrderResponseJSON["success"] == true {
let storyboard = UIStoryboard(name: "payment", bundle: nil)
let razorpayVC = storyboard.instantiateViewController(withIdentifier: "paymentSuccessViewController") as! paymentSuccessViewController self.present(razorpayVC, animated: false, completion: nil) }
else{
} case .failure(let error): print(error)
} }
}

Complete code-

References-

https://razorpay.com/docs/payment-gateway/ios-integration

Thank you so much, I hope this will help you. Please feel free to hit comment if you have any doubt. Please appreciate my effort.

I developed and maintain applications aimed at a range of iOS devices including mobile phones and tablet computers.