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

# Custom Events

<Accordion title="Handle custom event from miniapp">
  The custom events system is a powerful feature that enables bidirectional data communication between a **miniapp** and the **host app**. The **miniapp** can send data that the **host app** can recognize. Additionally, certain operations can be implemented at the native app level for enhanced functionality.

  ### Examples

  Calling custom event from miniapp:

  ```js theme={"system"}
  appboxo.send('AppBoxoWebAppCustomEvent', {
    type: 'any_string_identifier',  // Any string identifier to be handled by host app
    payload: {                      // Any payload data to be send to host app
      // Your data
    }
  })
  ```

  Calling custom event from miniapp with promise:

  ```js theme={"system"}

  const dataDTO = {
    type: 'custom_event_type', // custom event type
    payload: {data: 'data'}, // your data
  }

  appboxo.sendPromise('AppBoxoWebAppCustomEvent', dataDTO)
    .then(() => console.log('success'))  // success callback
    .catch(() => console.log('rejected'))  // reject callback
  ```

  Receiving custom event sent from host app:

  ```js theme={"system"}
  appboxo.subscribe(event => {
    if (!event.detail) {
      return;
    }

    const { type, data } = event.detail;

    if (type === 'AppBoxoWebAppCustomEvent') {
      // Reading result of the Code Reader
      console.log(data.type);       // Custom event string identifier
      console.log(data.payload);    // Payload data
    }
  });
  ```

  <br />

  # Boxo Event Bridge

  ***
</Accordion>

# Boxo Event Bridge

***

<Accordion title="Introduction">
  Boxo Event Bridge is a bidirectional communication functionality that enables host apps and miniapps to exchange events and information seamlessly within the Boxo ecosystem.

  ### Event Bridge flow

  Here is a sequence flow for event communication process between a miniapp and a host app.

  <Steps>
    <Step title="Create event">
      An app (either hostapp or miniapp) creates an event with a specific event type and payload
    </Step>

    <Step title="Send to Boxo Platform">
      The app sends the event to the Boxo Platform via the Event Bridge API
    </Step>

    <Step title="Validate and authenticate">
      The Boxo Platform validates the event and authenticates the sender
    </Step>

    <Step title="Forward to recipient">
      The Boxo Platform forwards the event to the recipient's event receiver URL
    </Step>

    <Step title="Process event">
      The recipient processes the event and returns a response
    </Step>

    <Step title="Capture response">
      The Boxo Platform captures the response and forwards it to the original sender
    </Step>

    <Step title="Receive response">
      The original sender receives the response and can take appropriate actions
    </Step>
  </Steps>
