- Updated: March 18, 2026
- 7 min read
Automating Multi‑Tenant Billing for OpenClaw with Stripe: A Step‑by‑Step Guide
Automating multi‑tenant billing for OpenClaw with Stripe means configuring Stripe products, building usage‑based webhook handlers, and wiring those handlers into OpenClaw’s rating API so that every tenant is billed accurately and automatically.
1. Introduction
In a SaaS environment, multi‑tenant billing is the backbone of predictable revenue. Without an automated system, you risk manual errors, delayed invoices, and a poor customer experience. OpenClaw—a powerful, open‑source rating and billing engine—already excels at rating usage, but it needs a payment processor to close the loop. Stripe (or any equivalent) provides a robust API for subscription management, usage‑based pricing, and automated invoicing.
This guide walks developers, DevOps engineers, and SaaS product managers through the end‑to‑end process of integrating Stripe with OpenClaw, from account creation to a fully automated billing flow.
2. Prerequisites
- An active OpenClaw instance hosted on UBOS.
- A Stripe account (or a compatible payment gateway that supports usage‑based billing).
- Node‑RED installed locally or on a server, or a comparable JavaScript runtime for webhook handling.
- Basic familiarity with REST APIs, JSON, and server‑side JavaScript.
3. Setting Up Stripe
3.1 Create a Stripe account and obtain API keys
Sign up at Stripe Docs. After verification, navigate to Developers → API keys and copy the Publishable key and Secret key. Store them securely (e.g., in a .env file).
3.2 Configure products, plans, and pricing tiers
In the Stripe Dashboard:
- Create a Product named “OpenClaw Usage”.
- Add a Price with Recurring billing set to
monthly(or your preferred interval). - Select Usage‑based as the pricing model and define the unit amount (e.g., $0.001 per API call).
3.3 Enable usage‑based pricing
When creating the price, choose “Metered usage”. Stripe will automatically generate usage_record objects that you can submit via the API. This is the key to aligning OpenClaw’s rating data with Stripe invoices.
4. Building Usage‑Based Webhook Handlers
4.1 Stripe webhook endpoint basics
Stripe sends events to a publicly reachable HTTPS endpoint. In Node‑RED, add an HTTP In node listening on /stripe/webhook. Connect it to a Function node that will verify the signature and route events.
4.2 Verifying signatures
Stripe signs each webhook with a secret. Store this secret in process.env.STRIPE_WEBHOOK_SECRET. Use the official Stripe library to verify:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
module.exports = async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.rawBody, sig, endpointSecret);
} catch (err) {
console.error('⚠️ Webhook signature verification failed.', err);
return res.sendStatus(400);
}
// Continue processing...
};
4.3 Handling key events
Focus on three events:
invoice.created– Triggered when Stripe prepares an invoice for a billing period.invoice.payment_succeeded– Confirms that payment was captured.usage_record.created– Confirms that a usage record was successfully attached to a subscription.
Below is a simplified Node‑RED Function node that routes these events:
switch (event.type) {
case 'invoice.created':
// Store invoice ID for later reconciliation
flow.set('currentInvoice', event.data.object.id);
break;
case 'invoice.payment_succeeded':
// Mark tenant as paid in OpenClaw
// (call OpenClaw rating API – see next section)
break;
case 'usage_record.created':
// Persist usage for audit
// (optional: write to DB)
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
return null;
4.4 Storing usage data for OpenClaw
When OpenClaw rates a call, push the usage metric to Stripe using the /v1/usage_records endpoint:
await stripe.subscriptionItems.createUsageRecord(
subscriptionItemId,
{
quantity: usageUnits,
timestamp: Math.floor(Date.now() / 1000),
action: 'increment',
}
);
Persist the subscriptionItemId per tenant in your database so the webhook can retrieve it later.
5. Integrating with OpenClaw’s Rating API
5.1 Overview of the rating API
OpenClaw exposes a REST endpoint /rating that accepts a JSON payload describing the tenant, the service, and the usage quantity. The API returns a rating result (cost, discounts, etc.).
5.2 Mapping usage records to rating calls
Each time a tenant makes a request, capture the raw usage (e.g., API calls, minutes, GB). Immediately after the request, invoke the rating API and forward the resulting cost to Stripe.
const axios = require('axios');
async function rateAndBill(tenantId, usageUnits) {
// 1️⃣ Call OpenClaw rating API
const ratingResponse = await axios.post(
`${process.env.OPENCLAW_URL}/rating`,
{
tenant_id: tenantId,
service: 'api',
quantity: usageUnits,
},
{ headers: { Authorization: `Bearer ${process.env.OPENCLAW_TOKEN}` } }
);
const costCents = ratingResponse.data.amount_cents;
// 2️⃣ Find Stripe subscription item for this tenant
const subItemId = await getStripeSubItemId(tenantId);
// 3️⃣ Report usage to Stripe
await stripe.subscriptionItems.createUsageRecord(
subItemId,
{
quantity: usageUnits,
timestamp: Math.floor(Date.now() / 1000),
action: 'increment',
}
);
return costCents;
}
5.3 Example Node‑RED flow
Below is a high‑level Node‑RED diagram (placeholder image) that demonstrates the flow:
Key nodes:
- HTTP In – Receives usage event from your SaaS front‑end.
- Function (Rate & Bill) – Executes the
rateAndBilllogic. - HTTP Response – Returns success/failure to the caller.
5.4 Error handling and retries
Network glitches or Stripe throttling can cause failures. Implement exponential back‑off and store failed usage records in a durable queue (e.g., Redis or a DB table). A separate “reconciliation worker” can poll the queue and retry until success.
6. End‑to‑End Billing Flow
6.1 From usage capture to invoice generation
- User triggers an API call → your service logs the event.
- Node‑RED function calls OpenClaw rating API → receives cost.
- Usage record is posted to Stripe via
subscriptionItems.createUsageRecord. - At the end of the billing period, Stripe automatically aggregates usage and creates an
invoice.createdevent. - Webhook handler receives
invoice.created, optionally adds a description, and waits forinvoice.payment_succeeded. - On payment success, the webhook updates OpenClaw’s tenant status (e.g., “paid”, “overdue”).
6.2 Automated reconciliation
Periodically run a script that compares OpenClaw’s internal usage logs with Stripe’s usage records. Any discrepancy triggers an alert (Slack, email) and a corrective job.
6.3 Customer portal considerations
Stripe provides a hosted Customer Portal. Embed the portal link in your UI so tenants can view invoices, update payment methods, or change plans without leaving your product.
7. Publishing the Article on ubos.tech
7.1 Formatting guidelines
UBOS expects clean HTML with Tailwind utility classes for styling. Use <h2>, <h3>, and <h4> for hierarchy, <ul>/<ol> for lists, and <pre> for code blocks. The prose class already provides readable typography.
7.2 Adding the internal link contextually
When you describe where to run OpenClaw, reference the hosting guide: host OpenClaw on UBOS. This single internal link satisfies SEO relevance and guides readers to the next step.
7.3 SEO best practices
- Primary keyword OpenClaw billing appears in the title, first paragraph, and H2.
- Secondary keywords (Stripe multi‑tenant, usage‑based billing, rating API integration) are naturally woven into subheadings and body copy.
- Internal links such as UBOS platform overview, UBOS pricing plans, and AI marketing agents distribute link equity across the site.
- External authoritative links (Stripe docs) use
rel="noopener"for security and SEO compliance. - Each section is self‑contained, making it easy for LLMs to quote or summarize.
8. Conclusion
By following this step‑by‑step guide, you have:
- Created a Stripe account with usage‑based pricing.
- Implemented secure webhook handlers for
invoice.created,invoice.payment_succeeded, andusage_record.created. - Connected OpenClaw’s rating API to Stripe, ensuring every tenant’s usage translates directly into a bill.
- Established an automated reconciliation loop and a customer‑friendly portal.
Next steps include exploring advanced features such as tiered discounts, proration handling, and integrating UBOS templates for quick start to accelerate future billing projects. For a deeper dive into OpenClaw’s capabilities, check out the Web app editor on UBOS and the Workflow automation studio.
Happy coding, and may your invoices always be on time! 🚀