The custom events system is a powerful feature that enables two sided data communication between a miniapp and a host app. The miniapp can send any data that can be recognised by the host app. Further, certain operations can be implemented on the native app level.

One possible scenario is when the user pays for the miniapp product on the level of the host app by using a host app’s payment system. The possible flow would be:

Here’s a revised version of the flow for clarity:

  1. User opens host app and launches miniapp: The user initiates the miniapp from within the host app.
  2. User proceeds with miniapp flow: The user navigates through the miniapp as intended.
  3. User selects products and clicks on BUY: The user chooses items and confirms their purchase.
  4. Miniapp sends custom event with product details, order, and amount: The miniapp sends the order details, including the products and total amount, through a custom event.
  5. Host app receives custom event and shows a confirmation screen for purchase: The host app processes the custom event and displays a purchase confirmation screen on top of the active miniapp.
  6. Host app performs purchasing operation and sends back a custom event to the miniapp: The host app completes the purchase and sends a custom event back to the miniapp, containing either transaction details and a success message or a failure message.
  7. Miniapp receives the custom event and shows confirmation/failure screen: The miniapp processes the response and displays either a success or failure screen based on the transaction outcome.
  8. If the transaction is successful, the miniapp saves the transaction details: For future reference and monthly reconciliation, the miniapp saves the successful transaction details.

This flow ensures that the interaction between the miniapp and host app is smooth and that purchase transactions are accurately tracked.

Examples

Calling custom event from miniapp:

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:


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:

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
  }
});

Boxo Event Bridge


Introduction

Boxo Event Bridge is a bidirectional communication functionality that enables miniapps to exchange events and information with host apps seamlessly through the Boxo platform. This feature allows miniapps to send notifications, request data, or respond to events initiated by the host app, creating a more integrated and interactive user experience.

Event Bridge flow

Here is a diagram illustrating the event communication process between a miniapp and a host app.

Here is the streamlined process for event communication in the Boxo ecosystem:

  1. The Miniapp creates an event with a specific event type and payload.

  2. The Miniapp server sends the event to the Boxo Platform through the Event Bridge API.

  3. The Boxo Platform validates the event and forwards it to the Host app server.

  4. The Host app server processes the event and returns a response to the Boxo Platform.

  5. The Boxo Platform forwards the response back to the Miniapp server.

  6. The Miniapp server processes the response and takes appropriate actions.

Alternatively, the process can start with the host app creating an event:

  1. The Host app creates an event for a specific miniapp.

  2. The Host app server sends the event to the Boxo Platform.

  3. The Boxo Platform forwards the event to the Miniapp server.

  4. The Miniapp server processes the event and returns a response.

  5. The Boxo Platform forwards the response back to the Host app server.

Setting up the backend

Note: Feature must be enabled in Dashboard Partnership

Data format The Boxo platform uses JSON format for data exchange. Event payloads can contain any valid JSON structure that follows the agreed-upon schema between the miniapp and host app.

1. “Send Event” Request

This endpoint is on the Boxo platform. Send a request to deliver an event to a host app.

URL and METHOD:

This is HTTPS POST /api/v1/event-bridge/miniapp/ endpoint IP address of requesting services must be provided in Dashboard for whitelisting or Request Signaturing must be enabled

Headers

KeyValue
Content-typeapplication/json

Body:

FieldData typeOptionalDescription
app_idStringNoMiniapp identifier
client_idStringNoHostapp identifier
event_typeStringNoType of event (e.g., “order_created”)
payloadObjectNoEvent data in JSON format

Response:

  • Response status will be 400 in case there is error_code

  • Response body: The response body will contain the host app’s response to the event, or an error message if delivery failed.

FieldData typeOptionalDescription
error_codeStringYesError code if event delivery failed
error_messageStringYesDetailed error message
Additional fields from host app response

Request Example:

curl --location --request POST '[BOXO_PLATFORM_SERVER_URL]/api/v1/event-bridge/miniapp/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "app_id": "{{MINIAPP_ID}}",
    "client_id": "{{CLIENT_ID}}",
    "event_type": "order_created",
    "payload": {
        "order_id": "ord_12345",
        "amount": 100.50,
        "currency": "USD",
        "items": [
            {
                "product_id": "prod_123",
                "quantity": 2,
                "price": 50.25
            }
        ]
    }
}'

Response Example:

Success response (containing host app’s response):

{
    "status": "received",
    "message": "Event processed successfully",
    "reference_id": "evt_987654"
}

Error response:

