Guide and insight

Build an AI API Reseller Portal: Tenant Provisioning, Usage Metering, Billing, and Telegram Ops

A practical reference architecture for agencies, consultants, and SaaS builders packaging AI API access for customers: tenant records, customer-scoped keys, spend limits, usage ledgers, billing sync, and Telegram operations.

If you package AI access for clients, do not hand them your upstream provider keys. Build a reseller layer that issues customer-scoped keys, enforces tenant limits before every request, records usage in your own ledger, and syncs billable totals to your billing system.

This guide describes a practical operating model for an AI API for agencies, consultants, and SaaS builders. It is not a customer case study. It is a reference architecture you can adapt whether you use a Partner API, an internal gateway, or a custom proxy in front of multiple model providers.

The reseller portal architecture

A safe reseller portal separates four responsibilities:

  • Partner administration: your internal app for creating customers, plans, keys, limits, and support workflows.
  • Request enforcement: the gateway path that authenticates customer keys, checks policy, routes requests, and blocks over-limit traffic.
  • Usage accounting: a durable ledger that records request-level usage and pricing inputs.
  • Billing and operations: scheduled invoice sync, alerts, key rotation notices, and support escalation.

A typical flow looks like this:

Partner Admin App
  → Partner API
    → customer / workspace records
    → customer-scoped API keys
    → plan, model, budget, and rate limits
    → request gateway
    → usage ledger
    → billing sync
    → Telegram notification bot

Fact: OpenAI recommends not sharing user-based API keys for collaboration and instead using project-based keys, assigned members, and distinct keys with isolated rate limits and spend controls. OpenAI’s services terms also prohibit buying, selling, or transferring API keys to or from a third party. Those facts support a reseller design where upstream credentials stay server-side and customers receive your own downstream keys.

Recommendation: issue one downstream key per customer, project, or environment. Do not reuse one customer key across multiple end clients. Do not expose upstream provider credentials in documentation, browser code, mobile apps, logs, or client support messages.

Tenant data model

The tenant model should make isolation explicit. At minimum, store these fields:

partner_id
customer_id
workspace_id
api_key_id
plan_id
billing_status
spend_limit
rate_limit
allowed_models
telegram_chat_id
usage_ledger_id
created_at
updated_at
revoked_at

In a larger portal, add fields for prepaid balance, currency, tax region, invoice customer ID, support tier, abuse status, and temporary overrides.

Example customer record

{
  "partner_id": "partner_123",
  "customer_id": "cust_acme",
  "workspace_id": "ws_prod",
  "plan_id": "growth_api",
  "billing_status": "active",
  "spend_limit": {
    "period": "month",
    "hard_cap_usd": 500,
    "alert_thresholds": [0.5, 0.8, 0.95]
  },
  "rate_limit": {
    "requests_per_minute": 120,
    "tokens_per_day": 2000000
  },
  "allowed_models": ["fast-chat", "reasoning-standard"],
  "telegram_chat_id": "-1001234567890",
  "usage_ledger_id": "ledger_cust_acme"
}

Recommendation: treat customer_id, workspace_id, and api_key_id as separate concepts. A customer may have multiple workspaces, and each workspace may need separate production, staging, and development keys. This makes revocation, debugging, and usage attribution much easier.

Onboarding sequence for a new customer

A reliable onboarding flow is boring by design. It should produce the same records every time and leave an audit trail.

  1. Create the customer: store legal name, billing contact, technical contact, and internal owner.
  2. Create a workspace: separate production from testing if the customer will integrate programmatically.
  3. Assign a plan: define included models, markup, billing cadence, and support expectations.
  4. Set limits: configure spend caps, request limits, token limits, and burst policy.
  5. Create API keys: issue scoped keys for the customer’s environments.
  6. Send integration instructions: provide base URL, authentication format, model list, limits, and support channel.
  7. Enable alerts: connect Telegram or another operations channel for low-balance, key, outage, and billing notices.
  8. Run a test request: verify authentication, usage recording, model access, and invoice mapping.

Recommendation: make onboarding idempotent. If your admin app retries a “create customer” operation, it should not create duplicate billing records or duplicate API keys. Use external IDs and idempotency keys for provisioning calls.

Request-time budget control

The most important enforcement happens before the request reaches an upstream model. Your gateway should not discover that a customer is over budget only after the provider has already charged you.

