---
page_title: 2. Initialize SDK
product: Hypercheckout
platform: iOS
page_source: https://juspay.io/in/docs/hyper-checkout/ios/base-sdk-integration/initiating-sdk
llms_txt: https://juspay.io/in/docs/llms.txt
product_llms_txt: https://juspay.io/in/docs/hyper-checkout/llms.txt
---


# 2. Initiating the SDK



To initialise the SDK, client needs to call the `initiate` SDK function. The initiate function call boots up the Hypercheckout SDK and makes it ready for all other operations

Follow the below steps to make an initiate SDK call

> **Error**
> Initiate is to be called in viewDidLoad function of the home screen view controller. Not following this will lead to increased Hypercheckout latency.




### Step 2.1. Import HyperSDK


Import the HyperSDK namespace to get access to HyperServices class in your code



#### Code Snippets: -

#### Swift Code Snippet:

```swift
import HyperSDK
```

#### ObjectiveC Code Snippet:

```objectivec
#import <HyperSDK/HyperSDK.h>
```



### Step 2.2. Create an instance of HyperServices


The Hypercheckout SDK exposes the `HyperServices` class. Create an object of this class for all upcoming operations



#### Code Snippets: -

#### Swift Code Snippet:

```swift
let hyperInstance = HyperServices();
```

#### ObjectiveC Code Snippet:

```objectivec
self.hyperInstance = [[HyperServices alloc] init];
```



### Step 2.3. Create Initiate payload


Initiate takes three parameters as input. One of the parameter is a JSON object referred as `InitiatePayload`. This payload contains certain key value pairs used by the SDK to perform a successful initiate

Refer to the following table for information about the description and sample payload.


### Payload
- **RequestId**:
  - Description: Unique uuid-v4 string
  - Value: $requestId
  - Tags: String, Mandatory
- **Service**:
  - Description: Value: in.juspay.hyperpay
  - Tags: String, Mandatory
- **Payload**:
  - Description: Parameters
  - Value:
    - **Action**:
      - Description: Value: initiate
      - Tags: String, Mandatory
    - **MerchantId**:
      - Description: Unique merchant id shared during onboarding
      - Tags: String, Mandatory
    - **ClientId**:
      - Description: Unique Client id shared during onboarding
      - Tags: String, Mandatory
    - **Environment**:
      - Description: Environment to be used for the session. Accepted value is “production” / “sandbox“
      - Tags: String, Mandatory
  - Tags: JSON, Mandatory




#### Code Snippets: -

#### Swift Code Snippet:

```swift
func createInitiatePayload() -> [String: Any] {
        let innerPayload : [String: Any] = [
            "action": "initiate",
            "merchantId": "testhdfc1",
            "clientId": "hdfcmaster",
            "xRoutingId": "x-routing-id-value",
            "environment": "sandbox"
        ];
        
        let sdkPayload : [String: Any] = [
            "requestId": UUID().uuidString,
            "service": "in.juspay.hyperpay",
            "payload": innerPayload
        ]
        
        return sdkPayload
    }
```

#### ObjectiveC Code Snippet:

```objectivec
- (NSDictionary *)createInitiatePayload {
    NSDictionary *innerPayload = @{
        @"action": @"initiate",
        @"merchantId": @"<MERCHANT_ID>",
        @"clientId": @"<CLIENT_ID>",
        @"x-routing-id": @"<CLIENT_ID>",
        @"environment": @"production"
    };

    NSDictionary *sdkPayload = @{
        @"requestId": @"12398b5571d74c3388a74004bc24370c",
        @"service": @"in.juspay.hyperpay",
        @"payload": innerPayload
    };

    return sdkPayload;
}
```



### Step 2.4. Create CallbackHandler


During its lifecycle, SDK emits multiple events to communicate about the transaction status. All of these events are received by an instance of `HyperPaymentsCallbackAdapter`.

This callback handler is passed as the second argument to the initiate call.



#### Code Snippets: -

#### Swift Code Snippet:

