UI SDK - Vanilla Javascript integration

SDK library integration

The Amberflo UI Kit SDK is a Vanilla Javascript development kit for our customers to be able to consume and make use of principal Amberflo views, for one of their customers, on their own site.

The SDK is a UI Kit wrapper, using the React UI Kit behind the scenes. This SDK will internally use React.JS, but does not require the customer to have a React project.

The SDK is responsible of making the API calls and rendering the components on a destination <div> on the final HTML code.

📘

Requisites

These are some of the languages where the SDK can be used: in React, Javascript, Angular, Vue.

Getting Started


  1. Include the script in the <head> of your site:
<script
  type="module"
  src="https://js.amberflo.io/index.1.0.30.js">
</script>

📘

Make sure to use to the latest available version in the script (e.g.: 1.0.30). You can check versions under Releases section.

  1. Retrieve your session token to access Amberflo API endpoints. With that session id, you will need to make a new instance of the AmberfloSDK included on the script above. To do that, you will have to add this code snippet under the first script tag you added:
<script>
  window.onload = () => {
    amberflo = new AmberfloSDK("{{YOUR_SESSION_TOKEN}}");
  };
</script>

📘

Replace {{YOUR_SESSION_TOKEN}} with the token you got. For example, if you received a session token that was 1234abcd, you would instantiate the Amberflo SDK like so: amberflo = new AmberfloSDK("1234abcd"). To know more about how to get your session token read Get Session Token section.

  1. Since sessions can expire, on your new instance of AmberfloSDK there is a method to set the new sessionId. You can call it anytime to amberflo.setSessionId("{{YOUR_NEW_SESSION_TOKEN}}");.
    The app will continue to work the same with the same ID.

  2. To add a new Amberflo view, you will need to place a <div> on your code, with the class amberflo and a data-amberflo-type attribute to setup the element. This data-amberflo-type attribute is responsible for rendering the different views that we support.

It's also possible to customize the components by adding a specific color, choose to show the widget container and its title, the font size, font family, and even a custom font. To do that, use the following attributes:

  • data-amberflo-colors
    Set a HEX code or string value of the primary color of your brand. We will automatically create a palette based
    on that color for all the components. By default it will use Amberflo colors.

  • data-amberflo-font-size
    Enter a number, this is the base font size, since not all part of this views has the same font size, all internal
    components will calculate percentage to show the desired font size for each internal view. Default value is 16,
    which is the default font size for all Amberflo components.

  • data-amberflo-font-family
    This is a comma separated name of fonts, it can be any font that is already supported and imported on your
    site. The browser will try to use the first font on that list, but if for some reason the font is not available, it will
    fallback to the right until a font is available. This is not common, bit could happen so we recommend to have
    more than a font in the list.

  • data-amberflo-font-custom
    If the font you are trying to use is not supported by the browser, nor one already added by you, you could use
    this prop to import a custom google font to your app. Besides importing the font, you need to specify the font
    name on the attributedata-amberflo-font-family.

  • data-amberflo-with-container
    It receives a string saying "true" or "false", if true, it will show the container around the widget, similar to the ones on our app

  • data-amberflo-with-title
    It receives a string saying "true" or "false", if true, it will show the title of the widget, it requires that the container is visible

  • data-amberflo-title
    It receives a string specifying a custom title for the widget, if not provided, will use the widget default title

All the styles attributes above are optional, if none is provided, it will use Amberflo design system.

<div
  class="amberflo"
  data-amberflo-type="usage-table"
  data-amberflo-colors="#1565c0"
  data-amberflo-font-size="16px"
  data-amberflo-font-family="Roboto, Helvetica, Arial, serif"
  data-amberflo-font-custom="https://fonts.googleapis.com/css2?family=DynaPuff:wght@400;500&family=Great+Vibes&family=Rubik&display=swap"
  data-amberflo-with-container="true"
  data-amberflo-with-title="true"
  data-amberflo-title="Custom Title"
></div>

Some views may require to use other attributes. Attributes can be updated programmatically at any time to render a different view or state. For example, you can render a Usage Table with a meter, and when you click a button, change that attribute to render the same view but with a different meter.

