Skip to main content

Setting Up SDK

Swift Package Manager (Recommended)
The recommended way to integrate the Cashfree iOS SDK is by using Swift Package Manager. You can do this through the Xcode interface. To add the Cashfree iOS SDK to your project, follow these steps:
  1. Open your project in Xcode.
  2. Go to File > Add Package Dependencies.
  3. Enter the repository URL: https://github.com/cashfree/core-ios-sdk.git.
  4. Select the version rule (Recommended: Up to Next Major Version).
  5. Choose the products you need:
    • CashfreePG — Complete Payment Gateway SDK (recommended)
    • CashfreePGCoreSDK — Core payment processing
    • CashfreePGUISDK — UI components
    • CashfreeAnalyticsSDK — Analytics and tracking
    • CFNetworkSDK — Networking layer
CocoaPods
In your pod file add the following line pod 'CashfreePG', '2.2.4'. Install the package using pod install. To provide UPI payments on iOS you will also need to enable the following permissions in your app. Open the info.plist file and add the below content.
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>phonepe</string>
  <string>tez</string>
  <string>paytmmp</string>
  <string>bhim</string>
  <string>amazonpay</string>
  <string>credpay</string>
</array>

Step 1: Creating an Order

The first step in the Cashfree Payment Gateway integration is to create an Order. You need to do this before any payment can be processed. You can add an endpoint to your server which creates this order and is used for communication with your frontend.
API Request for Creating an Order
Here’s a sample request for creating an order using your desired backend language. Cashfree offers backend SDKs to simplify the integration process. You can find the SDKs here.
import { Cashfree, CFEnvironment } from "cashfree-pg";

const cashfree = new Cashfree(
	CFEnvironment.PRODUCTION,
	"{Client ID}",
	"{Client Secret Key}"
);

function createOrder() {
	var request = {
		order_amount: "1",
		order_currency: "INR",
		customer_details: {
			customer_id: "node_sdk_test",
			customer_name: "",
			customer_email: "example@gmail.com",
			customer_phone: "9999999999",
		},
		order_meta: {
			return_url:
				"https://test.cashfree.com/pgappsdemos/return.php?order_id=order_123",
		},
		order_note: "",
	};

	cashfree
		.PGCreateOrder(request)
		.then((response) => {
			var a = response.data;
			console.log(a);
		})
		.catch((error) => {
			console.error("Error setting up order request:", error.response.data);
		});
}
After successfully creating an order, you will receive a unique order_id and payment_session_id that you need for subsequent steps. You can view all the complete api request and response for /orders here.

Step 2: Opening the Payment Page

Web Checkout is a streamlined payment solution that integrates Cashfree’s payment gateway into your iOS app through our SDK. This implementation uses a WebView to provide a secure, feature-rich payment experience. Your customers are presented with a familiar web interface where they can enter their payment details and complete their transaction seamlessly. All payment logic, UI components, and security measures are managed by our SDK, eliminating the need for complex custom implementation. To complete the payment, we can follow the following steps:
  1. Create a CFSession object.
  2. Create a Web Checkout Payment object.
  3. Set payment callback.
  4. Initiate the payment using the payment object created

Create a Session

This object contains essential information about the order, including the payment session ID (payment_session_id) and order ID (order_id) obtained from Step 1. It also specifies the environment (sandbox or production).
do {
    let session = try CFSession.CFSessionBuilder()
        .setOrderID(order_id)
        .setPaymentSessionId(payment_session_id)
        .setEnvironment(Utils.environment)
        .build()
      return session;
} catch let e {
    let error = e as! CashfreeError
    self.createAlert(title: "Warning", message: error.localizedDescription)
}

Create a Web Checkout Payment object

Use CFWebCheckoutPayment to create the payment object. This object acceps a CFSession, like the one created in the previous step.
let webCheckoutPayment = try CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder()
    .setSession(session)
    .build()

Setup callback

You need to set up callback handlers to handle events after payment processing.. The callback implements CFResponseDelegate to handle payment responses and errors. It must be initialized in viewDidLoad by calling CFPaymentGatewayService.getInstance().setCallback(self).
  • onError: Handles payment failures by displaying an alert with error details
  • verifyPayment: Called when payment needs merchant verification, shows status alert to user
Make sure to set the callback at activity’s onCreate as this also handles the activity restart cases.
extension ViewController: CFResponseDelegate {
        
    func onError(_ error: CFErrorResponse, order_id: String) {
        self.createAlert(title: error.status ?? "ERROR", message: error.message ?? "error_message_not_present")
    }
    
    func verifyPayment(order_id: String) {
        self.createAlert(title: "VERIFY PAYMENT", message: "Payment has to be verified by merchant for \(order_id)")
    }
        
}

// Class Variable
let pgService = CFPaymentGatewayService.getInstance()

override func viewDidLoad() {
   super.viewDidLoad()
   pgService.setCallback(self) 
}

Step 3: Sample Code

