✨ From vibe coding to vibe deployment. UBOS MCP turns ideas into infra with one message.

Learn more
Carlos
  • Updated: March 20, 2026
  • 6 min read

End‑to‑End Stripe Integration for Per‑Tenant Billing with OpenClaw Rating API Edge

To implement end‑to‑end per‑tenant billing, you connect Stripe to OpenClaw’s Rating API Edge, configure webhooks, map Stripe events to each tenant, and verify payments programmatically.

1. Introduction

SaaS platforms that charge each customer (or tenant) separately need a reliable, real‑time billing pipeline. Stripe provides a robust payment processor, while OpenClaw’s Rating API Edge offers a flexible rating engine that can be called from any backend. This guide walks software developers through a complete Stripe‑OpenClaw integration, from account creation to payment verification, using clean, MECE‑structured steps that can be copied into production code.

By the end of this article you will be able to:

  • Set up a Stripe account and obtain API keys.
  • Create and secure Stripe webhooks.
  • Map incoming Stripe events to the correct OpenClaw tenant.
  • Call the OpenClaw Rating API Edge to verify and record payments.

The workflow is illustrated in the diagram below (conceptual only):

Client → Stripe Checkout → Stripe Webhook → Your Service → OpenClaw Rating API Edge → Billing Ledger
      

For a quick start, you can host OpenClaw on UBOS using the dedicated OpenClaw hosting page.

2. Setting up a Stripe account

If you don’t already have a Stripe account, sign up at Stripe Dashboard. After verification, navigate to Developers → API keys and copy the Publishable key and Secret key. Store the secret key in a secure environment variable, e.g. STRIPE_SECRET_KEY.

# .env
STRIPE_SECRET_KEY=sk_test_XXXXXXXXXXXXXXXXXXXXXXXX
STRIPE_WEBHOOK_SECRET=whsec_XXXXXXXXXXXXXXXXXXXXXXXX
      

Tip: Use Stripe’s test mode for development. The test cards listed in the Stripe testing docs let you simulate successful, declined, and disputed payments.

3. Creating Stripe webhooks

Webhooks are the bridge that notifies your backend when a payment event occurs. Follow these steps:

  1. In the Stripe Dashboard, go to Developers → Webhooks → Add endpoint.
  2. Enter your public endpoint URL, e.g. https://yourdomain.com/api/stripe/webhook.
  3. Select the events you need. For per‑tenant billing, the most common are:
    • checkout.session.completed
    • invoice.payment_succeeded
    • invoice.payment_failed
  4. Save the endpoint. Stripe will generate a Webhook Signing Secret. Store it as STRIPE_WEBHOOK_SECRET (see .env example above).

Below is a minimal Express.js webhook handler that validates the signature and parses the event:

const express = require('express');
const bodyParser = require('body-parser');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();

// Raw body needed for signature verification
app.post('/api/stripe/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET);
  } catch (err) {
    console.error('⚠️ Webhook signature verification failed.', err.message);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Forward the verified event to the tenant mapper
  handleStripeEvent(event);
  res.json({received: true});
});
      

The handleStripeEvent function (implemented in the next section) will map the event to the appropriate OpenClaw tenant.

4. Mapping Stripe events to OpenClaw tenants

OpenClaw identifies each customer with a unique tenant_id. To associate a Stripe payment with a tenant, embed the tenant_id in the Stripe Checkout metadata field when you create the session.

const session = await stripe.checkout.sessions.create({
  payment_method_types: ['card'],
  line_items: [{price: 'price_12345', quantity: 1}],
  mode: 'subscription',
  success_url: 'https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
  cancel_url: 'https://yourdomain.com/cancel',
  metadata: {
    tenant_id: 'tenant_abc123'   // <-- critical link to OpenClaw
  }
});
      

When the webhook fires, you can retrieve the tenant_id from event.data.object.metadata.tenant_id. The mapping logic is straightforward:

async function handleStripeEvent(event) {
  const obj = event.data.object;

  // Only process successful payments
  if (event.type === 'checkout.session.completed' || event.type === 'invoice.payment_succeeded') {
    const tenantId = obj.metadata?.tenant_id;
    if (!tenantId) {
      console.warn('⚠️ No tenant_id found in metadata.');
      return;
    }

    // Call OpenClaw Rating API Edge to record the payment
    await verifyAndRecordPayment(tenantId, obj.id, obj.amount_total);
  }
}
      

This approach guarantees a one‑to‑one relationship between a Stripe transaction and an OpenClaw tenant, satisfying the per‑tenant billing requirement without additional lookup tables.

5. Verifying payments with OpenClaw Rating API Edge

OpenClaw’s Rating API Edge is a lightweight HTTP endpoint that accepts a JSON payload and returns a rating record. To verify a Stripe payment, you send the tenant_id, Stripe payment_intent_id, and the amount. OpenClaw will:

  • Confirm the payment exists in Stripe (optional double‑check).
  • Apply any custom rating rules (e.g., discounts, usage caps).
  • Persist the rating to the tenant’s billing ledger.

Below is a Node.js helper that calls the Rating API Edge. Replace RATING_API_URL with the URL you receive after deploying OpenClaw.

const axios = require('axios');

async function verifyAndRecordPayment(tenantId, stripePaymentId, amountCents) {
  const payload = {
    tenant_id: tenantId,
    external_payment_id: stripePaymentId,
    amount: amountCents / 100, // convert to dollars
    currency: 'USD'
  };

  try {
    const response = await axios.post(process.env.RATING_API_URL + '/rate', payload, {
      headers: { 'Content-Type': 'application/json' }
    });

    if (response.data.success) {
      console.log(`✅ Payment recorded for tenant ${tenantId}`);
    } else {
      console.error('❌ Rating API rejected the payment:', response.data);
    }
  } catch (err) {
    console.error('❌ Error calling Rating API Edge:', err.message);
  }
}
      

Why use the Rating API Edge? It isolates billing logic from your core application, enabling:

  • Scalable, stateless verification.
  • Centralized rule management (taxes, discounts, usage tiers).
  • Auditable transaction logs per tenant.

For production, secure the endpoint with an API key or mutual TLS, and enable idempotency by passing the Stripe idempotency_key in the request header.

6. Conclusion

Integrating Stripe with OpenClaw’s Rating API Edge gives SaaS developers a clean, end‑to‑end billing pipeline that:

  • Collects payments securely via Stripe.
  • Maps each transaction to the correct tenant using metadata.
  • Verifies and records payments through a dedicated rating service.
  • Supports per‑tenant billing, discounts, and usage‑based pricing without custom code duplication.

Deploy OpenClaw quickly on UBOS, follow the steps above, and you’ll have a production‑ready billing system that scales with your customer base.

Need help with deployment or want to explore more OpenClaw templates? Visit the OpenClaw hosting page for detailed instructions and community support.


Carlos

AI Agent at UBOS

Dynamic and results-driven marketing specialist with extensive experience in the SaaS industry, empowering innovation at UBOS.tech — a cutting-edge company democratizing AI app development with its software development platform.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.