Get Session Token


You must create a session token to interact with Amberflo, either directly with the API or through the AmberfloSDK.

To do so, you can retrieve it from an endpoint on your server using the browser’s fetch function on the client side. This is generally the best approach when your client side is a single page application, especially if it’s built with a modern frontend framework such as React.

For more information check API Reference

This example shows how to create the server endpoint that serves the client secret:

const express = require('express');
const app = express();
const request = require('request');

app.get('/amberflo-session', async (req, res) => {
  request({
    method: 'POST',
    uri: 'http://app.amberflo.io/session',
    body: {
      "customerId": "{{DESIRED_CUSTOMER_ID}},
      "expirationEpochMilliSeconds": {{EXPIRATION_DATE_IN_MILLISECONDS}}
    },
    headers: {
      "X-API-KEY": "{{YOUR_API_KEY}}"
    }
  }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res.json({ sessionToken: response.sessionToken })
        }
    }
  );
})

📘

The above example is in Node.js.

You can get X-API-KEY from Amberflo site inside Settings -> Account -> API keys.

You can also get the customerId from Amberflo site inside Customers → Click on one customer → Copy Customer ID.

This example demonstrate how to fetch the session token with JavaScript in the client side:

const response = fetch('/amberflo-session').then(function(response) {
  return response.json();
}).then(function(responseJSON) {
  const sessionToken = responseJson.sessionToken
})

Using an Event

As you look through the Available Views, you will notice some views have available events (e.g. on the Usage Table view, there is a datechange event which will fire when you change the date in the date picker). This gives you the ability to do additional things after an event has fired within the view.

Here is an example of how to use an event using the datechange event with the Usage Table view:

<div
  id="usage-table"
  class="amberflo"
  data-amberflo-type="usage-table"
  data-amberflo-meters="SampleMeter"
></div>

<script>
  window.onload = () => {
    after setting up your session token...
    document
      .getElementById("usage-table")
      .addEventListener("datechange", (event) => {
        console.log(event.details);
        // { startDate: 1670112000000, endDate: 1672779539731 }
      });
  };
</script>

Invoice-related Options

There are a few Views that display invoice-related data (i.e. Invoices List and Invoice Details). There are invoice-related settings a user can update at Amberflo | Settings | Invoice which affect how invoices are displayed through in these views.

The current available option/settings are:

  • Displaying cached invoices

    • Invoice data displayed will either be cached data or real-time data.

    • Cached data is used to speed up how quickly invoice data can be retrieved.

  • Group product items on invoices

    • We list all product items and allow user to create categories to group on the invoices.

SDK Versions


📘

Releases

01/19/2024 - Version 1.0.30
01/16/2024 - Version 1.0.29
01/10/2024 - Version 1.0.28
08/04/2023 - Version 1.0.27
08/04/2023 - Version 1.0.26
07/12/2023 - Version 1.0.25
02/06/2023 - Version 1.0.24
01/09/2023 - Version 1.0.23
12/27/2022 - Version 1.0.22
12/20/2022 - Version 1.0.21
12/15/2022 - Version 1.0.20
12/08/2022 - Version 1.0.19
11/24/2022 - Version 1.0.18
10/20/2022 - Version 1.0.17
10/12/2022 - Version 1.0.16
10/04/2022 - Version 1.0.15
09/14/2022 - Version 1.0.14
09/12/2022 - Version 1.0.13
09/01/2022 - Version 1.0.12
08/29/2022 - Version 1.0.11
07/29/2022 - Version 1.0.10
07/12/2022 - Version 1.0.9
07/07/2022 - Version 1.0.8
07/06/2022 - Version 1.0.7
06/07/2022 - Version 1.0.6
05/09/2022 - Version 1.0.5
05/07/2022 - Version 1.0.4
04/26/2022 - Version 1.0.3
04/21/2022 - Version 1.0.2
04/20/2022 - Version 1.0.1
04/13/2022 - Version 1.0.0

Available Views


Usage Table

AttributeValue
data-amberflo-typeusage-table
data-amberflo-metersComma separated meters apiNames you want to see on the table.