Use this preflight sequence:

  1. Authenticate the downstream API key.
  2. Resolve partner_id, customer_id, and workspace_id.
  3. Check whether the key is active and not revoked.
  4. Check billing status: active, trialing, prepaid, paused, overdue, or suspended.
  5. Check hard spend cap for the current billing period.
  6. Check rate limits, such as requests per minute and tokens per day.
  7. Check whether the requested model is allowed for the customer’s plan.
  8. Estimate maximum possible cost from model, max tokens, and request parameters.
  9. Route the request only if the policy passes.
if key.revoked:
    reject(401, "API key revoked")

if customer.billing_status in ["paused", "suspended", "overdue"]:
    reject(402, "Billing status does not allow usage")

if requested_model not in customer.allowed_models:
    reject(403, "Model not enabled for this workspace")

if current_period_spend + estimated_max_cost > customer.hard_cap:
    reject(402, "Spend limit exceeded")

if rate_limit_exceeded(customer_id, requested_model):
    reject(429, "Rate limit exceeded")

route_request()

Fact: OWASP API Security Top 10 2023 calls out broken object authorization, broken authentication, and unrestricted resource consumption as major API risks. These map directly to reseller portals: one tenant must not read another tenant’s data, keys must not be bypassable, and one customer must not be able to create unlimited provider spend.

Trade-off: strict hard caps protect your margin, but they can interrupt legitimate spikes. A good compromise is a temporary override workflow with an expiry time, approver, reason, and audit log entry.

Usage ledger as the source of truth

For real-time access control, keep your own usage ledger. External billing tools are excellent for invoicing, but they are usually not the right place to make millisecond-level allow-or-deny decisions.

A usage event should capture enough detail to reconcile provider invoices, explain customer bills, and debug disputes:

{
  "request_id": "req_01J...",
  "idempotency_key": "idem_abc123",
  "partner_id": "partner_123",
  "customer_id": "cust_acme",
  "workspace_id": "ws_prod",
  "api_key_id": "key_live_789",
  "model": "reasoning-standard",
  "input_tokens": 1850,
  "output_tokens": 420,
  "cached_tokens": 1200,
  "provider_cost": 0.0142,
  "reseller_price": 0.0230,
  "currency": "USD",
  "timestamp": "2026-08-02T10:15:30Z",
  "status": "succeeded"
}

Record failed requests too, but distinguish failures that are billable from failures that are not. Provider timeouts, validation failures, customer cancellations, retries, and safety blocks may have different accounting outcomes depending on when they occur.

Recommendation: write a pending ledger event when the request is accepted, then finalize it when token usage and cost are known. This allows you to reserve budget before routing and then correct the final amount after completion.

Reconciliation pattern

  1. Store request-level events in the internal ledger.
  2. Aggregate usage by customer, model, and billing period.
  3. Compare internal totals against upstream provider invoices or usage exports.
  4. Investigate material differences before issuing invoices.
  5. Sync summarized billable usage to the billing system.

Trade-off: syncing summarized usage reduces billing event volume and complexity, but it can make customer invoices less detailed. If customers need model-level or project-level reporting, preserve those dimensions in your billing sync or customer dashboard.

Billing sync with usage-based meters

Usage-based billing systems generally follow a pattern: define products and prices, ingest usage events, aggregate them over a billing period, generate invoices, and monitor errors. Stripe Billing, for example, supports meter events with an event name, customer identifier, numerical value, optional timestamp, optional idempotency identifier, and optional dimensions.

For AI API billing, common meter choices are:

  • Token total: useful when pricing is closely tied to input and output tokens.
  • Request count: useful for simple plans or low-token API calls.
  • Model-specific units: useful when premium models have different margins.
  • Seats or active workspaces: useful for hybrid SaaS-plus-usage plans.

Fact: Stripe meters support aggregation formulas such as sum, count, and last. Those map to token totals, request counts, and state-like values such as seats or active limits.

A daily billing sync might create meter events like this:

{
  "event_name": "ai_tokens_used",
  "customer": "stripe_customer_456",
  "value": 2270000,
  "timestamp": "2026-08-02T23:59:00Z",
  "idempotency_key": "cust_acme_2026-08-02_tokens",
  "dimensions": {
    "plan": "growth_api",
    "model_family": "standard"
  }
}

Recommendation: keep the internal ledger more granular than the invoice. You can invoice daily token totals while still retaining request-level records for support, fraud review, rate-limit tuning, and margin analysis.

Telegram operations without making Telegram the system of record

Telegram is useful for fast operator workflows: support teams already notice messages, bots can send alerts, and customers can receive onboarding instructions without logging into a dashboard. But Telegram should not be the only audit trail for billing, security, or support decisions.