{
    "error_code": "EVENT_RECEIVER_DISABLED",
    "error_message": "Event receiver is not enabled for the specified host app"
}

2. “Event Receiver” Endpoint

Set up this endpoint to receive events from host apps through the Boxo platform.

URL and METHOD: This endpoint must handle a HTTPS POST request URL to endpoint must be provided in Dashboard

  • We suggest whitelisting Boxo platform IP addresses for this endpoint.

Headers:

KeyValue
AuthorizationBasic <base64 encoded(app_id:secret_key)>
Content-typeapplication/json

app_id and secret_key will be provided in Dashboard

Body:

FieldData typeDescription
app_idStringMiniapp identifier
client_idStringHostapp identifier
event_typeStringType of event (e.g., “user_updated”)
payloadObjectEvent data in JSON format

Response:

  • Response status must be 200 in all cases

  • Response body can contain any valid JSON that will be forwarded to the host app

Request Example:

curl --location --request POST '[YOUR_SERVER_URL]/api/event-receiver/' \
--header 'Authorization: Basic {{BASE64_ENCODED_APP_ID_AND_SECRET_KEY}}' \
--header 'Content-Type: application/json' \
--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"
    }
}'

Response Example:

{
    "status": "processed",
    "message": "User profile update acknowledged"
}

Common Event Types

Here are some common event types that can be used for communication between miniapps and host apps:

Miniapp to Host App Events

Event TypeDescriptionExample Payload
order_createdA new order has been created in the miniapp{"order_id": "ord_123", "amount": 50.25}
product_viewedUser has viewed a product in the miniapp{"product_id": "prod_123", "category": "shoes"}
cart_updatedUser’s shopping cart has been updated{"cart_id": "cart_123", "item_count": 3}
content_sharedUser has shared content from the miniapp{"content_id": "cont_123", "content_type": "image"}
checkout_startedUser has initiated the checkout process{"cart_id": "cart_123", "amount": 75.00}

Host App to Miniapp Events

Event TypeDescriptionExample Payload
user_profile_updatedUser profile information has been updated{"user_id": "123", "updated_fields": ["email"]}
location_updatedUser’s location has been updated{"latitude": 37.7749, "longitude": -122.4194}
app_state_changeThe state of the host app has changed{"new_state": "background", "timestamp": 123456}
language_changedUser has changed their language preference{"language_code": "es", "locale": "es_MX"}
theme_changedUser has changed their theme preference{"theme": "dark", "color_scheme": "blue"}

Error Handling

If an error occurs during event processing, the Boxo Platform will return an appropriate error response:

Error CodeDescription
EVENT_RECEIVER_DISABLEDEvent receiver is not enabled for the host app
INVALID_EVENT_DATAThe event data format is invalid
EVENT_DELIVERY_FAILEDFailed to deliver the event to the host app
UNAUTHORIZEDMiniapp is not authorized to send events
INTEGRATION_DISABLEDEvent bridge is not enabled for this integration

Best Practices

  1. Event Types: Use descriptive event types that clearly communicate the purpose of the event
  2. Efficient Payloads: Keep event payloads as small as possible while including all necessary information
  3. Error Handling: Implement proper error handling for event failures and retry mechanisms where appropriate
  4. Idempotency: Design event handlers to be idempotent to handle potential duplicate events
  5. Event Documentation: Document all event types and their expected payloads for better integration with host apps
  6. Response Times: Process events quickly and respond within reasonable timeframes to avoid timeouts
  7. Validation: Validate incoming events before processing to ensure data integrity

SDK Integration

For client-side event handling in your miniapp, you can use the Boxo JS SDK:

// Listen for events from the host app
appboxoSdk.on('hostAppEvent', (eventData) => {
  const { eventType, payload } = eventData;
  
  // Handle different event types
  switch (eventType) {
    case 'user_profile_updated':
      updateUserProfile(payload);
      break;
    case 'location_updated':
      updateUserLocation(payload);
      break;
    // Handle other event types
    default:
      console.log('Received unknown event:', eventType);
  }
});

// Send events to the host app
appboxoSdk.sendEvent({
  eventType: 'order_created',
  payload: {
    orderId: 'ord_12345',
    amount: 100.50,
    currency: 'USD'
  }
}).then((response) => {
  console.log('Event sent successfully:', response);
}).catch((error) => {
  console.error('Failed to send event:', error);
});

By utilizing the Boxo Event Bridge, your miniapp can create seamless integrations with host apps, improving user experience and enabling more advanced functionality through real-time communication.

