---
page_source: https://docs.juspay.io/hypercheckout/ios/base-sdk-integration/initiating-sdk
page_title: 2. Initialize SDK
---


# 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
      - 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",
            "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>",
        @"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];
```