```swift
func hyperCallbackHandler(response: [String: Any]?) {
        if let data = response, let event = data["event"] as? String {
            if event == "hide_loader" {
                // hide loader
            }
            // Handle Process Result
            // This case will reach once the Hypercheckout screen closes
            // block:start:handle-process-result
            else if event == "process_result" {
                let error = data["error"] as? Bool ?? false
                
                if let innerPayload = data["payload"] as? [String: Any] {
                    let status = innerPayload["status"] as? String
                    let pi = innerPayload["paymentInstrument"] as? String
                    let pig = innerPayload["paymentInstrumentGroup"] as? String
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    
                    if !error {
                        performSegue(withIdentifier: "statusSegue", sender: status)
                        // txn success, status should be "charged"
                        // process data -- show pi and pig in UI maybe also?
                        // example -- pi: "PAYTM", pig: "WALLET"
                        // call orderStatus once to verify (false positives)
                    } else {
                        let errorCode = data["errorCode"] as? String
                        let errorMessage = data["errorMessage"] as? String
                        switch status! {
                        case "backpressed":
                            // user back-pressed from PP without initiating any txn
                            let alertController = UIAlertController(title: "Payment Cancelled", message: "User clicked back button on Payment Page", preferredStyle: .alert)
                            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                            alertController.addAction(okAction)
                            present(alertController, animated: true, completion: nil)

                            break
                        case "user_aborted":
                            // user initiated a txn and pressed back
                            // poll order status
                            let alertController = UIAlertController(title: "Payment Aborted", message: "Transaction aborted by user", preferredStyle: .alert)
                            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                            alertController.addAction(okAction)
                            present(alertController, animated: true, completion: nil)
                            break
                        case "pending_vbv", "authorizing":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // txn in pending state
                            // poll order status until backend says fail or success
                            break
                        case "authorization_failed", "authentication_failed", "api_failure":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // txn failed
                            // poll orderStatus to verify (false negatives)
                            break
                        case "new":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // order created but txn failed
                            // very rare for V2 (signature based)
                            // also failure
                            // poll order status
                            break
                        default:
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // unknown status, this is also failure
                            // poll order status
                            break
                        }
                    }
                }
            }
            // block:end:handle-process-result
        }
    }
```

#### ObjectiveC Code Snippet:

```objectivec
self.hyperCallbackHandler = ^(NSDictionary<NSString *,id> * _Nullable response) {
        NSDictionary *data = response;
        NSString *event = data[@"event"];
        
        if ([event isEqualToString:@"hide_loader"]) {
            // hide loader
        }
        // Handle Process Result
        // This case will reach once the Hypercheckout screen closes
        // block:start:handle-process-result

        else if ([event isEqualToString:@"process_result"]) {
            BOOL error = [data[@"error"] boolValue];

            NSDictionary *innerPayload = data[@"payload"];
            NSString *status = innerPayload[@"status"];
            NSString *pi = innerPayload[@"paymentInstrument"];
            NSString *pig = innerPayload[@"paymentInstrumentGroup"];

            if (!error) {
                // txn success, status should be "charged"
                // process data -- show pi and pig in UI maybe also?
                // example -- pi: "PAYTM", pig: "WALLET"
                // call orderStatus once to verify (false positives)
            } else {

                NSString *errorCode = data[@"errorCode"];
                NSString *errorMessage = data[@"errorMessage"];
                if([status isEqualToString:@"backpressed"]) {
                    // user back-pressed from PP without initiating any txn
                }
                else if ([status isEqualToString:@"backpressed"]) {
                    // user initiated a txn and pressed back
                    // poll order status
                } else if ([status isEqualToString:@"pending_vbv"] || [status isEqualToString:@"authorizing"]) {
                    // txn in pending state
                    // poll order status until backend says fail or success
                } else if ([status isEqualToString:@"authorization_failed"] || [status isEqualToString:@"authentication_failed"] || [status isEqualToString:@"api_failure"]) {
                    // txn failed
                    // poll orderStatus to verify (false negatives)
                } else if([status isEqualToString:@"new"]) {
                    // order created but txn failed
                    // very rare for V2 (signature based)
                    // also failure
                    // poll order status
                } else {
                    // unknown status, this is also failure
                    // poll order status
                }
            }
        }
        // block:end:handle-process-result
    };
```