import CashfreeAnalyticsSDK
import CashfreePG
import CashfreePGCoreSDK
import CashfreePGUISDK

class ViewController: UIViewController, CFResponseDelegate {

  // Class Variable
  let pgService = CFPaymentGatewayService.getInstance()

  override func viewDidLoad() {
    super.viewDidLoad()
    pgService.setCallback(self)
  }

  @IBAction func webCheckoutButtonTapped(_ sender: Any) {
    do {
      let session = try CFSession.CFSessionBuilder()
        .setPaymentSessionId(payment_session_id)
        .setOrderID(order_id)
        .setEnvironment(Utils.environment)
        .build()
      let webCheckoutPayment = try CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder()
        .setSession(session)
        .build()
      try pgService.doPayment(webCheckoutPayment, viewController: self)
    } catch let e {
      let err = e as! CashfreeError
      print(err.description)
    }

  }

  // Protocol Implementation
  func onError(_ error: CFErrorResponse, order_id: String) {
    self.createAlert(
      title: error.status ?? "ERROR", message: error.message ?? "error_message_not_present")
  }

  func verifyPayment(order_id: String) {
    self.createAlert(
      title: "VERIFY PAYMENT", message: "Payment has to be verified by merchant for \(order_id)")
  }
}

Step 4: Confirming the Payment

Once the payment is completed, you need to confirm whether the payment was successful by checking the order status. Once the payment finishes, the user will be redirected back to your activity.
Ensure you check the order status from your server endpoint.
To verify an order you can call our /pg/orders endpoint from your backend. You can also use our SDK to achieve the same.
version := "2023-08-01"
response, httpResponse, err := cashfree.PGFetchOrder(&version, "<order_id>", nil, nil, nil)
if err != nil {
	fmt.Println(err.Error())
} else {
	fmt.Println(httpResponse.StatusCode)
	fmt.Println(response)
}

Testing

You should now have a working checkout button that redirects your customer to Cashfree Checkout.
  1. Click the checkout button.
  2. You’re redirected to the Cashfree Checkout payment page.

Error Codes

To confirm the error returned in your ios application, you can view the error codes that are exposed by the SDK.
CashfreeError is an Enum that inherits Foundations Error class. The following are some of the error codes that are exposed by the SDK:
ERROR CODESMESSAGE
MISSING_CALLBACKThe callback is missing in the request.
ORDER_ID_MISSINGThe “order_id” is missing in the request.
CARD_EMI_TENURE_MISSINGThe “emi_tenure” is missing or invalid (It has to be greater than 0).
INVALID_UPI_APP_ID_SENTThe id sent is invalid. The value has to be one of the following: “tez://”,“phonepe://”,“paytmmp://”,“bhim://. Please refer the note in CFUPI class for more details
INVALID_PAYMENT_OBJECT_SENTThe payment object that is set does not match any payment mode. Please set the correct payment mode and try again.
WALLET_OBJECT_MISSINGThe CFWallet object is missing in the request
NETBANKING_OBJECT_MISSINGThe CFNetbanking object is missing in the request.
UPI_OBJECT_MISSINGThe CFUPI object is missing in the request.
CARD_OBJECT_MISSINGThe CFCard object is missing in the request.
INVALID_WEB_DATAThe url seems to be corrupt. Please reinstantiate the order.
SESSION_OBJECT_MISSINGThe “session” is missing in the request
PAYMENT_OBJECT_MISSINGThe “payment” is missing in the request
ENVIRONMENT_MISSINGThe “environment” is missing in the request.
ORDER_TOKEN_MISSINGThe “order_token” is missing in the request.
CHANNEL_MISSINGThe “channel” is missing in the request.
CARD_NUMBER_MISSINGThe “card_number” is missing in the request.
CARD_EXPIRY_MONTH_MISSINGThe “card_expiry_mm” is missing in the request.
CARD_EXPIRY_YEAR_MISSINGThe “card_expiry_yy” is missing in the request.
CARD_CVV_MISSINGThe “card_cvv” is missing in the request.
UPI_ID_MISSINGThe “upi_id” is missing in the request
WALLET_CHANNEL_MISSINGThe “channel” is missing in the wallet payment request
WALLET_PHONE_MISSINGThe “phone number” is missing in the wallet payment request
NB_BANK_CODE_MISSINGThe “bank_code” is missing in the request

💻 Quick dev-to-dev talk

You clearly care about building better payment experiences for your clients, here’s a quick tip: Earn additional income doing exactly what you’re doing now!Join the Cashfree Affiliate Partner Program and get rewarded every time your clients use Cashfree.What’s in it for you?
  • Earn up to 0.25% commission on every transaction
  • Be more than a dev - be the trusted fintech partner for your clients
  • Get a dedicated partner manager, your go-to expert
What’s in it for your clients?
  • Instant activation, go live in minutes.
  • Industry-best success rate across all payment modes.
  • Effortlessly accept international payments in 140+ currencies
Ready to push to prod? 👉 Become a Partner now