</Accordion>

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

  **Data format**

  JSON is used for data exchange. Event payloads can contain any valid JSON structure that both the sender and receiver agree upon.

  <Accordion title="1. Event Receiver Endpoint">
    This endpoint allows your app to receive events from the Boxo Platform.

    **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/)

    **Headers:**

    | Key             | Value                                                             |
    | --------------- | ----------------------------------------------------------------- |
    | `Authorization` | `<prefix> <base64 encoded(hostapp_client_id:hostapp_secret_key)>` |
    | `Content-type`  | `application/json`                                                |

    * 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                                             |
    | ------------ | --------- | ------------------------------------------------------- |
    | `app_id`     | String    | Miniapp identifier                                      |
    | `client_id`  | String    | Hostapp identifier                                      |
    | `event_type` | String    | Event type identifying the purpose of the event         |
    | `payload`    | Object    | Event data containing information specific to the event |

    **Response:**

    * Response status must be `200` in all cases
    * Response body can contain any valid JSON that will be forwarded to the event sender

    **Request Example:**

    ```
    curl --location --request POST '[YOUR_SERVER_URL]/api/event-receiver/'\
    --header 'Content-Type: application/json' \
    --header 'Authorization: Basic {{BASE64_ENCODED_CLIENT_ID_AND_CLIENT_SECRET}}' \
    --data-raw '{
        "app_id": "{{MINIAPP_ID}}",
        "client_id": "{{CLIENT_ID}}",
        "event_type": "user_profile_updated",
        "payload": {
            "user_id": "user123",
            "name": "John Doe",
            "email": "john@example.com"
        }
    }'
    ```
  </Accordion>

  <Accordion title="2. Sending Events API">
    This endpoint allows your app to send events to miniapps through the Boxo Platform.

    **URL and METHOD**

    This is HTTPS POST `/api/v1/events/hostapp/` endpoint

    **Headers**

    | Key             | Value                                                             |
    | --------------- | ----------------------------------------------------------------- |
    | `Authorization` | `<prefix> <base64 encoded(hostapp_client_id:hostapp_secret_key)>` |
    | `Content-type`  | `application/json`                                                |

    * 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                                             |
    | ------------------- | ---------------- | ------------------------------------------------------- |
    | `app_id`            | String           | Miniapp identifier (recipient)                          |
    | `client_id`         | String           | Hostapp identifier (sender)                             |
    | `event_type`        | String           | Event type identifying the purpose of the event         |
    | `external_event_id` | String(Optional) | Event ID from Miniapp                                   |
    | `payload`           | Object           | Event data containing information specific to the event |

    **Response**

    * Response status will be `200` if the event was delivered successfully
    * Response body will contain the response from the miniapp's event receiver endpoint

    **Request Example**

    ```
    curl --location --request POST 'https://api.boxo.io/api/v1/events/hostapp/' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Basic {{BASE64_ENCODED_CLIENT_ID_AND_CLIENT_SECRET}}' \
    --data-raw '{
        "app_id": "{{MINIAPP_ID}}",
        "client_id": "{{CLIENT_ID}}",
        "event_type": "payment_completed",
        "payload": {
            "transaction_id": "tx_12345",
            "amount": 100.50,
            "currency": "USD",
            "status": "completed"
        }
    }'
    ```
  </Accordion>
</Accordion>

<Accordion title="Common Event Types">
  Here are some common event types that can be used for communication between host apps and miniapps:

  ### Host App to Miniapp Events

  | Event Type             | Description                               | Example Payload                                             |
  | ---------------------- | ----------------------------------------- | ----------------------------------------------------------- |
  | `user_profile_updated` | User profile information has been updated | `{"user_reference": "123", "email": "example@example.com"}` |

  ### Miniapp to Host App Events

  | Event Type            | Description                      | Example Payload                                                         |
  | --------------------- | -------------------------------- | ----------------------------------------------------------------------- |
  | `order_status_update` | Miniapp order fulfillment status | `{"order_payment_id": "order_123", "fulfillment_status": "delivering"}` |
</Accordion>

<Accordion title="Error Handling">
  If an error occurs during event processing, the Boxo Platform will return an appropriate error response:

  | Error Code                | Description                                     |
  | ------------------------- | ----------------------------------------------- |
  | `EVENT_RECEIVER_DISABLED` | Event receiver is not enabled for the recipient |
  | `INVALID_EVENT_DATA`      | The event data format is invalid                |
  | `EVENT_DELIVERY_FAILED`   | Failed to deliver the event to the recipient    |
  | `UNAUTHORIZED`            | Sender is not authorized to send events         |
</Accordion>

<Accordion title="Best Practices">
  1. **Event Types**: Use consistent event types that clearly indicate the purpose of the event
  2. **Minimal Payloads**: Keep event payloads as small as possible, including only necessary information
  3. **Error Handling**: Implement proper error handling for event processing failures
  4. **Idempotency**: Design event handlers to be idempotent to handle potential duplicate events
  5. **Timeouts**: Implement reasonable timeouts for event processing to avoid blocking operations

  By following these guidelines, you can create a robust event-driven communication system between your host app and miniapps using Boxo Event Bridge.
</Accordion>