### Step 2.5. Call initiate


The final step is to call the `Initiate`function.

The initiate method takes three parameters: `ViewController` and `InitiatePayload` and `HyperPaymentsCallbackAdapter`. Use the functions created in the above steps to create the parameters

> **Warning**
> Initiate is a fire-and-forget call. For every HyperService instance you should **call initiate only once.** 





#### Code Snippets: -

#### Swift Code Snippet:

```swift
hyperInstance.initiate(
            self,
            payload: createInitiatePayload(),
            callback: hyperCallbackHandler
        )
```

#### ObjectiveC Code Snippet:

```objectivec
NSDictionary *initPayload = [self createInitiatePayload];
    [self.hyperInstance initiate:self payload:initPayload callback:self.hyperCallbackHandler];
```


---

## Complete Code Reference

The following code files are referenced in the steps above:

### ProductsViewController.swift

```
//
//  ProductsViewController.swift
//  juspay-sdk-integration-swift
//
//  Created by Arbinda Kumar Prasad on 08/06/23.
//

import UIKit

// Importing Hyper SDK
// block:start:import-hyper-sdk
import HyperSDK
// block:end:import-hyper-sdk


// Creating an object of HyperServices class.
// block:start:create-hyper-services-instance
let hyperInstance = HyperServices();
// block:end:create-hyper-services-instance

var p1Price = 1
var p2Price = 2
var p1Qnty = 3
var p2Qnty = 4

class ProductsViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        p1Outlet.text = "\(p1Qnty)"
        p2Outlet.text = "\(p2Qnty)"

        // Calling initiate on hyperService instance to boot up payment engine.
        // block:start:initiate-sdk
        hyperInstance.initiate(
            self,
            payload: createInitiatePayload(),
            callback: hyperCallbackHandler
        )
        // block:end:initiate-sdk
    }

    // Creating initiate payload JSON object
    // block:start:create-initiate-payload
    func createInitiatePayload() -> [String: Any] {
        let innerPayload : [String: Any] = [
            "action": "initiate",
            "merchantId": "testhdfc1",
            "clientId": "hdfcmaster",
            "xRoutingId": "x-routing-id-value",
            "environment": "sandbox"
        ];
        
        let sdkPayload : [String: Any] = [
            "requestId": UUID().uuidString,
            "service": "in.juspay.hyperpay",
            "payload": innerPayload
        ]
        
        return sdkPayload
    }
    // block:end:create-initiate-payload
    
    @IBOutlet weak var p1Outlet: UITextView!
    
    
    @IBOutlet weak var p2Outlet: UITextView!


    // Creating HyperPaymentsCallbackAdapter
    // This callback will get all events from hyperService instance
    // block:start:create-hyper-callback
    func hyperCallbackHandler(response: [String: Any]?) {
        if let data = response, let event = data["event"] as? String {
            if event == "hide_loader" {
                // hide loader
            }
            // Handle Process Result
            // This case will reach once the Hypercheckout screen closes
            // block:start:handle-process-result
            else if event == "process_result" {
                let error = data["error"] as? Bool ?? false
                
                if let innerPayload = data["payload"] as? [String: Any] {
                    let status = innerPayload["status"] as? String
                    let pi = innerPayload["paymentInstrument"] as? String
                    let pig = innerPayload["paymentInstrumentGroup"] as? String
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    
                    if !error {
                        performSegue(withIdentifier: "statusSegue", sender: status)
                        // txn success, status should be "charged"
                        // process data -- show pi and pig in UI maybe also?
                        // example -- pi: "PAYTM", pig: "WALLET"
                        // call orderStatus once to verify (false positives)
                    } else {
                        let errorCode = data["errorCode"] as? String
                        let errorMessage = data["errorMessage"] as? String
                        switch status! {
                        case "backpressed":
                            // user back-pressed from PP without initiating any txn
                            let alertController = UIAlertController(title: "Payment Cancelled", message: "User clicked back button on Payment Page", preferredStyle: .alert)
                            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                            alertController.addAction(okAction)
                            present(alertController, animated: true, completion: nil)

                            break
                        case "user_aborted":
                            // user initiated a txn and pressed back
                            // poll order status
                            let alertController = UIAlertController(title: "Payment Aborted", message: "Transaction aborted by user", preferredStyle: .alert)
                            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                            alertController.addAction(okAction)
                            present(alertController, animated: true, completion: nil)
                            break
                        case "pending_vbv", "authorizing":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // txn in pending state
                            // poll order status until backend says fail or success
                            break
                        case "authorization_failed", "authentication_failed", "api_failure":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // txn failed
                            // poll orderStatus to verify (false negatives)
                            break
                        case "new":
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // order created but txn failed
                            // very rare for V2 (signature based)
                            // also failure
                            // poll order status
                            break
                        default:
                            performSegue(withIdentifier: "statusSegue", sender: status)
                            // unknown status, this is also failure
                            // poll order status
                            break
                        }
                    }
                }
            }
            // block:end:handle-process-result
        }
    }
    // block:end:create-hyper-callback
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "statusSegue" {
            if let destinationVC = segue.destination as? StatusViewController {                
                if let txnStatus = sender as? String {
                    print(txnStatus)
                    destinationVC.txnStatus = txnStatus
                }
            }
            if let txnStatus = sender as? String {
                print(txnStatus) 
            }
        }
    }
    
    @IBAction func increaseP1Qnty(_ sender: Any) {
        p1Qnty = p1Qnty + 1
        p1Outlet.text = "\(p1Qnty)"

    }
    @IBAction func decreaseP1Qnty(_ sender: Any) {
        p1Qnty = p1Qnty - 1
        p1Outlet.text = "\(p1Qnty)"

    }
    @IBAction func decreaseP2Qnty(_ sender: Any) {
        p2Qnty = p2Qnty - 1
        p2Outlet.text = "\(p2Qnty)"
    }
    @IBAction func increaseP2Qnty(_ sender: Any) {
        p2Qnty = p2Qnty + 1
        p2Outlet.text = "\(p2Qnty)"
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    */
    


}

```

