---
page_title: 2. Initialize SDK
product: Hypercheckout
platform: Flutter
page_source: https://juspay.io/in/docs/hyper-checkout/flutter/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

> **Warning**
> Initiate is to be called in the build function of the Home Screen widget. 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

> **Error**
> Make sure that the MainActivity in Android inherits FlutterFragmentActivity instead of FlutterActivity. `android/app/src/main/kotlin/com/example/your_app_name/MainActivity.kt`





#### Code Snippets: -

#### Flutter Code Snippet:

```flutter
import 'package:flutter/material.dart';
import 'package:hypersdkflutter/hypersdkflutter.dart';
import 'package:flutter/services.dart';
import './screens/home.dart';

void main() {
  final hyperSDK = HyperSDK();
  runApp(MyApp(hyperSDK: hyperSDK));
}

class MyApp extends StatelessWidget {
  // Create Juspay Object
  // // block:start:create-hyper-sdk-instance
  final HyperSDK hyperSDK;
  // // block:end:create-hyper-sdk-instance
  const MyApp({Key? key, required this.hyperSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(
        hyperSDK: hyperSDK,
      ),
    );
  }
}

```



### 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: -

#### Flutter Code Snippet:

```flutter
import 'package:flutter/material.dart';
import 'package:hypersdkflutter/hypersdkflutter.dart';
import 'package:flutter/services.dart';
import './screens/home.dart';

void main() {
  final hyperSDK = HyperSDK();
  runApp(MyApp(hyperSDK: hyperSDK));
}

class MyApp extends StatelessWidget {
  // Create Juspay Object
  // // block:start:create-hyper-sdk-instance
  final HyperSDK hyperSDK;
  // // block:end:create-hyper-sdk-instance
  const MyApp({Key? key, required this.hyperSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(
        hyperSDK: hyperSDK,
      ),
    );
  }
}

```



### Step 2.3. Create Initiate payload


Initiate 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 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: -

#### Flutter Code Snippet:

```flutter
var initiatePayload = {
        "requestId": const Uuid().v4(),
        "service": "in.juspay.hyperpay",
        "payload": {
          "action": "initiate",
          "merchantId": "<MERCHANT_ID>",
          "clientId": "<CLIENT_ID>",
          "xRoutingId": "<X_ROUTING_ID>",
          "environment": "production"
        }
      };
```



### Step 2.4. Create CallbackHandler


During its lifecycle, SDK emits multiple events to communicate about the transaction status.

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



#### Code Snippets: -

#### Flutter Code Snippet:

```flutter
void initiateCallbackHandler(MethodCall methodCall) {
    if (methodCall.method == "initiate_result") {
      // check initiate result
    }
  }
```



### Step 2.5. Call initiate


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

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: -

#### Flutter Code Snippet:

```flutter
await widget.hyperSDK.initiate(initiatePayload, initiateCallbackHandler);
```


---

## Complete Code Reference

The following code files are referenced in the steps above:

### main.dart

```
import 'package:flutter/material.dart';
import 'package:hypersdkflutter/hypersdkflutter.dart';
import 'package:flutter/services.dart';
import './screens/home.dart';

void main() {
  final hyperSDK = HyperSDK();
  runApp(MyApp(hyperSDK: hyperSDK));
}

class MyApp extends StatelessWidget {
  // Create Juspay Object
  // // block:start:create-hyper-sdk-instance
  final HyperSDK hyperSDK;
  // // block:end:create-hyper-sdk-instance
  const MyApp({Key? key, required this.hyperSDK}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(
        hyperSDK: hyperSDK,
      ),
    );
  }
}

```

### home.dart

