Quickstart
Connect a Node.js app to Bunny end to end: create a subscription at signup, keep the tenant in sync from the provisioning webhook, report usage and open the customer portal.
This guide connects a Node.js app to Bunny at the four integration points: it creates a subscription when a customer signs up, keeps the customer’s tenant in sync from Bunny’s webhook, reports usage, and opens the customer portal. It uses the Superdesk sample company, and Express for the web server.
The same calls are available in the Ruby SDK and as raw GraphQL.
Before you startLink to Before you start section
In Bunny, set up these four things. Everything else happens in code.
| What | Where in Bunny | You need |
|---|---|---|
| A price list to sell | Product catalog: a product, plan and price list. To start trials, the price list must allow them. | The price list’s code, such as business_monthly |
| A usage-based charge, for step 4 | A charge on that price list that uses a feature with Is Unit on | The feature’s code, such as api_calls |
| An API client | Settings > Developers > API clients | The Client ID and Client Secret, with the scopes standard:read standard:write billing:write portal:write |
| Provisioning on the product’s platform | Settings > Developers > Platforms: on the platform your product belongs to, turn on Provisioning enabled, set the Webhook URL to your endpoint from step 3, and set a Webhook signing key | The signing key |
Your Bunny address is https://<subdomain>.bunny.com, the address you use to sign in to Bunny.
1. Install and configure the SDKLink to 1. Install and configure the SDK section
npm install @bunnyapp/api-client express
Create the client once, on your server. With a client ID and secret, the SDK gets access tokens itself and gets a new one when a token expires.
// bunny.js
const Bunny = require("@bunnyapp/api-client");
const bunny = new Bunny({
baseUrl: "https://<subdomain>.bunny.com",
clientId: process.env.BUNNY_CLIENT_ID,
clientSecret: process.env.BUNNY_CLIENT_SECRET,
scope: "standard:read standard:write billing:write portal:write",
webhookSigningToken: process.env.BUNNY_WEBHOOK_SIGNING_KEY,
});
module.exports = bunny;
Keep the client secret and access tokens on your server. Never send them to the browser. Authentication explains which token goes where.
2. Create a subscription at signupLink to 2. Create a subscription at signup section
When a customer signs up, create their tenant in your app first, then create the subscription in Bunny with the tenant’s code. Here the code is superdesk-123456, your own ID for the tenant.
const bunny = require("./bunny");
async function onSignup(tenant, user) {
const subscription = await bunny.subscriptionCreate("business_monthly", {
trial: true,
accountName: "Superdesk",
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
tenantCode: tenant.id, // "superdesk-123456"
tenantName: "Superdesk",
});
// Keep the subscription ID: usage records in step 4 need it.
await saveBunnySubscriptionId(tenant.id, subscription.id);
}
This creates the account, its billing contact, the tenant and a trial subscription. Leave out trial to start a paid subscription instead.
The SDK throws an Error with Bunny’s message if the subscription can’t be created. For example, Price list not found means the price list code doesn’t exist, and Tenant provisioning is not enabled means Provisioning enabled is off on the platform of the price list’s product. A tenant code only works with provisioning on.
Reference: subscriptionCreate. More options: Create a subscription.
3. Keep the tenant in syncLink to 3. Keep the tenant in sync section
Bunny sends the TenantProvisioningChange webhook to your platform’s Webhook URL whenever something changes what a tenant gets: the trial converts, the customer upgrades, a quote is applied, or the subscription is canceled. The payload lists the tenant’s current features and quantities. Set them on the tenant in your app.
const express = require("express");
const bunny = require("./bunny");
const app = express();
// Verify the signature against the raw body, exactly as received.
app.post("/webhooks/bunny", express.raw({ type: "application/json" }), async (req, res) => {
const signature = req.headers["x-bunny-signature"];
if (!signature || !bunny.webhooks.validate(signature, req.body)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body);
if (event.type === "TenantProvisioningChange") {
const tenantCode = event.payload.tenant.code; // "superdesk-123456"
const features = event.payload.change.features; // [{ code: "users", quantity: 10, ... }]
await updateTenantEntitlements(tenantCode, features);
}
res.sendStatus(200);
});
Respond with a 2xx status within 5 seconds. If your update takes longer, queue it and respond first. Bunny tries a failed request once more, and you can resend a webhook from Settings > Developers > Webhook logs. To send the current state for a tenant on demand, for example while testing, call tenantProvisioningSend.
Full payload and every trigger: Tenant provisioning change. Signature details: Webhook security.
4. Report usageLink to 4. Report usage section
If the price list has a usage-based charge, report usage as it happens, with the feature code, the quantity and the subscription ID you saved in step 2.
await bunny.featureUsageCreate("api_calls", 250, subscriptionId);
The usage is recorded at the current time. Pass an ISO 8601 date and time as a fourth argument to record it at another time. At the end of each billing period, Bunny combines the records using the charge’s usage calculation (Sum, Max, Last or Average) and bills the result.
Reference: featureUsageCreate. Usage calculations: Track usage for billing.
5. Open the customer portalLink to 5. Open the customer portal section
To let a customer update their card, pay invoices or change their plan, create a portal session for their tenant on your server and send them to the portal with the token.
app.get("/billing", async (req, res) => {
const tenantCode = req.user.tenantId; // "superdesk-123456"
const token = await bunny.portalSessionCreate(tenantCode, "https://app.example.com/settings");
res.redirect(`https://<subdomain>.bunny.com/portal/subscriptions?token=${token}`);
});
The token gives access to this one account and expires after 24 hours. Replace subscriptions in the URL with transactions or payment-method to open another page of the portal. The second argument is where the portal links back to, and where customers go when their session has expired.
To keep customers inside your app instead, use the same token with the popup customer portal or Bunny Components. Reference: portalSessionCreate.
Next stepsLink to Next steps section
- See all four steps working together in the sample SaaS app.
- Report logins and engagement with tenant metrics.
- Using an AI coding tool? Build with AI connects it to these docs.