### ViewController.m

```
//
//  IntegViewController.m
//  DevTools
//
//  Created by Balaganesh on 04/04/22.
//  Copyright © 2022 Juspay. All rights reserved.
//

#import "ViewController.h"

// Importing Hyper SDK
// block:start:import-hyper-sdk
#import <HyperSDK/HyperSDK.h>
// block:end:import-hyper-sdk

@interface ViewController ()

// Declaring HyperServices property
@property (nonatomic, strong) HyperServices *hyperInstance;
@property (nonatomic, copy) HyperSDKCallback hyperCallbackHandler;

@end

@implementation ViewController


// Creating initiate payload JSON object
// block:start:create-initiate-payload
- (NSDictionary *)createInitiatePayload {
    NSDictionary *innerPayload = @{
        @"action": @"initiate",
        @"merchantId": @"<MERCHANT_ID>",
        @"clientId": @"<CLIENT_ID>",
        @"x-routing-id": @"<CLIENT_ID>",
        @"environment": @"production"
    };

    NSDictionary *sdkPayload = @{
        @"requestId": @"12398b5571d74c3388a74004bc24370c",
        @"service": @"in.juspay.hyperpay",
        @"payload": innerPayload
    };

    return sdkPayload;
}
// block:end:create-initiate-payload


// Creating process payload JSON object
// block:start:fetch-process-payload
- (NSDictionary *)createProcessPayload {
    // Make an API Call to your server to create Session and return SDK Payload
    //Payload received from Session API call
    NSDictionary *sdkProcessPayload = @{
        @"clientId": @"<your_client_id>",
        @"x-routing-id": @"<your_client_id>",
        @"amount": @"1.0",
        @"merchantId": @"<your_merchant_id>",
        @"clientAuthToken": @"tkn_xxxxxxxxxxxxxxxxxxxxx",
        @"clientAuthTokenExpiry": @"2022-03-12T20:29:23Z",
        @"environment": @"sandbox",
        @"lastName": @"wick",
        @"action": @"paymentPage",
        @"customerId": @"testing-customer-one",
        @"returnUrl": @"https://shop.merchant.com",
        @"currency": @"INR",
        @"firstName": @"John",
        @"customerPhone": @"9876543210",
        @"customerEmail": @"test@mail.com",
        @"orderId": @"testing-order-one",
        @"description": @"Complete your payment"
    };
    
    NSDictionary *sdkPayload = @{
        @"requestId": NSUUID.UUID.UUIDString,
        @"service": @"in.juspay.hyperpay",
        @"payload": sdkProcessPayload
    };

    return sdkPayload;
}
// block:end:fetch-process-payload

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //block:start:create-hyper-services-instance
    self.hyperInstance = [[HyperServices alloc] init];
    //block:end:create-hyper-services-instance
    
    //block:start:create-hyper-callback
    self.hyperCallbackHandler = ^(NSDictionary<NSString *,id> * _Nullable response) {
        NSDictionary *data = response;
        NSString *event = data[@"event"];
        
        if ([event isEqualToString:@"hide_loader"]) {
            // hide loader
        }
        // Handle Process Result
        // This case will reach once the Hypercheckout screen closes
        // block:start:handle-process-result

        else if ([event isEqualToString:@"process_result"]) {
            BOOL error = [data[@"error"] boolValue];

            NSDictionary *innerPayload = data[@"payload"];
            NSString *status = innerPayload[@"status"];
            NSString *pi = innerPayload[@"paymentInstrument"];
            NSString *pig = innerPayload[@"paymentInstrumentGroup"];

            if (!error) {
                // txn success, status should be "charged"
                // process data -- show pi and pig in UI maybe also?
                // example -- pi: "PAYTM", pig: "WALLET"
                // call orderStatus once to verify (false positives)
            } else {

                NSString *errorCode = data[@"errorCode"];
                NSString *errorMessage = data[@"errorMessage"];
                if([status isEqualToString:@"backpressed"]) {
                    // user back-pressed from PP without initiating any txn
                }
                else if ([status isEqualToString:@"backpressed"]) {
                    // user initiated a txn and pressed back
                    // poll order status
                } else if ([status isEqualToString:@"pending_vbv"] || [status isEqualToString:@"authorizing"]) {
                    // txn in pending state
                    // poll order status until backend says fail or success
                } else if ([status isEqualToString:@"authorization_failed"] || [status isEqualToString:@"authentication_failed"] || [status isEqualToString:@"api_failure"]) {
                    // txn failed
                    // poll orderStatus to verify (false negatives)
                } else if([status isEqualToString:@"new"]) {
                    // order created but txn failed
                    // very rare for V2 (signature based)
                    // also failure
                    // poll order status
                } else {
                    // unknown status, this is also failure
                    // poll order status
                }
            }
        }
        // block:end:handle-process-result
    };
    //block:end:create-hyper-callback
    
}


- (IBAction)initiatePayments:(id)sender {
    // Calling initiate on hyperService instance to boot up payment engine.
    // block:start:initiate-sdk
    NSDictionary *initPayload = [self createInitiatePayload];
    [self.hyperInstance initiate:self payload:initPayload callback:self.hyperCallbackHandler];
    // block:end:initiate-sdk
}
- (IBAction)startPayments:(id)sender {
    // Calling process on hyperService to open the Hypercheckout screen
    // block:start:process-sdk
    NSDictionary *processPayload = [self createProcessPayload];
    [self.hyperInstance process:processPayload];
    // block:end:process-sdk
}


@end

```


---

## See Also

- [1. Getting SDK](https://juspay.io/in/docs/hyper-checkout/ios/base-sdk-integration/1-getting-sdk)
- [3. Open Hypercheckout Screen](https://juspay.io/in/docs/hyper-checkout/ios/base-sdk-integration/open-hypercheckout-screen)
