---
page_title: 3. Initialize SDK
product: EC Headless
platform: Android
page_source: https://juspay.io/in/docs/ec-headless/android/base-sdk-integration/initiating-sdk
llms_txt: https://juspay.io/in/docs/llms.txt
product_llms_txt: https://juspay.io/in/docs/ec-headless/llms.txt
---


## 3. Initiating the SDK



To initialise the SDK, client needs to call the `initiate` SDK API. The initiate api call boots up Express Checkout 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 the onCreate() method of your application's main activity (Home screen). Not following this will lead to increased latency.




### Step 3.1. Create an instance of HyperServices


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



#### Code Snippets: -

#### Java Code Snippet:

```java
hyperServicesHolder = new HyperServiceHolder(this);
```



### Step 3.2. Create Initiate payload


Initiate API takes two 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 request and response payload


## Request Payload
- **RequestID**:
  - Description: Unique uuid-v4 string
    
    Example: abcd-12345-abcd-12345
  - Value: value
  - Tags: String, Mandatory
- **Service**:
  - Description: Value: in.juspay.hyperapi
  - Tags: String, Mandatory
- **Payload**:
  - Description: Parameters required to call Hyper SDK API
  - Value:
    - **Action**:
      - Description: Operation to be performed in the SDK. Should be initiate for this call.
        
        Value: initiate
      - Tags: String, Mandatory
    - **Merchant_id**:
      - Description: The merchant id provided by Juspay
      - Tags: String, Mandatory
    - **Client_id**:
      - Description: Unique identifier associated with static resources assigned by juspay.
        
        Same as merchant_id
      - Tags: String, Mandatory
    - **Environment**:
      - Description: Juspay remote environment to be used for completing an operation.
        
        For production, pass `production`To be used for Live trafficFor sandbox,     pass `sandbox.`To be used for UAT/testing environment
      - Tags: String, Mandatory
  - Tags: JSON, Mandatory


## Response Payload
- **200**:
  - Value:
    - **RequestID**:
      - Description: Unique uuid-v4 string
        
        Example: abcd-12345-abcd-12345
      - Tags: String
    - **Service**:
      - Description: Value: in.juspay.hyperapi
      - Tags: String
    - **Payload**:
      - Value:
        - **Action**:
          - Description: Value: initiate
          - Tags: String
        - **Status**:
          - Description: Status of the SDK call
            
            Value: success
          - Tags: String
      - Tags: JSON
    - **Error**:
      - Description: false in case of success response
      - Tags: Boolean
    - **ErrorMessage**:
      - Description: empty in case of success response
      - Tags: String
    - **ErrorCode**:
      - Description: empty in case of success response
      - Tags: String
  - Tags: Success
- **400**:
  - Value:
    - **Error_code**:
      - Description: Example: JP_003
      - Tags: String
    - **Error_message**:
      - Description: Description of the error
      - Tags: String
    - **Error**:
      - Description: Value: true in case of non-200 response
      - Tags: Boolean
  - Tags: Invalid Input Data





#### Code Snippets: -

#### Java Code Snippet:

```java
// This function creates intiate payload.
    private JSONObject createInitiatePayload() {
        JSONObject sdkPayload = new JSONObject();
        JSONObject innerPayload = new JSONObject();
        try {
            // generating inner payload
            innerPayload.put("action", "initiate");
            innerPayload.put("merchantId", "<MERCHANT_ID>");      // Put your Merchant ID here
            innerPayload.put("clientId", "<CLIENT_ID>");          // Put your Client ID here
            innerPayload.put("customerId", "<CUSTOMER_Id>");      // Any unique refrences to current customer
            innerPayload.put("xRoutingId", "<XROUTING_ID>");      // Put your X-Routing ID here
            innerPayload.put("environment", "prod");
            sdkPayload.put("requestId",  ""+ UUID.randomUUID());
            sdkPayload.put("service", "in.juspay.hyperapi");
            sdkPayload.put("payload", innerPayload);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sdkPayload;
    }
```



### Step 3.3. 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 API call.



#### Code Snippets: -

#### Java Code Snippet:

