iosswiftuixcode-storyboardrazorpayxcode13.2

How to integrate Razorpay in SwiftUI without storyboard


I was looking at integrating the Razorpay checkout feature with iOS in Xcode and found the official documentation at https://razorpay.com/docs/payment-gateway/ios-integration/standard/. The documentation helps with integrating the Razorpay with UIViewController. The iOS app I am building does not make use of the storyboard and is strictly SwiftUI. I have looked at multiple ways of incorporating the UIViewController in SwiftUI which is totally possible with UIViewRepresentable but the code structure uses

struct ComponentName: UIViewRepresentable{}

But Razorpay SDK for iOS wants to implement RazorpayPaymentCompletionProtocol to a class and not struct. How do I go about in using this in a strictly SwiftUI application?


Solution

  • You can use coordinators to manage the view controllers, and that coordinator will RazorpayPaymentCompletionProtocol.

    Example:

    struct ComponentName: UIViewControllerRepresentable {
        func makeUIViewController(context: Context) -> CheckoutViewController {
            .init()
        }
    
        func updateUIViewController(_ uiViewController: CheckoutViewController, context: Context) { }
        
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }
    
        class Coordinator: NSObject, RazorpayPaymentCompletionProtocol {
            let parent: ComponentName
            
            typealias Razorpay = RazorpayCheckout
            var razorpay: RazorpayCheckout!
            
            init(_ parent: ComponentName) {
                self.parent = parent
                
                RazorpayCheckout.initWithKey(razorpayTestKey, andDelegate: self)
            }
            
            func onPaymentError(_ code: Int32, description str: String) {
                  print("error: ", code, str)
               //   self.presentAlert(withTitle: "Alert", message: str)
                // parent.alert with message
              }
    
              func onPaymentSuccess(_ payment_id: String) {
                  print("success: ", payment_id)
               //   self.presentAlert(withTitle: "Success", message: "Payment Succeeded")
              }
        }
    }
    
    class CheckoutViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            //  self.showPaymentForm()
        }
    }