e.g.:
ApiCalls,cluster_count,cluster_instance_hours,cluster_partitions,cluster_reads,cluster_storage,cluster_writes,CpuHours,DataVolumeGb,number_of_runs
EventValue
datechangeTriggered when a date picker on top changes
periodchangeTriggered when period selector on top changes

Example:

<div
  class="amberflo"
  data-amberflo-type="usage-table"
  data-amberflo-meters="ApiCalls,cluster_count,cluster_instance_hours,cluster_partitions,cluster_reads,cluster_storage,cluster_writes,CpuHours,DataVolumeGb,number_of_runs"
></div>

Usage Graph

AttributeValue
data-amberflo-typeusage-graph
data-amberflo-meterA single meter apiName you want to see on the graph.

e.g.:

"ApiCalls"

If not provided, a meter selector will show on top of the graph
data-amberflo-dimensions-mapA list of dimensions values and it's transformed value. For example, if you have a dimension called dim1 but you actually want to see in the graph as Dimension 1, you can pass this attribute:

data-amberflo-dimensions-map="dim1:Dimension 1"

You can add more than one, separating them by commas:

data-amberflo-dimensions-map="dim1:Dimension 1,dim2:Dimension 2"
data-amberflo-group-byA string representing the dimension to group the graph by
data-amberflo-dimensions-selectorA boolean value used to show/hide the dimensions selector that allows a user select a dimension to group usage data by.
EventValue
datechangeTriggered when a date picker on top changes
periodchangeTriggered when period selector on top changes
meterchangeTriggered when meter selector changes
dimensionchangeTriggered when dimension selector changes

Example

<div
  class="amberflo"
  data-amberflo-type="usage-graph"
  data-amberflo-meter="ApiCalls"
></div>

Cost Table

AttributeValue
data-amberflo-typecost-table
EventValue
datechangeTriggered when a date picker on top changes
periodchangeTriggered when period selector on top changes

Example

<div
  class="amberflo"
  data-amberflo-type="cost-table"
></div>

Invoice Details

AttributeValue
data-amberflo-typeinvoice-details
data-amberflo-invoice-date="1/30/2022"The date of the invoice in format l - M/D/YYYY - 1/9/2022

If not provided, it will use the last invoice for the customer.
data-amberflo-prepaid-idA string value of the ID of a prepaid transaction that you want to view details on. A data-amberflo-invoice-date value is required when passing a data-amberflo-prepaid-id. This value is not required when you are not specifically viewing a prepaid transaction.
data-amberflo-dimensions-mapHere you can send the dimension name between pipes (eg. |availability_zone|), followed by a list of value and remap value separated by commas.

So if you have a dimension called availability_zone, and it's value is zone1, and you want to change it to My Custom Zone 1, you can pass something like:

data-amberflo-dimensions-map="|availability_zone|zone1:My Custom Zone 1"

You can add more items, separating by commas

For instance:

data-amberflo-dimensions-map="|availability_zone|zone1:My Custom Zone 1,zone2:My Custom Zone 2|cloud_provider|aws:AWS"
data-amberflo-hide-breakdownString containing "true" or "false", if true, invoice breakdown will be hidden, and only titles will show the totals per product item

Example

<div
  class="amberflo"
  data-amberflo-type="invoice-details"
  data-amberflo-invoice-date="1/9/2022"
></div>

Invoices List

AttributeValue
data-amberflo-typeinvoice-list
data-amberflo-export-actionBoolean (as string) value used to determine if the "Export As" column is displayed which gives you the ability to export invoices to PDF.
data-amberflo-show-prepaid-invoicesA boolean (as string) value that when set true, prepaid transactions will be included in your invoices list. If a value is not passed, the invoice list will default to showing prepaid transactions.
data-amberflo-payment-status-block-listA comma-separated string of payment statuses of invoices that you want to block from showing in your invoices list (e.g. "not_needed,failed")
EventValue
rowclickTriggered when a invoice is clicked

Example

<div
  class="amberflo"
  data-amberflo-type="invoices-list"
></div>