Good Telegram workflows include:

  • Low-balance or high-spend alerts at 50%, 80%, and 95% of a cap.
  • New customer onboarding messages with documentation links and masked key names.
  • API-key rotation notices before and after rotation.
  • Provider outage or degraded-model alerts.
  • Human support escalation when a customer hits repeated 401, 402, 403, or 429 errors.

Fact: Telegram Bot API calls are made over HTTPS to bot-token endpoints, and Telegram webhooks can include a secret token header to help verify webhook origin.

Recommendation: store Telegram chat IDs as tenant metadata, but do not expose them across customers. Log every bot-triggered administrative action in your internal audit log with actor, timestamp, customer, old value, new value, and reason.

Security and isolation checklist

Before selling access, test tenant isolation as if a customer is actively trying to cross boundaries.

  • Customer A cannot view Customer B API keys.
  • Customer A cannot view Customer B usage, invoices, limits, Telegram chat IDs, or billing status.
  • A revoked key fails immediately on all request paths.
  • A billing-paused customer cannot continue spending through cached sessions or old keys.
  • A customer cannot request models outside the assigned plan.
  • Rate limits apply by customer and workspace, not only by global IP address.
  • Webhook handlers verify signatures or secret headers where supported.
  • All provisioning, limit changes, key rotations, and billing overrides create audit log entries.
  • Retry logic uses idempotency keys so duplicate requests do not double-bill customers.
  • Support tools mask secrets and restrict who can reveal or rotate keys.

Prediction: reseller portals will increasingly compete on governance and billing clarity, not only on access to many models. Customers will expect per-project usage, clear invoices, fast key rotation, and hard spend controls as standard features.

Key trade-offs to decide early

Prepaid versus postpaid

Prepaid balances reduce credit risk and make hard cutoffs straightforward, but customers may dislike interruptions. Postpaid billing is smoother for established customers, but it requires credit checks, dunning workflows, and stronger anomaly detection.

One blended price versus model-specific pricing

A blended price is easier to explain. Model-specific pricing protects margins and encourages efficient model selection. If you offer many models, publish a simple customer-facing model catalog and hide unnecessary provider-specific complexity.

Real-time metering versus delayed billing

Real-time metering enables spend caps and prepaid balances. It also requires durable writes, replay handling, and reconciliation. Delayed billing is simpler, but it exposes you to runaway spend before limits take effect.

Telegram-first support versus dashboard-first support

Telegram is fast and familiar for many operators. A dashboard is better for auditability, exports, permissions, and customer self-service. Use Telegram for notifications and approvals, but store the canonical record in your system.

Actionable rollout plan

  1. Start with tenant isolation: implement customer, workspace, key, plan, and limit records before adding advanced billing features.
  2. Build preflight enforcement: block revoked keys, suspended billing, disallowed models, and over-limit traffic before routing.
  3. Create the usage ledger: record request IDs, token counts, costs, reseller prices, statuses, timestamps, and idempotency keys.
  4. Add reconciliation: compare internal usage against upstream provider totals before invoicing.
  5. Sync billing summaries: send daily or hourly aggregates to your billing platform with stable customer mappings and idempotency keys.
  6. Wire Telegram alerts: start with low-balance, outage, key rotation, and support escalation messages.
  7. Run isolation tests: verify that no customer can access another customer’s keys, usage, limits, invoices, or chat metadata.

A reseller portal is not just a wrapper around an AI API. It is an operating layer for authentication, tenant policy, usage analytics, billing, and support. Build the ledger and limits first, keep upstream keys server-side, and make every customer-facing key revocable, scoped, and attributable.

Related reading

FAQ

Frequently asked questions

Should an AI API reseller give customers upstream provider API keys?
No. A safer pattern is to keep upstream provider credentials server-side and issue your own downstream customer-scoped keys. This supports revocation, usage attribution, spend limits, and tenant isolation.
Should billing be based on request counts or tokens?
It depends on the product. Token billing tracks model costs more closely, request billing is easier to explain, and model-specific units protect margins when customers can choose expensive models. Many resellers use a hybrid approach.
Why keep an internal usage ledger if a billing platform already stores usage?
The internal ledger supports real-time access control, prepaid balances, hard spend caps, debugging, and reconciliation. The billing platform can receive summarized usage for invoicing.
Can Telegram be used for customer operations?
Yes, Telegram can work well for alerts, onboarding notices, outage messages, key rotation notices, and support escalation. It should not be the only audit trail for billing, security, or administrative decisions.