The custom events system is a powerful feature that enables two sided data communication between a miniapp and a host app. The miniapp can send any data that can be recognised by the host app. Further, certain operations can be implemented on the native app level.

One possible scenario is when the user pays for the miniapp product on the level of the host app by using a host app’s payment system. The possible flow would be:

Here’s a revised version of the flow for clarity:

  1. User opens host app and launches miniapp: The user initiates the miniapp from within the host app.
  2. User proceeds with miniapp flow: The user navigates through the miniapp as intended.
  3. User selects products and clicks on BUY: The user chooses items and confirms their purchase.
  4. Miniapp sends custom event with product details, order, and amount: The miniapp sends the order details, including the products and total amount, through a custom event.
  5. Host app receives custom event and shows a confirmation screen for purchase: The host app processes the custom event and displays a purchase confirmation screen on top of the active miniapp.
  6. Host app performs purchasing operation and sends back a custom event to the miniapp: The host app completes the purchase and sends a custom event back to the miniapp, containing either transaction details and a success message or a failure message.
  7. Miniapp receives the custom event and shows confirmation/failure screen: The miniapp processes the response and displays either a success or failure screen based on the transaction outcome.
  8. If the transaction is successful, the miniapp saves the transaction details: For future reference and monthly reconciliation, the miniapp saves the successful transaction details.

This flow ensures that the interaction between the miniapp and host app is smooth and that purchase transactions are accurately tracked.

Examples

Calling custom event from miniapp:

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:


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:

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
  }
});

Boxo Event Bridge


Introduction

Boxo Event Bridge is a bidirectional communication functionality that enables miniapps to exchange events and information with host apps seamlessly through the Boxo platform. This feature allows miniapps to send notifications, request data, or respond to events initiated by the host app, creating a more integrated and interactive user experience.

Event Bridge flow

Here is a diagram illustrating the event communication process between a miniapp and a host app.

Here is the streamlined process for event communication in the Boxo ecosystem:

  1. The Miniapp creates an event with a specific event type and payload.

  2. The Miniapp server sends the event to the Boxo Platform through the Event Bridge API.

  3. The Boxo Platform validates the event and forwards it to the Host app server.

  4. The Host app server processes the event and returns a response to the Boxo Platform.

  5. The Boxo Platform forwards the response back to the Miniapp server.

  6. The Miniapp server processes the response and takes appropriate actions.

Alternatively, the process can start with the host app creating an event:

  1. The Host app creates an event for a specific miniapp.

  2. The Host app server sends the event to the Boxo Platform.

  3. The Boxo Platform forwards the event to the Miniapp server.

  4. The Miniapp server processes the event and returns a response.

  5. The Boxo Platform forwards the response back to the Host app server.

Setting up the backend

Note: Feature must be enabled in Dashboard Partnership

Data format The Boxo platform uses JSON format for data exchange. Event payloads can contain any valid JSON structure that follows the agreed-upon schema between the miniapp and host app.

1. “Send Event” Request

This endpoint is on the Boxo platform. Send a request to deliver an event to a host app.

URL and METHOD:

This is HTTPS POST /api/v1/event-bridge/miniapp/ endpoint IP address of requesting services must be provided in Dashboard for whitelisting or Request Signaturing must be enabled

Headers

KeyValue
Content-typeapplication/json

Body:

FieldData typeOptionalDescription
app_idStringNoMiniapp identifier
client_idStringNoHostapp identifier
event_typeStringNoType of event (e.g., “order_created”)
payloadObjectNoEvent data in JSON format

Response:

  • Response status will be 400 in case there is error_code

  • Response body: The response body will contain the host app’s response to the event, or an error message if delivery failed.

FieldData typeOptionalDescription
error_codeStringYesError code if event delivery failed
error_messageStringYesDetailed error message
Additional fields from host app response

Request Example:

curl --location --request POST '[BOXO_PLATFORM_SERVER_URL]/api/v1/event-bridge/miniapp/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "app_id": "{{MINIAPP_ID}}",
    "client_id": "{{CLIENT_ID}}",
    "event_type": "order_created",
    "payload": {
        "order_id": "ord_12345",
        "amount": 100.50,
        "currency": "USD",
        "items": [
            {
                "product_id": "prod_123",
                "quantity": 2,
                "price": 50.25
            }
        ]
    }
}'

Response Example:

Success response (containing host app’s response):

{
    "status": "received",
    "message": "Event processed successfully",
    "reference_id": "evt_987654"
}

Error response:

