> ## Documentation Index
> Fetch the complete documentation index at: https://boxo.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Boxo Connect

## Introduction

Boxo Connect is a **Single Sign-On (SSO)** functionality that enables the host app to securely pass user profile information, allowing seamless authorization within the mini app. In essence, the Boxo Platform facilitates the transfer of user data from the host app backend to the mini app backend, ensuring smooth user authentication and returning a session token for continued access.

<Tabs>
  <Tab title="BoxoConnect OAuth">
    This is the traditional OAuth flow where the host app backend provides auth codes and access tokens to the Boxo Platform.

    <Accordion title="OAuth Flow Diagram">
      Here is diagram showcasing the hostapp user authorization inside miniapp

      <img src="https://mintcdn.com/boxo/Wh8QdEC9u1BJqwjc/images/boxo_connect.png?fit=max&auto=format&n=Wh8QdEC9u1BJqwjc&q=85&s=35be79078809c05575135c2e4833289f" alt="AuthDiagram" width="1880" height="2140" data-path="images/boxo_connect.png" />

      Authentication and User Authorization Flow

      <Steps>
        <Step title="User launches miniapp">
          The user opens the host app and launches the mini app.
        </Step>

        <Step title="User identification required">
          To proceed, the user must be identified (e.g., for product purchases or user registration).
        </Step>

        <Step title="Miniapp calls login">
          The mini app calls `Boxo.login()`.
        </Step>

        <Step title="User consent">
          The user is prompted to confirm access to their personal data required for authorization.
        </Step>

        <Step title="SDK retrieves auth code">
          The Boxo native SDK retrieves an authorization code from the host app and sends an HTTPS request to the Boxo platform.
        </Step>

        <Step title="Platform forwards auth code">
          The Boxo platform forwards the authorization code via an HTTPS request to the host app backend.
        </Step>

        <Step title="Backend validates and returns access token">
          The host app backend validates the authorization code and returns an access token.
        </Step>

        <Step title="Platform requests user data">
          The Boxo platform sends an HTTPS request with the access token to the host app backend to retrieve user data.
        </Step>

        <Step title="Backend returns user data">
          The host app backend validates the access token and returns user data.
        </Step>

        <Step title="Platform forwards user data to miniapp">
          The Boxo platform forwards the user data via an HTTPS request to the mini app backend.
        </Step>

        <Step title="Miniapp backend processes user">
          The mini app backend registers a new user or identifies an existing one, then issues an authorization token to the Boxo platform.
        </Step>

        <Step title="Authorization token returned to SDK">
          The Boxo platform returns the authorization token to the Boxo native SDK.
        </Step>

        <Step title="Token passed to miniapp">
          The authorization token is passed to the mini app.
        </Step>

        <Step title="Miniapp requests user data">
          The mini app sends a request with the authorization token to the mini app backend to retrieve user data.
        </Step>

        <Step title="Backend validates and returns data">
          The mini app backend validates the authorization token and returns the user data.
        </Step>

        <Step title="User successfully authorized">
          The user is successfully authorized and can proceed within the mini app.
        </Step>
      </Steps>
    </Accordion>

    <Accordion title="Setting up the backend">
      \*Note: Feature must be enabled in [Dashboard Partnership](https://dashboard.boxo.io/partnerships/)

      <img src="https://mintcdn.com/boxo/3dTfSQuOOiy3lc57/images/connect_integration.png?fit=max&auto=format&n=3dTfSQuOOiy3lc57&q=85&s=e866fcdb53c6a80e33ce04dec749e259" alt="AuthDiagram" width="1880" height="280" data-path="images/connect_integration.png" />

      **Data format**

      Currently, data exchange is conducted in JSON format. String size limits are defined within the respective data types.

      <Accordion title="Get access token">
        This endpoint allows the Boxo platform to obtain an access token in exchange for an authorization code.

        **URL and METHOD**

        This endpoint must handle a HTTPS POST request URL to endpoint must be provided in [Dashboard](https://dashboard.boxo.io/host-apps/)

        <img src="https://mintcdn.com/boxo/3dTfSQuOOiy3lc57/images/connect_hostapp.png?fit=max&auto=format&n=3dTfSQuOOiy3lc57&q=85&s=f65c57b2e3853e8665f682c5bddc931a" alt="AuthDiagram" width="1880" height="840" data-path="images/connect_hostapp.png" />

        **Headers**

        | Key                 | Value                                                             |
        | ------------------- | ----------------------------------------------------------------- |
        | Authorization       | `<prefix> <base64 encoded(hostapp_client_id:hostapp_secret_key)>` |
        | X-Miniapp-App-ID    | `<app_id - Miniapp identifier>`                                   |
        | X-Hostapp-Client-ID | `<client_id - Hostapp identifier>`                                |

        * Default `<prefix>`: Token. Access token prefix can be set in [Boxo Connect](https://dashboard.boxo.io/host-apps/).
        * `hostapp_client_id` and `hostapp_secret_key` must be provided in [Dashboard](https://dashboard.boxo.io/host-apps/)

        **Body**

        | Field      | Data type | Description                               |
        | ---------- | --------- | ----------------------------------------- |
        | auth\_code | String    | Auth code provided by hostapp to Boxo SDK |

        **Response**

        * Response status must be `200` in all cases
        * Response body:

        | Field           | Data type    | Optional                         | Description                                                                                                                                                       |
        | --------------- | ------------ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
        | `access_token`  | String(1000) | No, except `error_code` provided | Access token for get user data request. To use in payments requests enable `Use access token` in [Boxo Payments](https://dashboard.boxo.io/host-apps/).           |
        | `refresh_token` | String(1000) | Yes                              | Refresh token for get user data request. To use in payments requests enable `Use access token` in [Boxo Payments](https://dashboard.boxo.io/host-apps/).          |
        | `error_code`    | String       | Yes                              | If some error is occured error code should be provided. Example: `{"error_code": "INVALID_AUTH_CODE"}` All error codes can be found [here](/host-apps/ErrorCodes) |

        **Request Example:**

        ```text theme={"system"}
            curl --location --request POST '[YOUR_SERVER_URL]/api/get_access_token/' \
            --header 'Content-Type: application/json' \
            --header 'Authorization: Basic {{BASE64_ENCODED_CLIENT_ID_AND_CLIENT_SECRET}}' \
            --data-raw '{ "auth_code": "{{HOSTAPP_AUTH_CODE_THAT_COMES_FROM_SDK}}" }'
        ```
      </Accordion>

      <Accordion title="Get user data">
        This endpoint allows the Boxo platform to retrieve user data using an access token.

        **URL and METHOD**

        * This endpoint must handle a HTTPS GET request
        * URL to endpoint must be provided in [Dashboard](https://dashboard.boxo.io/host-apps/)

                  <img src="https://mintcdn.com/boxo/3dTfSQuOOiy3lc57/images/connect_hostapp.png?fit=max&auto=format&n=3dTfSQuOOiy3lc57&q=85&s=f65c57b2e3853e8665f682c5bddc931a" alt="AuthDiagram" width="1880" height="840" data-path="images/connect_hostapp.png" />

        **Headers**

        | Key                   | Value                              |
        | --------------------- | ---------------------------------- |
        | `Authorization`       | `Token <access_token>`             |
        | `X-Miniapp-App-ID`    | ` <app_id - Miniapp identifier>`   |
        | `X-Hostapp-Client-ID` | `<client_id - Hostapp identifier>` |

        **Response:**

        * Response status must be `200` in all cases
        * Response body:

        | Field        | Data type | Optional                         | Description                                                                                                                                                          |
        | ------------ | --------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
        | `user_data`  | UserData  | No, except `error_code` provided | Hostapp user data.                                                                                                                                                   |
        | `error_code` | String    | Yes                              | If some error is occured error code should be provided. Example: `{"error_code": "INVALID_ACCESS_TOKEN"}` All error codes can be found [here](/host-apps/ErrorCodes) |

        **UserData**

        | Field               | Data type   | Optional | Description                                |
        | ------------------- | ----------- | -------- | ------------------------------------------ |
        | `reference`         | String(100) |          | Reference to user in Hostapp Server        |
        | `email`             | String      | Yes      | Verified user email address                |
        | `phone`             | String      | Yes      | Verified user phone number in E.164 format |
        | `first_name`        | String      | Yes      | User's first name                          |
        | `last_name`         | String      | Yes      | User's last name                           |
        | `custom_attributes` | JSON        | Yes      | Custom attributes                          |

        <Warning>
          **WARNING** For Shopboxo miniapps either `email` or `phone` must be provided
        </Warning>

        **Request Example:**

        ```text theme={"system"}
            curl --location --request GET '[YOUR_SERVER_URL]/api/get_user_data/'\
            --header 'Content-Type: application/json' \
            --header 'Authorization: Token {{ACCESS_TOKEN}}'
        ```

        **Required fields**

        Each mini app requires a set of minimum fields to create a user within its system and generate a session for the newly created user. The specific required fields for each mini app can be found in its details on the Showroom page.

        Below is a list of all possible fields:

        * email
        * phone
        * first\_name
        * last\_name
      </Accordion>
    </Accordion>

    <Accordion title="Setting up the SDK">
      **Initialization**

      Parameter Descriptions:

      Within the SDK, there are specific parameters and methods that must be either provided or implemented to ensure proper functionality. `app_id` - Boxo miniapp app id

      To launch a specific mini app, you must first call the initialization method.

      <Tabs>
        <Tab title="iOS">
          ```swift theme={"system"}
          let miniapp = Boxo.shared.getMiniapp(appId: "app_id")
          miniapp.delegate = self
          miniapp.open(viewController: self)
          ...
          extension ViewController : MiniappDelegate {
              func onAuth(miniapp: Miniapp) {
                  //get AuthCode from hostapp backend and send it to miniapp
                  miniapp.setAuthCode(authCode: "auth_code")
              }
          }
          ```
        </Tab>

        <Tab title="Android">
          ```kotlin theme={"system"}
          val miniapp = Boxo.getMiniapp("app_id")
          miniapp.setAuthListener { _, miniapp ->
              //get AuthCode from hostapp backend and send it to miniapp
              miniapp.setAuthCode("auth_code")
          }
          miniapp.open()
          ```
        </Tab>

        <Tab title="Flutter">
          ```dart theme={"system"}
          Boxo.openMiniapp('app_id');
          Boxo.lifecycleHooksListener(
              onAuth: (appId) { // called when authorization flow starts
                  //get AuthCode from hostapp backend and send it to miniapp
                  Boxo.setAuthCode('app_id', 'auth_code');
              }
          );
          ```
        </Tab>

        <Tab title="ReactNative">
          ```js theme={"system"}
          Boxo.openMiniapp('app_id')
          Boxo.lifecycleHooksListener({
              onAuth: (appId: string) => {
                  //get AuthCode from hostapp backend and send it to miniapp
                  Boxo.setAuthCode('app_id', 'auth_code');
              },    
          });
          ```
        </Tab>

        <Tab title="Capacitor">
          ```js theme={"system"}
          Boxo.openMiniapp({ appId: 'app_id'});
          Boxo.addListener('miniapp_lifecycle', event => {
            if (event.lifecycle == 'onAuth') {
              //get AuthCode from hostapp backend and send it to miniapp
              Boxo.setAuthCode({ appId: 'app_id', 'auth_code'});
            }
          });
          ```
        </Tab>

        <Tab title="Expo">
          ```js theme={"system"}
          Boxo.openMiniapp({ appId: 'app_id' })
          Boxo.addAuthListener((authEvent) => {
              //get AuthCode from hostapp backend and send it to miniapp
              Boxo.setAuthCode('app_id', 'auth_code')
          });
          ```
        </Tab>
      </Tabs>

      <Warning>
        **WARNING** When a user logs out of the host app, ensure that the WebView cache is cleared using the following commands: `Boxo.logout()` for Android or `Boxo.shared.logout()` for iOS so that the miniapps' storage is also cleared to log out the miniapp users as well.
      </Warning>
    </Accordion>

    <Accordion title="Get user consent">
      This is Boxo endpoint to get status of user consent in Boxo Platform

      **URL and METHOD**

      * This is HTTPS GET `/api/v1/accounts/consent/get_consent/` endpoint

      ### Query Parameters:

      | Parameter        | Data type | Optional | Description                         |
      | ---------------- | --------- | -------- | ----------------------------------- |
      | `client_id`      | String    |          | Hostapp identifier                  |
      | `app_id`         | String    |          | Miniapp identifier                  |
      | `user_reference` | String    |          | Reference to user in Hostapp Server |

      **Response:**

      ```text theme={"system"}
      {
         "is_consented": <Bool>
      }
      ```
    </Accordion>
  </Tab>

  <Tab title="BoxoConnect Direct">
    This is the streamlined Direct flow where the host app backend directly sends user data to the Boxo Platform.

    <Accordion title="Direct Flow Diagram">
      Here is diagram showcasing the hostapp user authorization inside miniapp

      <img src="https://mintcdn.com/boxo/3dTfSQuOOiy3lc57/images/boxo_connect_v2.png?fit=max&auto=format&n=3dTfSQuOOiy3lc57&q=85&s=a774ba0190cd20655522a89edcb32631" alt="AuthDiagram" width="7016" height="6680" data-path="images/boxo_connect_v2.png" />

      Authentication and User Authorization Flow

      <Steps>
        <Step title="User launches miniapp">
          The user opens the host app and launches the miniapp.
        </Step>

        <Step title="Miniapp identifies user needs">
          The miniapp determines that user identification is needed to proceed.
        </Step>

        <Step title="JS SDK login call">
          The miniapp calls `appboxosdk.login` JS SDK event to request login action.
        </Step>

        <Step title="Consent screen displayed">
          The user sees a consent dialog asking to "Allow miniapp to access your account information" with an "Allow" button.
        </Step>

        <Step title="Auth Gateway request">
          After user consent, the system makes a request to the host app's authentication gateway.
        </Step>

        <Step title="Host app sends user data">
          The host app backend sends the user data to the Boxo Platform **connect/** endpoint.
        </Step>

        <Step title="Platform forwards to miniapp">
          The Boxo Platform forwards the user data to the miniapp backend.
        </Step>

        <Step title="Miniapp generates auth token">
          The miniapp backend processes the user data and generates an authorization token.
        </Step>

        <Step title="Token returned to host app">
          The token is also provided back to the host app.
        </Step>

        <Step title="Token sent to miniapp">
          The authorization token is sent back through the chain to the miniapp frontend.
        </Step>

        <Step title="User authorized">
          The miniapp server authorizes the user using the token.
        </Step>

        <Step title="Flow completed">
          The user is successfully authorized and can continue using the miniapp.
        </Step>
      </Steps>

      This process ensures a secure and seamless flow for user authorization between the host app, Boxo platform, and miniapp.
    </Accordion>

    <Accordion title="Setting up the backend for Direct">
      \*Note: Feature must be enabled in [Dashboard Partnership](https://dashboard.boxo.io/partnerships/)

      <img src="https://mintcdn.com/boxo/3dTfSQuOOiy3lc57/images/connect_integration.png?fit=max&auto=format&n=3dTfSQuOOiy3lc57&q=85&s=e866fcdb53c6a80e33ce04dec749e259" alt="AuthDiagram" width="1880" height="280" data-path="images/connect_integration.png" />

      **Data format**

      Currently, data exchange is conducted in JSON format. String size limits are defined within the respective data types.

      <Accordion title="Connect endpoint">
        This endpoint is called by the Super App (partner) server to connect a user to a miniapp on the Boxo Platform. On success, it returns an authorization token pair for the miniapp session.

        **URL and METHOD**

        * HTTPS POST `/api/v1/connect/` (Boxo Platform)

        **Headers**

        | Key          | Value              |
        | ------------ | ------------------ |
        | Content-type | `application/json` |

        > Authentication to this endpoint is managed via your partnership configuration in the Dashboard (e.g., IP whitelisting or [Request Signaturing](/host-apps/Signaturing)). Follow your integration setup.

        **Request Body**

        | Field       | Data type | Optional | Description             |
        | ----------- | --------- | -------- | ----------------------- |
        | `client_id` | String    | No       | Hostapp identifier      |
        | `app_id`    | String    | No       | Miniapp identifier      |
        | `user_data` | UserData  | No       | User information object |

        **UserData**

        | Field               | Data type | Optional | Description                                |
        | ------------------- | --------- | -------- | ------------------------------------------ |
        | `reference`         | String    | No       | Reference to user in Hostapp Server        |
        | `email`             | String    | Yes      | Verified user email address                |
        | `phone`             | String    | Yes      | Verified user phone number in E.164 format |
        | `first_name`        | String    | Yes      | User's first name                          |
        | `last_name`         | String    | Yes      | User's last name                           |
        | `custom_attributes` | JSON      | Yes      | Custom attributes                          |

        **Response**

        * Response status `200` for success, `400` for errors
        * Response body:

        **Success Response (200):**

        | Field           | Data type | Description   |
        | --------------- | --------- | ------------- |
        | `token`         | String    | Auth token    |
        | `refresh_token` | String    | Refresh token |

        **Error Response (400):**

        | Field               | Data type | Optional | Description                    |
        | ------------------- | --------- | -------- | ------------------------------ |
        | `error_code`        | String    | No       | Error code                     |
        | `error_message`     | String    | No       | Detailed error message         |
        | `exception`         | String    | Yes      | Exception details if available |
        | `custom_attributes` | Object    | Yes      | Additional error context       |

        **Request Example**

        ```text theme={"system"}
        curl --location --request POST '[BOXO_PLATFORM_SERVER_URL]/api/v1/connect/' \
          --header 'Content-Type: application/json' \
          --data-raw '{
            "client_id": "{{CLIENT_ID}}",
            "app_id": "{{MINIAPP_ID}}",
            "user": {
              "reference": "{{USER_REFERENCE}}",
              "email": "john@example.com",
              "phone": "+11234567890",
              "first_name": "John",
              "last_name": "Doe",
              "custom_attributes": {}
            }
          }'
        ```

        <Warning>
          **WARNING** For Shopboxo miniapps either `email` or `phone` must be provided
        </Warning>

        **Success Response (200)**

        ```text theme={"system"}
        {
          "token": "<AUTH_TOKEN>",
          "refresh_token": "<REFRESH_TOKEN>"
        }
        ```

        **Error Response (400)**

        ```text theme={"system"}
        {
          "error_code": "INVALID_INPUT",
          "error_message": "Missing required field: app_id",
          "exception": null,
          "custom_attributes": null
        }
        ```

        **Required fields**

        Each mini app requires a set of minimum fields to create a user within its system and generate a session for the newly created user. The specific required fields for each mini app can be found in its details on the Showroom page.

        Below is a list of all possible fields:

        * email
        * phone
        * first\_name
        * last\_name
        * custom\_attributes
      </Accordion>
    </Accordion>

    <Accordion title="Setting up the SDK for Direct">
      **Initialization**

      Parameter Descriptions:

      Within the SDK, there are specific parameters and methods that must be either provided or implemented to ensure proper functionality. `app_id` - Boxo miniapp app id

      To launch a specific mini app, you must first call the initialization method.

      <Tabs>
        <Tab title="iOS">
          ```swift theme={"system"}
          let miniapp = Boxo.shared.getMiniapp(appId: "app_id")
          miniapp.delegate = self
          miniapp.open(viewController: self)
          ...
          extension ViewController : MiniappDelegate {

              func onAuth(miniapp: Miniapp) {
                  //send a request to backend to fetch tokens
                  miniapp.setAuthTokens(["token" : "<token>", "refresh_token" : "<refresh_token>"])
              }
          }
          ```
        </Tab>

        <Tab title="Android">
          ```kotlin theme={"system"}
          val miniapp = Boxo.getMiniapp("app_id")
          miniapp.setAuthListener { _, miniapp ->
              //send a request to backend to fetch tokens
              miniapp.setAuthTokens(mapOf(
                  "token" to "<token>",
                  "refresh_token" to "<refresh_token>"
              ))
          }
          miniapp.open()
          ```
        </Tab>

        <Tab title="Flutter">
          ```dart theme={"system"}
          Boxo.openMiniapp('app_id');
          Boxo.lifecycleHooksListener(
              onAuth: (appId) { // called when authorization flow starts
                  //send a request to backend to fetch tokens
                  Boxo.setAuthTokens({
                      'token': '<token>',
                      'refresh_token': '<refresh_token>'
                  });
              }
          );
          ```
        </Tab>

        <Tab title="ReactNative">
          ```js theme={"system"}
          Boxo.openMiniapp('app_id')
          Boxo.lifecycleHooksListener({
              onAuth: (appId: string) => {
                  //send a request to backend to fetch tokens
                  Boxo.setAuthTokens({
                      'token': '<token>',
                      'refresh_token': '<refresh_token>'
                  });
              },    
          });
          ```
        </Tab>
      </Tabs>

      <Warning>
        **WARNING** When a user logs out of the host app, ensure that the WebView cache is cleared using the following commands: `Boxo.logout()` for Android or `Boxo.shared.logout()` for iOS so that the miniapps' storage is also cleared to log out the miniapp users as well.
      </Warning>
    </Accordion>

    <Accordion title="Get user consent for Direct">
      This is Boxo endpoint to get status of user consent in Boxo Platform

      **URL and METHOD**

      * This is HTTPS GET `/api/v1/accounts/consent/get_consent/` endpoint

      ### Query Parameters:

      | Parameter        | Data type | Optional | Description                         |
      | ---------------- | --------- | -------- | ----------------------------------- |
      | `client_id`      | String    |          | Hostapp identifier                  |
      | `app_id`         | String    |          | Miniapp identifier                  |
      | `user_reference` | String    |          | Reference to user in Hostapp Server |
      | **Response:**    |           |          |                                     |

      ```text theme={"system"}
      {
         "is_consented": <Bool>
      }
      ```
    </Accordion>
  </Tab>
</Tabs>
