top of page

Seamless Payments Made Easy: Integrating Razorpay in Your SwiftUI App!

Writer's picture: Abhishek BagelaAbhishek Bagela

Updated: Oct 20, 2024

Integrating Razorpay into an iOS SwiftUI application involves several steps. Below is a step-by-step guide following best practices, using the MVVM architecture, adhering to SOLID principles, and considering Apple's Human Interface Guidelines.





Step 1: Setting Up Your Razorpay Account

  1. Sign Up: Create an account on Razorpay.

  2. Get API Keys: Navigate to the Razorpay Dashboard, create a new app, and note down the API Key and Secret.


Step 2: Setting Up Your Xcode Project

  1. Create a New SwiftUI Project:

    • Open Xcode, select "File" -> "New" -> "Project".

    • Choose "App" and select SwiftUI as the interface.

    • Name your project (e.g., "ElectronicsShop").


  1. Add Razorpay SDK:


    You can integrate Razorpay using CocoaPods or Swift Package Manager. Here’s how to do it with CocoaPods:

    • Add the following to your Podfile:


	pod 'Razorpay', '~> 1.2.0'

  1. Open the .xcworkspace file created by CocoaPods.


Step 3: Setting Up the MVVM Architecture

  • Create the following folders in your project:

    • Models

    • ViewModels

    • Views

Step 4: Create Your Model

Create a simple model for an electronic item.


// Models/ElectronicItem.swift
import Foundation
struct ElectronicItem: Identifiable {
    let id: UUID
    let name: String
    let price: Double
}


Step 5: Create Your ViewModel

Create a ViewModel to handle the business logic.


// ViewModels/ElectronicsViewModel.swift
import Foundation
class ElectronicsViewModel: ObservableObject {
    @Published var items: [ElectronicItem] = []
    
    init() {
        // Dummy data for electronics
        items = [
            ElectronicItem(id: UUID(), name: "Laptop", price: 999.99),
            ElectronicItem(id: UUID(), name: "Smartphone", price: 499.99)
        ]
    }
}

Step 6: Create Your Razorpay Payment Handler

Implement a service for handling payments.


// Services/RazorpayService.swift
import Foundation
import Razorpay
class RazorpayService: NSObject, RazorpayPaymentCompletionProtocol {
    static let shared = RazorpayService()
    
    func startPayment(amount: Double) {
        let razorpay = RazorpayClient.init(withKey: "YOUR_API_KEY", andSecret: "YOUR_API_SECRET")
        
        let options: [String: Any] = [
            "amount": amount * 100, // Amount in paise
            "currency": "INR",
            "description": "Electronics Purchase",
            "image": "https://example.com/your_logo",
            "name": "Electronics Shop",
            "order_id": UUID().uuidString, // Use a proper order ID
            "theme": ["color": "#F37254"]
        ]
        
        razorpay.open(options)
    }
    
    func onPaymentSuccess(_ payment_id: String) {
        // Handle successful payment
        print("Payment successful: \(payment_id)")
    }
    
    func onPaymentFailure(_ error: String) {
        // Handle payment failure
        print("Payment failed: \(error)")
    }
}

Step 7: Create Your Views

Create a view to display items and handle the payment.


// Views/ElectronicsListView.swift
import SwiftUI
struct ElectronicsListView: View {
    @ObservedObject var viewModel = ElectronicsViewModel()
    
    var body: some View {
        NavigationView {
            List(viewModel.items) { item in
                HStack {
                    Text(item.name)
                    Spacer()
                    Text("₹\(item.price, specifier: "%.2f")")
                    Button("Buy") {
                        RazorpayService.shared.startPayment(amount: item.price)
                    }
                    .buttonStyle(BorderlessButtonStyle())
                }
            }
            .navigationTitle("Electronics Shop")
        }
    }
}
struct ContentView: View {
    var body: some View {
        ElectronicsListView()
    }
}

Step 8: Handle Payment Callbacks in App Delegate

In your AppDelegate, ensure you handle Razorpay callbacks:


import UIKit
import Razorpay
@main
struct ElectronicsShopApp: App {
    init() {
        RazorpayService.shared = RazorpayService()
    }
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Step 9: Adhere to Apple’s Human Interface Guidelines

  1. Design Principles: Ensure your app’s UI is clear, functional, and aesthetically pleasing.

  2. Accessibility: Use accessibility identifiers and proper labels for elements.

  3. Feedback: Provide users with feedback for actions (e.g., show alerts for successful/failed payments).


Conclusion

This setup gives you a basic structure for integrating Razorpay in a SwiftUI application using MVVM and following SOLID principles. You can further enhance the application by implementing more features, such as user authentication, detailed order processing, and persistent data storage.


Additional Best Practices

  • Testing: Write unit tests for your ViewModels.

  • Error Handling: Implement robust error handling for payment transactions.

  • Environment Configuration: Use environment variables for sensitive data like API keys in production.

Feel free to expand on each part according to your app's requirements!


Commentaires


The Techpreneur Blog

© 2024 The Techpreneur Blog. All Rights Reserved.
bottom of page