Razorpay Integration in iOS Swift: A Step-by-Step Guide

Incorporating a robust and secure payment gateway is vital for any contemporary mobile application, particularly for businesses that depend on transactions. Razorpay stands out as a trusted payment solution, providing effortless integration for both web and mobile platforms. For iOS developers, embedding Razorpay using Swift not only guarantees smooth transactions but also enhances the user experience and fortifies payment security. In this detailed guide, we cover the entire process of integrating Razorpay into an iOS app with Swift. By the end of this tutorial, your iOS app will feature a fully operational Razorpay checkout.
Prerequisites for Razorpay Integration
Before beginning the Razorpay integration, ensure that the following requirements are fulfilled. First, you must have a Razorpay account, which supplies the API keys required for authentication. Second, verify that Xcode 14 or a later version is installed, as it provides optimal support for Swift 5 and iOS development. Additionally, a basic understanding of Swift and UIKit is necessary, given that the integration process involves implementing delegate methods and managing UI interactions. Lastly, to handle dependencies smoothly, familiarity with CocoaPods or Swift Package Manager (SPM) is recommended for installing the Razorpay SDK.
Setting Up the Razorpay SDK in Swift
1. Install via CocoaPods
If you have not already installed CocoaPods, execute the following command in your terminal:
sudo gem install cocoapods
Navigate to your project directory and generate a Podfile if one does not exist:
cd /path/to/YourProject
pod init
Next, add the Razorpay pod to your Podfile. Open the file and insert:
target 'YourProject' do
Use_frameworks!
pod 'Razorpay', '~> 1.2.6' # or any latest version as specified in the Razorpay documentation
end
Install the pod by running:
pod install
Then, open the newly created .xcworkspace file:
open YourProject.xcworkspace
2. Project Configuration
Import the Razorpay framework in the file where you intend to use it (for example, in a view controller):
import Razorpay
Initialize RazorpayCheckout in your class:
class PaymentViewController: UIViewController {
// Replace "YOUR_KEY_ID" with the actual key from your Razorpay Dashboard
let razorpay = RazorpayCheckout.initWithKeyID("YOUR_KEY_ID", andDelegate: self)
override func viewDidLoad() {
super.viewDidLoad()
// Additional setup code here
}
}
Extend your class to conform to the RazorpayPaymentCompletionProtocol to manage callbacks:
extension PaymentViewController: RazorpayPaymentCompletionProtocol {
func onPaymentSuccess(_ payment_id: String) {
print("Payment Success: \(payment_id)")
// Process the successful payment here
}
func onPaymentError(_ code: Int32, description str: String) {
print("Payment Error: \(code) | \(str)")
// Process the failed payment here
}
}
3. Creating an Order (Backend)
Razorpay advises generating an order on your backend server using your secret key. The server will return an order_id, which is then used when launching the checkout in your iOS app.
This order_id is essential if you are utilizing the Orders API. Once you have received it, include it along with other payment parameters in the options when presenting the Razorpay checkout.
4. Presenting the Payment Screen
Configure the payment options and trigger the Razorpay checkout with the following action:
@IBAction func payButtonTapped(_ sender: UIButton) {
// Options displayed on the payment screen
let options: [String:Any] = [
"amount": "", // Payment amount in paise (e.g., 100 paise = ₹1)
"currency": "",
"description": "Purchase Description",
"order_id": "order_DBJOWzybf0sJAA", // The order_id generated on your backend
"prefill": [
"contact": "9999999999",
"email": "test@example.com"
],
"theme": [
"color": "#F37254"
]
]
razorpay?.open(options)
}
5. Handling Deep Links or External Redirects (Optional)
For certain payment options, Razorpay might redirect users to external apps or websites to complete the transaction. Generally, the SDK handles the return to your app automatically; however, if you are utilizing custom URL schemes or advanced flows, make sure these scenarios are properly managed in your SceneDelegate or AppDelegate.
6. Testing and Going Live
Begin by using the Test Keys available in your Razorpay Dashboard and simulate payments using the test card details provided by Razorpay.
After thorough testing, update your code to use the Live Keys:
let razorpay = RazorpayCheckout.initWithKeyID("YOUR_LIVE_KEY_ID", andDelegate: self)
Ensure that your backend server is also configured with the live credentials to generate the correct order_id.
Common Troubleshooting Tips
Key ID vs. Key Secret: Remember, the Key ID is utilized on the client side within your iOS app, whereas the Key Secret must remain solely on your server (never expose the secret in the client code).
App Transport Security (ATS): Should you encounter networking problems, check that your Info.plist is correctly set up for ATS or that exceptions for Razorpay domains are added (this is generally unnecessary when using HTTPS).
Swift Versions & Xcode: Confirm that you are using a supported version of Swift and Xcode. Sometimes, updating CocoaPods and the pod specifications can resolve compatibility issues.
Deploying to Production
Switch to Live Mode in the Razorpay Dashboard.
Replace the test API key with your live API key in ViewController.swift.
Ensure your backend is configured for live transactions.
Submit your app to the App Store (if applicable).
Once testing is complete, it’s time to deploy your Razorpay integration to a production environment. Switch your Razorpay Dashboard to Live Mode and generate the live API keys. Replace the test key in your code with the live key to enable actual transactions. Additionally, verify that your backend server is properly set up to manage live orders and payments. Finally, assess your app’s payment flow and, if necessary, submit your app to the App Store.
This is your Feature section paragraph. Use this space to present specific credentials, benefits or special features you offer.Velo Code Solution This is your Feature section specific credentials, benefits or special features you offer. Velo Code Solution This is
More Ios app Features
Developing for Apple Watch: A Step-by-Step Guide
This guide covers everything you need to know to start building apps for Apple Watch. Learn how to set up WatchKit, build interfaces, and connect with iPhone apps. Ideal for iOS developers looking to expand their skills to wearable technology.
ARKit: Developing Augmented Reality Apps
Explore how to create immersive AR experiences on iOS using ARKit. This tutorial covers plane detection, object placement, gesture handling, and rendering. Learn the tools needed to turn real-world environments into interactive digital playgrounds.