Better version for integrate razorpay in swiftui based project:
import Razorpay
import SwiftUI
struct RazorpayView : UIViewControllerRepresentable {
@State var razorKey : String
func makeUIViewController(context: UIViewControllerRepresentableContext<RazorpayView>) -> RazorViewController {
let controller = RazorViewController()
controller.razorKey = self.razorKey
return controller
}
func updateUIViewController(_ uiViewController: RazorViewController, context: UIViewControllerRepresentableContext<RazorpayView>) {
}
}
class RazorViewController: UIViewController {
//MARK: - INSTANCE VARIABLES
private var razorpay:RazorpayCheckout?
var razorKey = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
razorpay = RazorpayCheckout.initWithKey(razorKey, andDelegateWithData: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
let options: [String:Any] = [
"amount" : "15",
"description": "test",
"image": "https://url-to-image.jpg",
"name": "test",
"prefill": [
"contact": "9797979797",
"email": "foo@bar.com"
],
"theme": [
"color": "#F37254"
]
]
razorpay?.open(options)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
extension RazorViewController: RazorpayPaymentCompletionProtocolWithData {
func onPaymentSuccess(_ payment_id: String, andData response: [AnyHashable : Any]?) {
let alert = UIAlertController(title: "Paid", message: "Payment Success", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
func onPaymentError(_ code: Int32, description str: String, andData response: [AnyHashable : Any]?) {
let alert = UIAlertController(title: "Error", message: "\(code)\n\(str)", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}