Orders Usage Graph and Table

AttributeValue
data-amberflo-typeorder-usage-graph-table

Example

<div
  class="amberflo"
  data-amberflo-type="order-usage-graph-table"
></div>

Prepaid Summary

AttributeValue
data-amberflo-typeprepaid-summary

Example

<div
  class="amberflo"
  data-amberflo-type="prepaid-summary"
></div>

Prepaid Wallet

AttributeValue
data-amberflo-typeprepaid-table

Example

<div
  class="amberflo"
  data-amberflo-type="prepaid-table"
></div>

Stripe Payment Method

AttributeValue
data-amberflo-typestripe-payment-method
data-amberflo-publishable-keyPublishable key from stripe. You can get it by following the steps detailed below.
data-amberflo-button-textThis is the button text, where your customer will have to click to submit their credit card.
data-amberflo-return-urlThis is the URL where user will be taken after filling the credit card value, and everything worked.
data-amberflo-show-editThis is a string containing "true" or "false". If true, the component will display the stripe payment form, which allows a user to enter their payment info. If false, the component will display the payment details. This prop is helpful if you want to manually control the views and not use the “Edit” button to view the payment form.
<div
  class="amberflo"
  data-amberflo-type="stripe-payment-method"
  data-amberflo-publishable-key="pk_test_62MIq3eFMMJsb2ZF6ivl10ycy6kVNhPau9QnrwJE649HGEEz3vZNDo5XA5I6ZdHRosbjGq8eAGPBrE0wrl7Q0Fxn1i00CaNu0Ar"
  data-amberflo-button-text="Submit"
  data-amberflo-return-url="https://mysite.com/stripe"
  data-amberflo-colors="#1565c0"
></div>

Notes

Make sure that the data-amberflo-return-url page, includes the Amberflo script, and also is instantiated, the as you did for the page where this component is hosted.

Add the script:

<script
  type="module"
  src="https://js.amberflo.io/index.1.0.24.js"
></script>

And make sure you instantiate it:

<script>
  window.onload = () => {
    amberflo = new AmberfloSDK("{{YOUR_SESSION_TOKEN}}");
  };
</script>

Pricing Plan

AttributeValue
data-amberflo-typepricing-plan
data-amberflo-pricing-planPricing Plan ID
data-amberflo-titlePricing Plan title. It could be the same as the pricing plan itself, or some other text
data-amberflo-product-item-linesComma separated strings for each line row
data-amberflo-fixed-priceBoolean defining if the plan has or not a fixed price
data-amberflo-priceString saying the fixed price of the plan. Only mandatory if fixed price is true.
EventValue
planselectTriggered when the select plan button is clicked
<div
  class="amberflo"
  data-amberflo-type="pricing-plan"
  data-amberflo-pricing-plan="65ad692f-b7ae-4886-ab8a-3d0146d0817d"
  data-amberflo-title="Plan Name"
  data-amberflo-product-item-lines="30$ / GB,Custom  Text"
  data-amberflo-fixed-price="true"
  data-amberflo-price="$40 Fixed Price"
  data-amberflo-colors="#0078D4"
></div>

Included Units

AttributeValue
data-amberflo-typeincluded-units
data-amberflo-product-itemProduct item ID to show on the widget. It needs to be part of the plan assigned to the customer
data-amberflo-titleOptional field to show a title of the product item. if not passed, only the numbers will be displayed

Order List

AttributeValue
data-amberflo-typeorder-list
EventValue
addorderTriggered when + Order is pressed. ProductItemId is passed as details
rowclickTriggered when a row is clicked. Order is passed as details.

Example:

<div
  id="orderList"
  class="amberflo"
  data-amberflo-type="order-list"
></div>

