Message Builder Web Component

TL;DR

  • The Hero Health Message Builder SDK enables partners to integrate messaging functionality into their applications via a Web Component called hh-message-builder .
  • Partners need to securely store user credentials and establish a server-side endpoint to fetch Access Tokens from the Hero Health Public API, utilizing the " Create Access Token " operation.
  • Upon acquisition, partners can showcase the Web Component, transmitting the Access Token via the jwt-token prop.
  • For server-side rendered implementations, partners can retrieve Access Tokens during rendering, ensuring that calls to the Hero Health Public API are not made from the frontend.

What is a Web Component?

A Web Component is a reusable, encapsulated piece of code that provides specific functionality or UI elements for a web page. It allows developers to create custom HTML elements with their own behaviour, styles, and functionality, which can be easily reused across different web applications.

Check this document for more information.

Prerequisites

Before proceeding with the integration, make sure you have the following:

  • Valid API Key and Practice Group ID provided by Hero Health;
  • Endpoint on your server to securely store and manage the credentials or a server-side rendering approach on your application

Authentication

The Message Builder SDK authentication relies on Access Tokens, which are short-lived tokens that must be obtained immediately before loading the Message Builder Web Component.

To generate an Access Token, you can utilize the Hero Health Public API. To do so, it's necessary to create an endpoint on your server that securely interacts with the Hero Health Public API for Access Token generation. This endpoint should enforce robust authentication measures and restrict access solely to authenticated users within your system.

SDK Auth Scheme

Note that if your application uses a server-side rendered approach, you can call the Hero Health Public API to generate an Access Token directly, as long as it does not come from the frontend.

Example of an endpoint

Here is an example of an endpoint to retrieve the Access Token from Hero Health Public API.

Copy
Copied
const express = require("express");
const fetch = require("node-fetch");

const app = express();
const PORT = process.env.PORT || 3000;

// Define your Hero Health API credentials
const API_KEY = "YOUR_API_KEY";
const PRACTICE_GROUP_ID = "YOUR_PRACTICE_GROUP_ID";

// Define the endpoint to retrieve the Access Token
app.get("/get-access-token", async (req, res) => {
  // Make sure only authenticated users can access the endpoint
  if (!req.user) {
    res.status(401);
  }
  try {
    // Make a request to Hero Health Public API to generate the Access Token
    const response = await fetch("https://api.herohealth.net/v1/access_token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY,
        "x-practice-group-id": PRACTICE_GROUP_ID,
      },
    });

    if (!response.ok) {
      throw new Error("Failed to generate Access Token");
    }

    const data = await response.json();
    const accessToken = data.access_token;

    // Return the Access Token as a response
    res.json({ access_token: accessToken });
  } catch (error) {
    console.error("Error retrieving Access Token:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Check the documentation for the “Create Access Token” operation on Hero Health Public API.

Using the Message Builder SDK

1. Include the script tag

Copy
Copied
<script src="https://scripts.htech.app/message-builder/web-component/latest.js"></script>

2. Render the Web Component

You'll need to write a script to render the Web Component when you receive the Access Token from the server. This can be accomplished in various ways, but you can refer to the example below:

Copy
Copied
<div id="message-builder-container"></div>

<script>
  // Function to retrieve the Access Token from the server
  function getAccessToken() {
    // Make an AJAX request to your server endpoint to retrieve the Access Token
    // Replace 'YOUR_SERVER_ENDPOINT' with your actual endpoint URL
    fetch("YOUR_SERVER_ENDPOINT")
      .then((response) => response.json())
      .then((data) => {
        const accessToken = data.access_token;
        // Display the Web Component after retrieving the Access Token
        displayMessageBuilder(accessToken);
      })
      .catch((error) => {
        console.error("Error fetching Access Token:", error);
      });
  }

  // Function to display the Hero Health Message Builder Web Component
  function displayMessageBuilder(accessToken) {
    // Create a new instance of the Web Component
    const messageBuilderComponent =
      document.createElement("hh-message-builder");
    // Set the 'jwt-token' prop with the retrieved Access Token
    messageBuilderComponent.setAttribute("jwt-token", accessToken);
    // Append the Web Component to the container element
    document
      .getElementById("message-builder-container")
      .appendChild(messageBuilderComponent);
  }

  // Call the function to retrieve the Access Token when the page loads
  window.onload = function () {
    getAccessToken();
  };
</script>

Server-side rendered pages

Suppose you are using a server-side rendering approach in your application. In that case, you can retrieve the access token on render time and inject it directly into the Message Builder component.

Be aware that the Access Token expires in 30 minutes, so caching strategies can lead to authentication errors.

Example:

Copy
Copied
const express = require("express");
const fetch = require("node-fetch");

const app = express();
const PORT = process.env.PORT || 3000;

// Define your Hero Health API credentials
const API_KEY = "YOUR_API_KEY";
const PRACTICE_GROUP_ID = "YOUR_PRACTICE_GROUP_ID";

// Define a function to fetch the Access Token from the Hero Health Public API
async function getAccessToken() {
  try {
    // Make a request to Hero Health Public API to generate the Access Token
    const response = await fetch("https://api.herohealth.net/v1/access_token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": API_KEY,
        "x-practice-group-id": PRACTICE_GROUP_ID,
      },
    });

    if (!response.ok) {
      throw new Error("Failed to generate Access Token");
    }

    const data = await response.json();
    const accessToken = data.access_token;

    return accessToken;
  } catch (error) {
    console.error("Error retrieving Access Token:", error);
    throw error;
  }
}

// Define a route to render the web component after getting the Access Token
app.get("/render-component", async (req, res) => {
  try {
    // Retrieve the Access Token
    const accessToken = await getAccessToken();

    // Render the web component with the Access Token
    const html = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Rendered Component</title>
                <script src="https://scripts.htech.app/message-builder/web-component/latest.js"></script>
            </head>
            <body>
                <hh-message-builder jwt-token="${accessToken}"></hh-message-builder>
            </body>
            </html>
        `;

    res.send(html);
  } catch (error) {
    res.status(500).send("Internal Server Error");
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Attributes

The Message Builder Web Component exposes the following attributes:

  • jwt-token : the access token generated using Hero Health Public API.
  • patient-id : opens the Message Builder for the loaded patient (if provided). Optional .
  • env : define the environment, allowed values are production and staging. Default to staging.
  • theme : an object containing the theme variables like colours and spacing. Optional . See the Theming section below.