{
    "error_code": "EVENT_RECEIVER_DISABLED",
    "error_message": "Event receiver is not enabled for the specified host app"
}

2. “Event Receiver” Endpoint

Set up this endpoint to receive events from host apps through the Boxo platform.

URL and METHOD: This endpoint must handle a HTTPS POST request URL to endpoint must be provided in Dashboard

  • We suggest whitelisting Boxo platform IP addresses for this endpoint.

Headers:

KeyValue
AuthorizationBasic <base64 encoded(app_id:secret_key)>
Content-typeapplication/json

app_id and secret_key will be provided in Dashboard

Body:

FieldData typeDescription
app_idStringMiniapp identifier
client_idStringHostapp identifier
event_typeStringType of event (e.g., “user_updated”)
payloadObjectEvent data in JSON format

Response:

  • Response status must be 200 in all cases

  • Response body can contain any valid JSON that will be forwarded to the host app

Request Example:

curl --location --request POST '[YOUR_SERVER_URL]/api/event-receiver/' \
--header 'Authorization: Basic {{BASE64_ENCODED_APP_ID_AND_SECRET_KEY}}' \
--header 'Content-Type: application/json' \
--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"
    }
}'

Response Example:

{
    "status": "processed",
    "message": "User profile update acknowledged"
}

Common Event Types

Here are some common event types that can be used for communication between miniapps and host apps:

Miniapp to Host App Events

Event TypeDescriptionExample Payload
order_createdA new order has been created in the miniapp{"order_id": "ord_123", "amount": 50.25}
product_viewedUser has viewed a product in the miniapp{"product_id": "prod_123", "category": "shoes"}
cart_updatedUser’s shopping cart has been updated{"cart_id": "cart_123", "item_count": 3}
content_sharedUser has shared content from the miniapp{"content_id": "cont_123", "content_type": "image"}
checkout_startedUser has initiated the checkout process{"cart_id": "cart_123", "amount": 75.00}

Host App to Miniapp Events

Event TypeDescriptionExample Payload
user_profile_updatedUser profile information has been updated{"user_id": "123", "updated_fields": ["email"]}
location_updatedUser’s location has been updated{"latitude": 37.7749, "longitude": -122.4194}
app_state_changeThe state of the host app has changed{"new_state": "background", "timestamp": 123456}
language_changedUser has changed their language preference{"language_code": "es", "locale": "es_MX"}
theme_changedUser has changed their theme preference{"theme": "dark", "color_scheme": "blue"}

Error Handling

If an error occurs during event processing, the Boxo Platform will return an appropriate error response:

Error CodeDescription
EVENT_RECEIVER_DISABLEDEvent receiver is not enabled for the host app
INVALID_EVENT_DATAThe event data format is invalid
EVENT_DELIVERY_FAILEDFailed to deliver the event to the host app
UNAUTHORIZEDMiniapp is not authorized to send events
INTEGRATION_DISABLEDEvent bridge is not enabled for this integration

Best Practices

  1. Event Types: Use descriptive event types that clearly communicate the purpose of the event
  2. Efficient Payloads: Keep event payloads as small as possible while including all necessary information
  3. Error Handling: Implement proper error handling for event failures and retry mechanisms where appropriate
  4. Idempotency: Design event handlers to be idempotent to handle potential duplicate events
  5. Event Documentation: Document all event types and their expected payloads for better integration with host apps
  6. Response Times: Process events quickly and respond within reasonable timeframes to avoid timeouts
  7. Validation: Validate incoming events before processing to ensure data integrity

SDK Integration

For client-side event handling in your miniapp, you can use the Boxo JS SDK:

// Listen for events from the host app
appboxoSdk.on('hostAppEvent', (eventData) => {
  const { eventType, payload } = eventData;
  
  // Handle different event types
  switch (eventType) {
    case 'user_profile_updated':
      updateUserProfile(payload);
      break;
    case 'location_updated':
      updateUserLocation(payload);
      break;
    // Handle other event types
    default:
      console.log('Received unknown event:', eventType);
  }
});

// Send events to the host app
appboxoSdk.sendEvent({
  eventType: 'order_created',
  payload: {
    orderId: 'ord_12345',
    amount: 100.50,
    currency: 'USD'
  }
}).then((response) => {
  console.log('Event sent successfully:', response);
}).catch((error) => {
  console.error('Failed to send event:', error);
});

By utilizing the Boxo Event Bridge, your miniapp can create seamless integrations with host apps, improving user experience and enabling more advanced functionality through real-time communication.