```java
private HyperPaymentsCallbackAdapter createHyperPaymentsCallbackAdapter() {
        return new HyperPaymentsCallbackAdapter() {
            @Override
            public void onEvent(JSONObject jsonObject, JuspayResponseHandler responseHandler) {
                Intent redirect = new Intent(CheckoutActivity.this, ResponsePage.class);
                redirect.putExtra("responsePayload", jsonObject.toString());
                System.out.println(jsonObject);
                try {
                    String event = jsonObject.getString("event");
                    if (event.equals("hide_loader")) {
                        // Hide Loader
                        dialog.hide();
                    }
                    else if (event.equals("initiate_result")) {
                        boolean error = jsonObject.optBoolean("error");
                        JSONObject innerPayload = jsonObject.optJSONObject("payload");
                        String status = innerPayload.optString("status");
                        if (status.equals("success")) {
                            // Initiate was successful, handle accordingly (call Process)
                        } else {
                            // Initiate failed, handle accordingly (call initiate() again)
                        }
                    }
                    // Handle Process Result
                    // This case will reach once the Hypercheckout screen closes
                    // block:start:handle-process-result
                    else if (event.equals("process_result")) {
                        boolean error = jsonObject.optBoolean("error");
                        JSONObject innerPayload = jsonObject.optJSONObject("payload");
                        String status = innerPayload.optString("status");

                        if (!error) {
                            switch (status) {
                                case "charged":
                                    // Successful Transaction
                                    // check order status via S2S API
                                    redirect.putExtra("status", "OrderSuccess");
                                    startActivity(redirect);
                                    break;
                                case "cod_initiated":
                                    redirect.putExtra("status", "CODInitiated");
                                    startActivity(redirect);
                                    break;
                            }
                        } else {
                            switch (status) {
                                case "backpressed":
                                    // user back-pressed from PP without initiating transaction

                                    break;
                                case "user_aborted":
                                    // user initiated a txn and pressed back
                                    // check order status via S2S API
                                    Intent successIntent = new Intent(CheckoutActivity.this, ResponsePage.class);
                                    redirect.putExtra("status", "UserAborted");
                                    startActivity(redirect);
                                    break;
                                case "pending_vbv":
                                    redirect.putExtra("status", "PendingVBV");
                                    startActivity(redirect);
                                    break;
                                case "authorizing":
                                    // txn in pending state
                                    // check order status via S2S API
                                    redirect.putExtra("status", "Authorizing");
                                    startActivity(redirect);
                                    break;
                                case "authorization_failed":
                                    redirect.putExtra("status", "AuthorizationFailed");
                                    startActivity(redirect);
                                    break;
                                case "authentication_failed":
                                    redirect.putExtra("status", "AuthenticationFailed");
                                    startActivity(redirect);
                                    break;
                                case "api_failure":
                                    redirect.putExtra("status", "APIFailure");
                                    startActivity(redirect);
                                    break;
                                    // txn failed
                                    // check order status via S2S API
                            }
                        }
                    }
                    // block:end:handle-process-result
                } catch (Exception e) {
                    // merchant code...
                }
            }
        };
    }
```



### Step 3.4. Call initiate


The final step is to call the `Initiate SDK API`.

The initiate method takes two parameters: `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: -

#### Java Code Snippet:

```java
//This function initiate the Juspay SDK
    private void initiatePaymentsSDK() {
        if(!hyperServicesHolder.isInitiated()){
            initiatePayload = createInitiatePayload();
            HyperPaymentsCallbackAdapter callbackAdapter = createHyperPaymentsCallbackAdapter()
            hyperServicesHolder.setCallback(callbackAdapter);
            hyperServicesHolder.initiate(initiatePayload);
            //Showing snackbar
            Helper helper = new Helper();
            CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinatorLayout2);
            helper.showSnackbar("Initiate Called!", coordinatorLayout);
        }
    }
```


---

## Complete Code Reference

The following code files are referenced in the steps above:

### ProductsActivity.java

```
package in.juspay.devtools;

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.util.UUID;
import in.juspay.hyperinteg.HyperServiceHolder;


