The Optimizer GraphQL API allows you to fetch data managed from https://app.getoptimizer.com/ ready to be used in your application.
This document contains instructions to use the Optimizer API and SDKs along with guides and examples.
An API Key should be sent as part of every request to the Optimizer API, in the form of a Publishable-Key
request header.
You can manage API Keys from Settings > Api Keys
.
An API Key tells our API server that the request it received came from you. Everything that you have access to in Optimizer is accessible with an API Key generated for you.
For ease of use, you only need to configure the Optimizer SDK one time for all requests.
Call the configure
function once to set your api key for all subsequent requests.
import {configure} from "@haiku/optimizer-sdk";
configure({apiKey: "pub_production_xyz"});
Api keys are sent via a Publishable-Key
request header.
curl -X POST 'https://api.getoptimizer.com/v0/graphql' \
-H 'Publishable-Key: pub_production_xyz'
--data-raw '{"query": "..."}'
If a request fails for any reason such as invalid parameters, authentication errors, and network unavailability our client libraries will provide you with a path to handle the error gracefully.
We recommend writing code that checks and handles all possible API exceptions.
If you are making a request directly to the API, you can expect an standard GraphQL error response, this is a 200
status code, but an array of error messages in the errors
key of the JSON response.
All API calls in the JavaScript SDK accept a classic Node.js-style callback that provides an error variable as the first parameter.
import {getPlansByProduct} from "@haiku/optimizer-sdk";
getPlansByProduct('product_id', (error, plans) => {
if (error) {
// Handle error
}
});
An error response from the API contains an array of errors in the errors
key of the response.
{"data":null,"errors":["EOF"]}
The recommended way to fetch data from the Optimizer API is via our SDK libraries.
SDKs not only hide some complexities from you but also enhance the responses with methods and utilities to make your life easier when dealing with currencies, amounts, etc.
At the time being, the only SDK available is the JavaScript SDK which can be used in Node.js and the browser, but we plan on including more languages in the near term.
You can install the JavaScript SDK via npm/yarn
npm install --save @haiku/optimizer-sdk
Or you can use the SDK directly from our CDN
<script src="https://static.getoptimizer.com/sdk/latest/optimizer.min.js">
If you don't want to deal with setting up the SDK yourself, you can find an embed script that does the setup for you in Settings > Developers
.
Just copy and paste the code in your HTML and you're good to go.
Attribute | Type | Description |
---|---|---|
name | string | The name of the plan |
amount | number | Amount in cents, you will probably want to use the SDK convenience methods to deal with plan amounts. Tiered plans always have this value set to zero. |
currency | string | Three-letter ISO currency code, in lowercase. |
interval | string | The frequency at which a subscription is billed. One of day , week , month or year . |
intervalCount | number | The number of intervals between subscription billings. For example, interval=month and intervalCount=3 bills every 3 months. |
tiersMode | string | Defines if the tiering price should be graduated or volume based. |
tiers | Tier[] | Each element represents a pricing [Tier]. |
active | boolean | Whether the plan can be used for new purchases. |
trialPeriodDays | number | Default number of trial days when subscribing a customer to this plan |
recurring | boolean | Whether the plan is recurring or not. |
stripePlanID | string | The plan ID used in Stripe |
You can get a list of Plan
s for a given product with the JavaScript SDK's getPlansByProduct
method, the response contains an array of Plan
objects enhanced with convenience methods
to display amounts.
getTotalAmount
and getTotalAmountFormatted
are able to calculate and format amounts based on the plan tiersMode
, the number of Tiers
, and optional extra parameters that you can provide.
import {getPlansByProduct} from '@haiku/optimizer-sdk';
getPlansByProduct('optimizer_product_id', (error, plans) => {
if (error) {
// Handle gracefully
}
plans[0].amount // 400 (the amount in cents)
plans[0].getTotalAmount(); // 4 (the total amount)
plans[0].getTotalAmountFormatted(); // $4 (the total amount formatted)
});
Attribute | Type | Description |
---|---|---|
flatAmount | number | Price for the entire tier. |
unitAmount | number | Per unit price for units relevant to the tier. |
upTo | number | Up to and including to this quantity will be contained in the tier. |
upToInf | boolean | Indicates wether this is the last Tier in the series. |
The Optimizer API allows you to show localized prices to your users without having to deal with the geo-localization of the users and the management of different plans in different currencies.
To fetch data using the SDK, you can either use the embed code or install the SDK from npm. We generally recommend to install the SDK from npm to take adventage of niceties like TypeScript definitions and tree-shaking on your bundle.
If you'd rather use the embed, you can skip the first step in this guide.
To install the SDK, run:
npm install --save @haiku/optimizer-sdk
Once installed, you need to configure the SDK with your Public Key.
First, grab your Public Key from Settings > Developers
and then, use the configure
function:
import {configure} from "@haiku/optimizer-sdk";
configure({apiKey: "your-api-key"});
Now you're ready to fetch data from Optimizer. The SDK tries to be as unobtrusive as possible: the goal is to only change the way in which you fetch plans so you have to change as little as possible of the way in which you are displaying your plans.
To fetch plans, grab the Stripe product ID of the product that contains your plans from the Optimizer dashboard (Settings > Developers
) and use the getPlansByProduct
method:
import {configure, getPlansByProduct} from "@haiku/optimizer-sdk";
configure({apiKey: "your-api-key"});
getPlansByProduct("stripe_product_id", (error, plans) => {
// Display your plans
});
getPlanByProducts
returns an array of localized Plans based on the geographic location of the user that visits your page.
We recommend to always handle errors and whenever possible do this gracefully to avoid disrupting the user experience as much as possible. The first parameter to the callback function of getPlansByProduct
. If an error ocurred it will be returned by this argument, if no error ocurred, error
will be set to null
.
import {configure, getPlansByProduct} from "@haiku/optimizer-sdk";
configure({apiKey: "your-api-key"});
getPlansByProduct("stripe_product_id", (error, plans) => {
if (error) {
// Handle error.
}
// Display your plans
});
If you already have fallback code in place for possible exceptions when fetching plans then you can use it here. If you don't have a fallback system in place we recommend storing the default prices in a data structure in your code, this way you will not be able to display localized prices but at least the user will be presented with the available plans.
Since fetching the plans from Stripe is handled by Optimizer, your back-end doesn't need to do any kind of fetching or validation with Stripe anymore, it can simply be a passtrough to Stripe to make the purchase.