```
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:hypersdkflutter/hypersdkflutter.dart';
import 'package:uuid/uuid.dart';

import './checkout.dart';

import '../widgets/app_bar.dart';
import '../widgets/bottom_button.dart';

class HomeScreen extends StatefulWidget {
  final HyperSDK hyperSDK;

  const HomeScreen({Key? key, required this.hyperSDK}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  var countProductOne = 1;
  var countProductTwo = 0;

  @override
  Widget build(BuildContext context) {
    initiateHyperSDK();

    var screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: customAppBar(text: "Home Screen", context: context),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Container(
            color: const Color(0xFFF8F5F5),
            height: screenHeight / 12,
            child: Container(
                width: double.infinity,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 20),
                child: const Text(
                  "Juspay Payments SDK should be initiated on this screen",
                  style: TextStyle(
                    fontSize: 14,
                  ),
                )),
          ),
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(left: 20, top: 15),
            child: const Text(
              "Products",
              style: TextStyle(
                  fontSize: 18,
                  color: Color(0xFfFB8D33),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Container(
            height: screenHeight / 1.75,
            margin: const EdgeInsets.symmetric(vertical: 8),
            child: Column(
              children: [
                singleProduct(screenHeight / 1.75, "one", countProductOne),
                singleProduct(screenHeight / 1.75, "two", countProductTwo)
              ],
            ),
          ),
          BottomButton(
              height: screenHeight / 10,
              text: "Go to Cart",
              onpressed: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => CheckoutScreen(
                            productOneCount: countProductOne,
                            productTwoCount: countProductTwo,
                            hyperSDK: widget.hyperSDK,
                          ))))
        ],
      ),
    );
  }

  void initiateHyperSDK() async {
    // Check whether hyperSDK is already initialised
    if (!await widget.hyperSDK.isInitialised()) {
      // Getting initiate payload
      // block:start:get-initiate-payload
      var initiatePayload = {
        "requestId": const Uuid().v4(),
        "service": "in.juspay.hyperpay",
        "payload": {
          "action": "initiate",
          "merchantId": "<MERCHANT_ID>",
          "clientId": "<CLIENT_ID>",
          "xRoutingId": "<X_ROUTING_ID>",
          "environment": "production"
        }
      };
      // block:end:get-initiate-payload

      // Calling initiate on hyperSDK instance to boot up payment engine.
      // block:start:initiate-sdk
      await widget.hyperSDK.initiate(initiatePayload, initiateCallbackHandler);
      // block:end:initiate-sdk
    }
  }

  // Define handler for inititate callback
  // block:start:initiate-callback-handler
  void initiateCallbackHandler(MethodCall methodCall) {
    if (methodCall.method == "initiate_result") {
      // check initiate result
    }
  }
  // block:end:initiate-callback-handler

  Widget singleProduct(double height, String text, int itemCount) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 18),
      height: height / 2,
      child: Column(
        children: [
          Container(
            height: height / 4,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: Color.fromARGB(255, 121, 119, 119)),
            child: Image.asset(
              text == 'one'
                  ? 'assets/product1.png'
                  : 'assets/product2.png', // Replace with the path to your image
              fit: BoxFit.cover,
            ),
          ),
          Container(
            height: height / 4,
            color: const Color(0xFFFFFFFF),
            padding: const EdgeInsets.only(top: 10),
            child: Column(
              children: [
                Container(
                    alignment: Alignment.centerLeft,
                    margin: const EdgeInsets.only(bottom: 10),
                    child: Text(
                      "Product $text",
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    )),
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: RichText(
                          text: TextSpan(children: [
                        const TextSpan(
                            text: "Price: Rs. 1/item",
                            style:
                                TextStyle(fontSize: 12, color: Colors.black)),
                        const TextSpan(text: "\n"),
                        const TextSpan(
                            text: "Awesome product description for",
                            style:
                                TextStyle(fontSize: 12, color: Colors.black)),
                        TextSpan(
                            text: "\nproduct $text",
                            style: const TextStyle(
                                fontSize: 12, color: Colors.black)),
                      ])),
                    ),
                    Expanded(
                        flex: 2,
                        child: Center(
                          child: Container(
                            margin: const EdgeInsets.symmetric(horizontal: 20),
                            height: height / 12,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                border:
                                    Border.all(color: Colors.black, width: 2)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                GestureDetector(
                                  onTap: () => decreaseItemQuantity(text),
                                  child: const Icon(
                                    Icons.horizontal_rule_rounded,
                                    color: Color(0xFF115390),
                                  ),
                                ),
                                Text(
                                  itemCount.toString(),
                                  style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Color(0xFFFB8D33)),
                                ),
                                GestureDetector(
                                    onTap: () => increaseItemQuantity(text),
                                    child: const Icon(Icons.add,
                                        color: Color(0xFF115390)))
                              ],
                            ),
                          ),
                        )),
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void increaseItemQuantity(String text) {
    if (text == "one") {
      setState(() {
        countProductOne += 1;
      });
    } else {
      setState(() {
        countProductTwo += 1;
      });
    }
  }

  void decreaseItemQuantity(String text) {
    if (text == "one") {
      setState(() {
        if (countProductOne != 0) {
          countProductOne -= 1;
        }
      });
    } else {
      setState(() {
        if (countProductTwo != 0) {
          countProductTwo -= 1;
        }
      });
    }
  }
}

```


---

## See Also

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