public class ProductsActivity extends AppCompatActivity {
    private Button proceedButton;
    private TextView itemCountTv1, itemCountTv2;
    private HyperServiceHolder hyperServicesHolder;
    private JSONObject initiatePayload;
    protected CoordinatorLayout coordinatorLayout;
    private int item1Count = 1, item2Count = 0, item1Price = 1, item2Price = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_products);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //block:start:create-hyper-services-instance
        
        hyperServicesHolder = new HyperServiceHolder(this);

        //block:end:create-hyper-services-instance
        initiatePaymentsSDK();
        proceedButton = findViewById(R.id.rectangle_8);
        itemCountTv1 = findViewById(R.id.some_id);
        itemCountTv2 = findViewById(R.id.some_id2);
        proceedButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(item1Count>=1 || item2Count >=1){
                    Intent intent = new Intent(ProductsActivity.this, CheckoutActivity.class);
                    intent.putExtra("item1Count", item1Count);
                    intent.putExtra("item2Count", item2Count);
                    intent.putExtra("item1Price", item1Price);
                    intent.putExtra("item2Price", item2Price);
                    startActivity(intent);
                } else {
                    Toast.makeText(ProductsActivity.this, "You should add atlease one item", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    
    //block:start:call-initiate
    //This function initiate the Juspay SDK
    private void initiatePaymentsSDK() {
        if(!hyperServicesHolder.isInitiated()){
            initiatePayload = createInitiatePayload();
            HyperPaymentsCallbackAdapter callbackAdapter = createHyperPaymentsCallbackAdapter()
            hyperServicesHolder.setCallback(callbackAdapter);
            hyperServicesHolder.initiate(initiatePayload);
            //Showing snackbar
            Helper helper = new Helper();
            CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinatorLayout2);
            helper.showSnackbar("Initiate Called!", coordinatorLayout);
        }
    }
    //block:end:call-initiate

    
    
    //block:start:create-initiate-payload
    // This function creates intiate payload.
    private JSONObject createInitiatePayload() {
        JSONObject sdkPayload = new JSONObject();
        JSONObject innerPayload = new JSONObject();
        try {
            // generating inner payload
            innerPayload.put("action", "initiate");
            innerPayload.put("merchantId", "<MERCHANT_ID>");      // Put your Merchant ID here
            innerPayload.put("clientId", "<CLIENT_ID>");          // Put your Client ID here
            innerPayload.put("customerId", "<CUSTOMER_Id>");      // Any unique refrences to current customer
            innerPayload.put("xRoutingId", "<XROUTING_ID>");      // Put your X-Routing ID here
            innerPayload.put("environment", "prod");
            sdkPayload.put("requestId",  ""+ UUID.randomUUID());
            sdkPayload.put("service", "in.juspay.hyperapi");
            sdkPayload.put("payload", innerPayload);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sdkPayload;
    }
    //block:end:create-initiate-payload


    public void add1Clicked(View v){
        item1Count += 1;
        itemCountTv1.setText(Integer.toString(item1Count));
    }
    public void add2Clicked(View v){
        item2Count += 1;
        itemCountTv2.setText(Integer.toString(item2Count));

    }
    public void remove1Clicked(View v){
        if(item1Count<1){
            Toast.makeText(this, "Cannot remove as item count is already 0.", Toast.LENGTH_SHORT).show();
        } else {
            item1Count -= 1;
            itemCountTv1.setText(Integer.toString(item1Count));
        }
    }
    public void remove2Clicked(View v){
        if(item2Count<1){
            Toast.makeText(this, "Cannot remove as item count is already 0.", Toast.LENGTH_SHORT).show();
        } else {
            item2Count -= 1;
            itemCountTv2.setText(Integer.toString(item2Count));
        }
    }
}

```

### CheckoutActivity.java

```

{
    //block:start:process-sdk-call

    if (hyperInstance.isInitialised()){
    hyperInstance.process(processPayload);
}
    //block:end:process-sdk-call



    // block:start:create-hyper-callback
    
    private HyperPaymentsCallbackAdapter createHyperPaymentsCallbackAdapter() {
        return new HyperPaymentsCallbackAdapter() {
            @Override
            public void onEvent(JSONObject jsonObject, JuspayResponseHandler responseHandler) {
                Intent redirect = new Intent(CheckoutActivity.this, ResponsePage.class);
                redirect.putExtra("responsePayload", jsonObject.toString());
                System.out.println(jsonObject);
                try {
                    String event = jsonObject.getString("event");
                    if (event.equals("hide_loader")) {
                        // Hide Loader
                        dialog.hide();
                    }
                    else if (event.equals("initiate_result")) {
                        boolean error = jsonObject.optBoolean("error");
                        JSONObject innerPayload = jsonObject.optJSONObject("payload");
                        String status = innerPayload.optString("status");
                        if (status.equals("success")) {
                            // Initiate was successful, handle accordingly (call Process)
                        } else {
                            // Initiate failed, handle accordingly (call initiate() again)
                        }
                    }
                    // Handle Process Result
                    // This case will reach once the Hypercheckout screen closes
                    // block:start:handle-process-result
                    else if (event.equals("process_result")) {
                        boolean error = jsonObject.optBoolean("error");
                        JSONObject innerPayload = jsonObject.optJSONObject("payload");
                        String status = innerPayload.optString("status");

                        if (!error) {
                            switch (status) {
                                case "charged":
                                    // Successful Transaction
                                    // check order status via S2S API
                                    redirect.putExtra("status", "OrderSuccess");
                                    startActivity(redirect);
                                    break;
                                case "cod_initiated":
                                    redirect.putExtra("status", "CODInitiated");
                                    startActivity(redirect);
                                    break;
                            }
                        } else {
                            switch (status) {
                                case "backpressed":
                                    // user back-pressed from PP without initiating transaction

                                    break;
                                case "user_aborted":
                                    // user initiated a txn and pressed back
                                    // check order status via S2S API
                                    Intent successIntent = new Intent(CheckoutActivity.this, ResponsePage.class);
                                    redirect.putExtra("status", "UserAborted");
                                    startActivity(redirect);
                                    break;
                                case "pending_vbv":
                                    redirect.putExtra("status", "PendingVBV");
                                    startActivity(redirect);
                                    break;
                                case "authorizing":
                                    // txn in pending state
                                    // check order status via S2S API
                                    redirect.putExtra("status", "Authorizing");
                                    startActivity(redirect);
                                    break;
                                case "authorization_failed":
                                    redirect.putExtra("status", "AuthorizationFailed");
                                    startActivity(redirect);
                                    break;
                                case "authentication_failed":
                                    redirect.putExtra("status", "AuthenticationFailed");
                                    startActivity(redirect);
                                    break;
                                case "api_failure":
                                    redirect.putExtra("status", "APIFailure");
                                    startActivity(redirect);
                                    break;
                                    // txn failed
                                    // check order status via S2S API
                            }
                        }
                    }
                    // block:end:handle-process-result
                } catch (Exception e) {
                    // merchant code...
                }
            }
        };
    }
    // block:end:create-hyper-callback



    //block:start:onBackPressed
    
    @Override
    public void onBackPressed() {
        boolean handleBackpress = hyperServicesHolder.onBackPressed();
        if(!handleBackpress) {
            super.onBackPressed();
        }

    }
    //block:end:onBackPressed

    

    /*
    Optional Block
    These functions are only supposed to be implemented in case if you are overriding
    onActivityResult or onRequestPermissionsResult Life cycle hooks


    - onActivityResult
    - Handling onActivityResult hook and passing data to HyperServices Instance, to handle App Switch
    @Override
    public void onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // block:start:onActivityResult

        // If super.onActivityResult is available use following:
        // super.onActivityResult(requestCode, resultCode, data);

        // In case super.onActivityResult is NOT available please use following:
        // if (data != null) {
        //    hyperServices.onActivityResult(requestCode, resultCode, data);
        // }

        // block:end:onActivityResult

        // Rest of your code.
    }


    - onRequestPermissionsResult
    - Handling onRequestPermissionsResult hook and passing data to HyperServices Instance, to OTP reading permissions
    @Override
    public void onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        // block:start:onRequestPermissionsResult

        //  If super.onRequestPermissionsResult is available use following:
        // super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // In case super.onActivityResult is NOT available please use following:
        // hyperServices.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // block:end:onRequestPermissionsResult
    }
     */
}

```


---

## See Also

- [2. Creating a Customer](https://juspay.io/in/docs/ec-headless/android/base-sdk-integration/creating-a-customer)
- [4. Rendering the Checkout Screen](https://juspay.io/in/docs/ec-headless/android/base-sdk-integration/rendering-the-checkout-screen)