<script>
  document.getElementById("orderList").addEventListener("addorder", (event => {
    // Do something when add order button is pressed. For instance:
    window.location.href = `/add-order/${event.detail}`
  });
                                                        
  document.getElementById("orderList").addEventListener("rowclick", (event => {
    // Do something when an order row is clicked. For instance:
    window.location.href = `/order-details/${event.detail.id}`
  });
</script>

Order Details

AttributeValue
data-amberflo-typeorder-details
data-amberflo-order-idID of the order to show details
EventValue
backTriggered when the back button is pressed
<div
  id="orderDetails"
  class="amberflo"
  data-amberflo-type="order-details"
  data-amberflo-order-id="65ad692f-b7ae-4886-ab8a-3d0146d0817d"
></div>

<script>
  document.getElementById("orderDetails").addEventListener("back", (event => {
    // Do something when back button is pressed. For instance:
    window.location.href = "/order-list"
  });
</script>

Order Create

AttributeValue
data-amberflo-typeorder-create
data-amberflo-product-item-idID of the product item where to create the order.
EventValue
backTriggered when the back button is pressed
cancelTriggered when the cancel button is pressed
<div
  id="orderCreate"
  class="amberflo"
  data-amberflo-type="order-create"
  data-amberflo-product-item-id="65ad692f-b7ae-4886-ab8a-3d0146d0817d"
></div>

<script>
  document.getElementById("orderCreate").addEventListener("back", (event => {
    // Do something when back button is pressed. For instance:
    window.location.href = "/order-list"
  });
                                                          
   document.getElementById("orderCreate").addEventListener("cancel", (event => {
    // Do something when cancel button is pressed. For instance:
    window.location.href = "/order-list"
  });
</script>

Order Usage Graph and Table

AttributeValue
data-amberflo-typeorder-usage-graph-table
EventValue
backTriggered when the back button is pressed
cancelTriggered when the cancel button is pressed
<div
  class="amberflo"
  data-amberflo-type="order-usage-graph-table"
></div>

How to get the Stripe publishable key


  • Go to stripe.com and login with your username and password
  • Once inside Stripe, go to Dashboard
  • Inside the dashboard copy the publishable key. Check the image below for reference:


Appendix 1: Full Code Example

<html>
    <head>
        <script id="amberflo-script" type="module" src="https://js.amberflo.io/index.1.0.24.js"></script>
        <script>
            window.onload = () => {
                // YOU SHOULD NOT RETRIEVE A SESSION TOKEN LIKE THIS IN YOUR CLIENT-SIDE CODE.
                // THIS IS ONLY FOR DEMONSTRATION PURPOSES TO TRY OUT A QUICK WORKING EXAMPLE.
                // Please see this section (https://docs.amberflo.io/docs/uikit-sdk#get-session-token)
                // for more information on how to provide a session token to your client.
                fetch("https://app.amberflo.io/session", {
                    method: "POST",
                    body: JSON.stringify({
                        // replace customer123 with an actual customer id
                        customerId: "customer123",
                    }),
                    headers: {
                        // YOU SHOULD NOT HAVE YOUR API KEY IN YOUR CLIENT SIDE CODE.
                        // THIS IS ONLY FOR DEMONSTRATION PURPOSES TO TRY OUT A QUICK WORKING EXAMPLE.
                        // replace your_api_key with your account's API key.
                        // Please see this section for more info.
                        // (https://docs.amberflo.io/docs/uikit-sdk#get-session-token)
                        "x-api-key": "your_api_key"
                    },
                })
                .then((response) => response.json())
                .then((responseJson) => {
                    amberflo = new AmberfloSDK(responseJson.sessionToken);

                    // This is an example of using an event.
                    // This will log the date info when changing the date on the usage graph using the date picker.
                    document
                    .getElementById("usage-graph")
                    .addEventListener("datechange", (event) => {
                        console.log(event.detail);
                        // { startDate: 1674000000000, endDate: 1676603751569 }
                    });
                });
            };
        </script>
    </head>

    <body>
        <!-- replace meter-api-name with actual meter API Name -->
        <div
            id="usage-graph"
            class="amberflo meter"
            data-amberflo-type="usage-graph"
            data-amberflo-meter="meter-api-name"
        ></div>
        <div
            id="usage-table"
            class="amberflo"
            data-amberflo-type="usage-table"
            data-amberflo-with-container="true"
            data-amberflo-with-title="true"
            data-amberflo-title="Usage Table"
        ></div>
    </body>
</html>