From 99dabb4bbdd453902c1f7bdc7409e5a5deb19648 Mon Sep 17 00:00:00 2001 From: shanakamadushanka Date: Mon, 6 Jul 2026 15:48:28 +0530 Subject: [PATCH 1/3] Adding AI API monetizatino guide --- .../monetization/ai-api-monetization.md | 294 ++++++++++++++++++ en/docs/llms.txt | 3 + 2 files changed, 297 insertions(+) create mode 100644 en/docs/guides/monetization/ai-api-monetization.md diff --git a/en/docs/guides/monetization/ai-api-monetization.md b/en/docs/guides/monetization/ai-api-monetization.md new file mode 100644 index 000000000..13d313b70 --- /dev/null +++ b/en/docs/guides/monetization/ai-api-monetization.md @@ -0,0 +1,294 @@ +--- +title: "Monetize an AI API with Stripe" +description: "Charge for an Anthropic Claude AI API without writing billing code: publish an AI proxy with a Pay-as-you-go plan, cap LLM cost with token-based rate limiting, and let WSO2 API Platform sync per-request usage to Stripe for metering and payments." +canonical_url: https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization/ +md_url: https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization.md +tags: + - guides + - monetization + - stripe + - ai-gateway + - anthropic +author: WSO2 API Platform Documentation Team +last_updated: 2026-07-06 +content_type: "tutorial" +--- + +# Monetize an AI API with Stripe + +## Overview + +This guide shows you how to charge consumers for access to an LLM without writing any billing code. You front the Anthropic Claude API with a WSO2 API Platform AI proxy, connect Stripe, and publish a paid subscription plan. WSO2 API Platform syncs usage to Stripe, handles payment processing, enforces subscription access, and gives consumers a self-service billing portal — while a token-based rate limit protects you from runaway LLM cost. + +By the end, you'll have a published Claude AI proxy with a Pay-as-you-go plan, a token quota on every subscription, and per-request Stripe metering on every authenticated call. + +--- + +## Prerequisites + +- A WSO2 API Platform account. Sign up for free at [console.bijira.dev](https://console.bijira.dev). +- An Anthropic API key for the backend Claude API. Create one in the [Anthropic Console](https://console.anthropic.com/). +- A Stripe account with your **Publishable Key** and **Secret Key**. These are available in the Stripe Dashboard under **Developers > API Keys**. +- `curl` for testing. + +--- + +## Architecture + +```text +AI API consumers (developers / apps) + + | HTTPS + OAuth2 bearer token + v + ++-----------------------------------+ +| WSO2 AI Gateway | +| auth · token rate limit · audit | ++-----------------------------------+ + + | HTTPS (backend API key) | usage records + v v + +Anthropic Claude API +---------------------------+ + | Stripe | + | metering · invoicing | + | payment · portal | + +---------------------------+ +``` + +Consumers subscribe to a plan in the Developer Portal, pay via Stripe checkout, and call the AI API with an OAuth2 bearer token. The gateway injects the backend Anthropic key, enforces the token-based rate limit, and reports usage records to Stripe, which handles invoicing, payment collection, and the consumer billing portal. WSO2 API Platform never touches payment details, and consumers never see your Anthropic key. + +--- + +## Step 1: Create and deploy the Claude AI proxy + +Create an AI proxy for the Anthropic Claude provider so the gateway fronts Claude and injects your backend key. + +Follow [Create an API Proxy for an Anthropic Claude AI API](../../cloud/create-api-proxy/third-party-apis/claude.md) to create the proxy, configure the backend endpoint and Anthropic API key, and deploy it to Production. Return here once the **Production** deployment status shows **Active**. + +!!! note + Monetization is applied on the AI proxy, not on the backend. Because the gateway authenticates every consumer and meters every call, you can bill each consumer accurately without exposing your Anthropic key or changing the backend. + +--- + +## Step 2: Cap LLM cost with a token-based rate limit + +Unlike a REST API, an LLM charges you per token, so a single expensive prompt can cost far more than a single cheap one. Attach a token-based rate limit to the AI proxy so each subscription is bounded by a token quota, not just a request count. + +1. In the left navigation menu of your Claude AI proxy, click **Manage**, then click **Policies**. +2. Attach the **Token-Based Rate Limit** policy. +3. Set a per-subscription token quota and time unit — for example, `100000` tokens per **Month**. +4. Click **Save** and redeploy the proxy if prompted. + +**Expected result:** The gateway counts prompt and completion tokens per subscription and blocks calls once the quota is exhausted. + +!!! tip + Pair the token quota with the request-count limit in your subscription plan (Step 4). The request count controls how *often* a consumer can call the API; the token limit controls how *much* LLM work each consumer can consume — the real driver of your Anthropic bill. For details, see [Token-Based Rate Limit for AI APIs](../../cloud/create-api-proxy/third-party-apis/token-ratelimit.md). + +--- + +## Step 3: Connect Stripe + +Connect your Stripe account at the organization level. The platform uses these credentials to create Stripe products, prices, and usage records on your behalf — you don't write any billing code. + +1. In the API Platform Console header, go to the **Organization** list and select your organization. +2. In the left navigation menu, click **Admin**, then click **Settings**. +3. Click the **Credentials** tab, then the **Stripe Credentials** sub-tab. +4. Click **Add Stripe Credentials**. +5. Enter your **Secret Key** and **Publishable Key** from the [Stripe Dashboard](https://dashboard.stripe.com/). +6. Click **Save**. + +**Expected result:** Your Stripe account is connected and ready to process payments for AI API subscriptions. + +!!! note + You can use a Standard secret key or a Restricted secret key. For Restricted keys, see [Getting Started with API Monetization](../../monetization/getting-started.md) for the minimum permissions required. + +--- + +## Step 4: Create a subscription plan + +Create a Pay-as-you-go subscription plan that charges consumers per API request. + +1. In the left navigation menu, click **Admin**, then click **Settings**. +2. Click the **Subscription Plans** tab, then click **+ Create**. +3. Enter the following details: + + | Field | Value | + |---|---| + | **Name** | Pay-as-you-go | + | **Description** | Pay $0.05 per Claude request, billed monthly | + | **Request Count** | 1000 | + | **Request Count Time Unit** | Minute | + | **Pricing Model** | Unit | + | **Currency** | USD | + | **Billing Period** | Monthly | + | **Unit Amount** | 0.05 | + +4. Click **Create**. + +**Expected result:** The Pay-as-you-go plan appears in the Subscription Plans list. + +!!! note + In usage-based models, a unit equals one API request. With the Unit model, the total charge is request count × unit price. For tiered pricing, use Volume or Graduated instead. Set the unit price above your expected per-call Anthropic cost so each billed request stays profitable. + +--- + +## Step 5: Enable the plan on the AI API + +Enable the Pay-as-you-go plan on the Claude AI proxy so consumers can discover and subscribe to it in the Developer Portal. + +1. In the left navigation menu of your Claude AI proxy, click **Manage**, then click **Monetize**. +2. Enable the toggle for **Pay-as-you-go**. +3. Click **Save**. + +**Expected result:** The Pay-as-you-go plan is active on the AI API and appears in the Developer Portal subscription dialog. + +!!! tip + You can enable multiple plans on the same AI API to offer tiered pricing — for example, a free tier with a small token quota alongside this pay-as-you-go tier — without managing separate proxies. + +--- + +## Step 6: Publish the AI API to the Developer Portal + +Publish the AI API so consumers can discover it, review available plans, and subscribe. + +1. In the left navigation menu, click **Manage**, then click **Lifecycle**. +2. Click **Publish**. +3. In the **Publish API** dialog, confirm the details and click **Confirm**. + +**Expected result:** The lifecycle state changes to **Published** and the AI API appears in the Developer Portal. + +--- + +## Step 7: Subscribe to the paid plan + +As an API consumer, subscribe to the Pay-as-you-go plan through the Developer Portal. + +1. Go to [devportal.bijira.dev](https://devportal.bijira.dev) and sign in. +2. In the sidebar, click **APIs**. +3. Find the Claude AI API and click **Subscribe**. +4. In the **Choose Your Subscription Plan** dialog, select an application from the dropdown, or create one named `Claude App`. +5. Click **Subscribe** on the **Pay-as-you-go** plan. +6. A Stripe checkout window opens. Enter your payment details and complete the payment. + +**Expected result:** The application is subscribed to the Claude AI API under the Pay-as-you-go plan. The Stripe checkout confirmation is shown. + +!!! note + Payments are processed by Stripe, and WSO2 API Platform doesn't store your payment details. If your Stripe account is in test mode, use the test card `4242 4242 4242 4242` with any future expiry date and any CVC to complete checkout. + +--- + +## Step 8: Generate API credentials + +Generate OAuth2 credentials for your application so you can make authenticated AI API calls. + +1. In the Developer Portal, click **Applications** and open **Claude App**. +2. Click **Manage Keys**. +3. On the **Production** tab, click **Generate Key**. +4. Copy the **Consumer Key** and **Consumer Secret**. +5. Click **Generate** to generate an access token and copy it. + +**Expected result:** You have an access token ready to use in AI API calls. + +!!! note + Bearer tokens expire after 3600 seconds by default. To extend the lifetime, click **Modify** on the Manage Keys page and increase the **Application Access Token Expiry Time** before generating. + +--- + +## Step 9: Invoke the AI API + +Make your first authenticated call to the monetized Claude AI API using the access token. The gateway authenticates the request, injects your backend Anthropic key, and forwards it to Claude. + +```bash +curl -X POST https:////v1/messages \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -H "anthropic-version: 2023-06-01" \ + -d '{ + "model": "claude-opus-4-8", + "max_tokens": 256, + "messages": [ + { "role": "user", "content": "In one sentence, what is API monetization?" } + ] + }' +``` + +Replace `` and `` with the endpoint from the AI API's **Overview** page in the Developer Portal, and `` with the access token you just copied. + +**Expected result:** `HTTP 200` with a JSON message from Claude. Each successful call increments your usage meter in Stripe and counts against your token quota. + +--- + +## Step 10: View billing and usage + +After making AI API calls, check your usage, upcoming charges, and invoices from the Developer Portal. + +1. In the Developer Portal, click your profile icon in the top right corner. +2. Click **Billing**. +3. On the **Usage Summary** tab, review your **Total Billed API Calls**, **Active Subscriptions**, and **Estimated Cost** for the current period. +4. Click the **Invoices** tab to view and download past invoices. +5. Click the **Billed Subscriptions** tab to see subscription details and click **Manage** to update or cancel. + +**Expected result:** Your Claude AI API calls appear in the usage breakdown with the Pay-as-you-go plan, and the estimated cost reflects your request count × $0.05. + +!!! note + Allow a few minutes for usage to appear in the Billing page after the first request. + +--- + +## Verify + +1. Confirm authenticated calls are billed. Call the AI API with your token and then check the Usage Summary — the call count should increment. + + **Expected result:** The request count in **Billing > Usage Summary** increases by the number of calls made. + +2. Confirm the token quota is enforced. Make repeated calls until the token quota configured in Step 2 is exhausted. + + **Expected result:** The gateway returns `HTTP 429` Too Many Requests once the token limit for the subscription is reached, protecting you from further LLM cost. + +3. Confirm unauthenticated requests are rejected. Call the AI API without an Authorization header. + + ```bash + curl -v -X POST https:////v1/messages + ``` + + **Expected result:** `HTTP 401` Unauthorized. + +4. Confirm subscription enforcement. In the Developer Portal, cancel the Pay-as-you-go subscription under **Billing > Billed Subscriptions > Manage > Cancel**. Then attempt to call the AI API with the same token. + + **Expected result:** `HTTP 403` Forbidden — the gateway revokes access when the subscription lapses. + +--- + +## Troubleshooting + +| Symptom | Resolution | +|---|---| +| Stripe Credentials save fails | Confirm your Secret Key and Publishable Key are from the same Stripe account and that the secret key has the required permissions. | +| AI API calls return `HTTP 401` from the backend | Confirm the backend Anthropic API key is configured on the proxy and is valid in the Anthropic Console. | +| Plans don't appear in Developer Portal subscription dialog | Confirm the plan toggles are enabled in **Manage > Monetize** and the AI API is in the **Published** lifecycle state. | +| Stripe checkout doesn't open | Confirm your Stripe account is active and not in restricted mode. Check the Stripe Dashboard for any pending account verification. | +| `HTTP 401` on every call after subscribing | Confirm your access token is not expired. Generate a new token in **Manage Keys** and update your request. | +| `HTTP 403` after subscribing | Confirm the subscription is active in **Billing > Billed Subscriptions**. If payment failed, the subscription may be inactive. | +| `HTTP 429` sooner than expected | Confirm the token quota in the Token-Based Rate Limit policy matches your intended per-subscription budget. Large prompts and completions consume tokens quickly. | +| Usage not appearing in Billing page | Allow a few minutes after making calls. Usage reporting to Stripe is near-real-time but not instantaneous. | + +--- + +## What you learned + +- Fronted the Anthropic Claude API with a WSO2 API Platform AI proxy so the gateway authenticates consumers and injects the backend key. +- Capped per-subscription LLM cost with a token-based rate limit — the metering dimension that matters most for AI APIs. +- Connected a Stripe account so the platform manages all billing infrastructure without custom code. +- Created a Unit-priced Pay-as-you-go plan, then enabled and published it to the Developer Portal for consumer self-service. +- Invoked a monetized AI API using OAuth2 credentials, with each request automatically metered and reported to Stripe. +- Viewed real-time usage, invoices, and subscription management from the Developer Portal Billing page. + +--- + +## Next steps + +- [Token-Based Rate Limit for AI APIs](../../cloud/create-api-proxy/third-party-apis/token-ratelimit.md) — tune per-subscription token quotas to balance consumer access against your LLM cost. +- [Manage paid subscription plans](../../monetization/manage-paid-subscription-plans.md) — edit, version, or deactivate your plans as your pricing evolves. +- [Monetize a REST API with Stripe](api-monetization.md) — compare the monetization flow for a standard REST API. +- [Monetize MCP Tools with the Self-Hosted Gateway](mcp-tool-monetization.md) — bill AI agents per MCP tool call with the self-hosted AI gateway and Moesif. diff --git a/en/docs/llms.txt b/en/docs/llms.txt index 50061a5c4..cc18f79cd 100644 --- a/en/docs/llms.txt +++ b/en/docs/llms.txt @@ -355,6 +355,9 @@ - [Configure Google Gemini CLI with AI Gateway](https://wso2.com/api-platform/docs/guides/ai-and-mcp/ai-coding-assistants/gemini-cli-configuration-with-ai-gateway.md): Configure Google Gemini CLI to route LLM traffic through the WSO2 AI Gateway - [Configure OpenAI Codex CLI with AI Gateway](https://wso2.com/api-platform/docs/guides/ai-and-mcp/ai-coding-assistants/codex-configuration-with-ai-gateway.md): Configure OpenAI Codex CLI to route LLM traffic through the WSO2 AI Gateway - [Go from Zero to a Working API Call Using the Developer Portal](https://wso2.com/api-platform/docs/guides/developer-portal/api-discovery-and-tryout.md): End-to-end walkthrough: discover an API in the Developer Portal, try it with an API key, subscribe to a plan, and invoke it with rate limiting applied +- [Monetize a REST API with Stripe](https://wso2.com/api-platform/docs/guides/monetization/api-monetization.md): End-to-end walkthrough: publish a REST API with a Pay-as-you-go plan and let WSO2 API Platform sync per-request usage to Stripe for metering and payments, with no billing code +- [Monetize an AI API with Stripe](https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization.md): End-to-end walkthrough: front the Anthropic Claude API with an AI proxy, cap LLM cost with a token-based rate limit, publish a Pay-as-you-go plan, and sync per-request usage to Stripe for metering and payments +- [Monetize MCP Tools with the Self-Hosted Gateway](https://wso2.com/api-platform/docs/guides/monetization/mcp-tool-monetization.md): End-to-end walkthrough: front an MCP server with the self-hosted AI gateway, publish per-tool-call usage to Moesif, and connect Stripe to bill AI agents for the MCP tools they call ## Tools From e13244d21c8a144239611ab53852be1199a14d01 Mon Sep 17 00:00:00 2001 From: shanakamadushanka Date: Wed, 8 Jul 2026 18:44:32 +0530 Subject: [PATCH 2/3] changes --- en/docs/guides/monetization/ai-api-monetization.md | 2 +- en/mkdocs.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/en/docs/guides/monetization/ai-api-monetization.md b/en/docs/guides/monetization/ai-api-monetization.md index 13d313b70..f930d2820 100644 --- a/en/docs/guides/monetization/ai-api-monetization.md +++ b/en/docs/guides/monetization/ai-api-monetization.md @@ -28,7 +28,7 @@ By the end, you'll have a published Claude AI proxy with a Pay-as-you-go plan, a - A WSO2 API Platform account. Sign up for free at [console.bijira.dev](https://console.bijira.dev). - An Anthropic API key for the backend Claude API. Create one in the [Anthropic Console](https://console.anthropic.com/). -- A Stripe account with your **Publishable Key** and **Secret Key**. These are available in the Stripe Dashboard under **Developers > API Keys**. +- A [Stripe account](https://dashboard.stripe.com/) with your **Publishable Key** and **Secret Key**. These are available in the Stripe Dashboard under **Developers > API Keys**. - `curl` for testing. --- diff --git a/en/mkdocs.yml b/en/mkdocs.yml index 61ac00c98..9f844447e 100644 --- a/en/mkdocs.yml +++ b/en/mkdocs.yml @@ -690,6 +690,7 @@ nav: - Go from Zero to a Working API Call Using the Developer Portal: guides/developer-portal/api-discovery-and-tryout.md - Monetization: - API Monetization : guides/monetization/api-monetization.md + - AI API Monetization: guides/monetization/ai-api-monetization.md - MCP Tool Monetization: guides/monetization/mcp-tool-monetization.md - Gateway Federation: - Discover APIs from AWS API Gateway: guides/gateway-federation/discover-apis-from-aws-api-gateway.md From 2bf41280f6956d0db090fb4242d16676f2d95ecd Mon Sep 17 00:00:00 2001 From: shanakamadushanka Date: Wed, 8 Jul 2026 20:15:43 +0530 Subject: [PATCH 3/3] changes --- .../monetization/ai-api-monetization.md | 304 ++++++++---------- en/docs/llms.txt | 2 +- 2 files changed, 134 insertions(+), 172 deletions(-) diff --git a/en/docs/guides/monetization/ai-api-monetization.md b/en/docs/guides/monetization/ai-api-monetization.md index f930d2820..6fe9f353a 100644 --- a/en/docs/guides/monetization/ai-api-monetization.md +++ b/en/docs/guides/monetization/ai-api-monetization.md @@ -1,262 +1,226 @@ --- -title: "Monetize an AI API with Stripe" -description: "Charge for an Anthropic Claude AI API without writing billing code: publish an AI proxy with a Pay-as-you-go plan, cap LLM cost with token-based rate limiting, and let WSO2 API Platform sync per-request usage to Stripe for metering and payments." +title: "Monetize an AI API with the AI Workspace and Moesif" +description: "Charge for an Anthropic Claude LLM API exposed through the WSO2 AI Workspace: attribute usage per consumer with GenAI Applications, publish token usage to Moesif, and connect Stripe to bill consumers for the tokens they consume." canonical_url: https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization/ md_url: https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization.md tags: - guides - monetization - - stripe - - ai-gateway + - ai-workspace + - moesif - anthropic author: WSO2 API Platform Documentation Team -last_updated: 2026-07-06 +last_updated: 2026-07-08 content_type: "tutorial" --- -# Monetize an AI API with Stripe +# Monetize an AI API with the AI Workspace and Moesif ## Overview -This guide shows you how to charge consumers for access to an LLM without writing any billing code. You front the Anthropic Claude API with a WSO2 API Platform AI proxy, connect Stripe, and publish a paid subscription plan. WSO2 API Platform syncs usage to Stripe, handles payment processing, enforces subscription access, and gives consumers a self-service billing portal — while a token-based rate limit protects you from runaway LLM cost. +This guide shows you how to monetize an LLM API — an Anthropic Claude service exposed through the WSO2 AI Workspace — and charge consumers for the tokens they consume. The AI Gateway captures each LLM call as an analytics event, including per-call token usage and the consuming application, and publishes it to Moesif. In Moesif you define usage-based billing meters and connect a billing provider such as Stripe to invoice consumers automatically. No billing code required. -By the end, you'll have a published Claude AI proxy with a Pay-as-you-go plan, a token quota on every subscription, and per-request Stripe metering on every authenticated call. +By the end, you'll have a Claude LLM provider deployed through the AI Workspace, per-consumer usage attributed with GenAI Applications, token usage flowing to Moesif, and a billing meter connected to Stripe. + +!!! note "AI APIs are monetized through Moesif, not Stripe subscription plans" + The Stripe **subscription plan** flow under **Admin > Settings** (used in [Monetize a REST API with Stripe](api-monetization.md)) applies to REST API proxies on the cloud gateway — it is **not** available for AI APIs. LLM traffic through the AI Workspace is billed on **token and cost usage** published to Moesif, which connects to a billing provider such as Stripe. This is the same metered-billing model used for [MCP tool monetization](mcp-tool-monetization.md), and it fits AI APIs because the real cost driver is tokens consumed, not requests made. + +--- + +## Key concepts + +Before you start, here are the terms this guide uses: + +**AI Workspace** is the WSO2 API Platform control plane for AI. You manage LLM providers, App LLM proxies, GenAI applications, guardrails, rate limits, and AI consumption insights from it. + +**AI Gateway** is the runtime that routes requests between consumer applications and LLM providers, enforces policies, and publishes analytics events. + +**LLM Provider** connects the AI Workspace to an AI service such as Anthropic. Consumers call the provider's Invoke URL with a gateway API key; the gateway injects the backend Anthropic key. + +**GenAI Application** represents a real consumer application and groups the API keys it uses, so usage — including tokens and cost — is attributed per application rather than per raw key. This is what lets you bill the right consumer. + +**Moesif** is the analytics and monetization platform WSO2 API Platform integrates with. The AI Workspace Insights page is already Moesif-powered. Moesif receives token-usage events, applies usage-based billing meters, and connects to a billing provider. + +**Billing provider** is the payment platform (such as Stripe, Recurly, or Chargebee) that Moesif connects to for invoicing and payment collection. --- ## Prerequisites - A WSO2 API Platform account. Sign up for free at [console.bijira.dev](https://console.bijira.dev). -- An Anthropic API key for the backend Claude API. Create one in the [Anthropic Console](https://console.anthropic.com/). -- A [Stripe account](https://dashboard.stripe.com/) with your **Publishable Key** and **Secret Key**. These are available in the Stripe Dashboard under **Developers > API Keys**. -- `curl` for testing. +- An Anthropic API key for the backend Claude service. Create one in the [Anthropic Console](https://console.anthropic.com/). +- A Moesif account and a Collector **Application ID**. Sign up at [moesif.com](https://www.moesif.com/). +- A billing provider account (this guide uses Stripe) with access to the [Stripe Dashboard](https://dashboard.stripe.com/) for connecting it to Moesif. +- Python 3 and `pip` for generating traffic with the Anthropic SDK. --- ## Architecture ```text -AI API consumers (developers / apps) +AI API consumers (apps / agents) - | HTTPS + OAuth2 bearer token + | HTTPS + gateway API key (X-API-Key) v +-----------------------------------+ -| WSO2 AI Gateway | -| auth · token rate limit · audit | +| WSO2 AI Gateway | +| auth · token/cost limits · audit | +-----------------------------------+ - | HTTPS (backend API key) | usage records + | HTTPS (backend key) | analytics events (tokens, app) v v Anthropic Claude API +---------------------------+ - | Stripe | - | metering · invoicing | - | payment · portal | + | Moesif | + | usage meters · billing | + +-------------+-------------+ + | + v + +---------------------------+ + | Billing provider | + | (Stripe) invoicing | +---------------------------+ ``` -Consumers subscribe to a plan in the Developer Portal, pay via Stripe checkout, and call the AI API with an OAuth2 bearer token. The gateway injects the backend Anthropic key, enforces the token-based rate limit, and reports usage records to Stripe, which handles invoicing, payment collection, and the consumer billing portal. WSO2 API Platform never touches payment details, and consumers never see your Anthropic key. +A consumer application calls the Claude provider through the gateway with its API key. The gateway validates the key, injects the backend Anthropic key, forwards the call to Claude, and asynchronously publishes a usage event — including token counts and the owning GenAI Application — to Moesif. Moesif meters token usage per consumer and connects to Stripe for invoicing. The gateway never touches payment details, and consumers never see your Anthropic key. --- -## Step 1: Create and deploy the Claude AI proxy +## Step 1: Deploy a Claude LLM provider in the AI Workspace + +Set up an AI Gateway and an Anthropic Claude LLM provider so the gateway fronts Claude and injects your backend key. -Create an AI proxy for the Anthropic Claude provider so the gateway fronts Claude and injects your backend key. +Follow [Get started with AI Workspace](../../cloud/ai-workspace/getting-started.md) to: -Follow [Create an API Proxy for an Anthropic Claude AI API](../../cloud/create-api-proxy/third-party-apis/claude.md) to create the proxy, configure the backend endpoint and Anthropic API key, and deploy it to Production. Return here once the **Production** deployment status shows **Active**. +1. Create and connect an **AI Gateway** so its status is **Active**. +2. Add an **Anthropic** LLM provider with your Anthropic **API Key**, then **Deploy to Gateway**. + +Return here once the provider is deployed and its Invoke URL is available. !!! note - Monetization is applied on the AI proxy, not on the backend. Because the gateway authenticates every consumer and meters every call, you can bill each consumer accurately without exposing your Anthropic key or changing the backend. + Monetization is applied to the LLM provider (or an App LLM proxy), not the backend. Because the gateway authenticates every consumer and records token usage per call, you can bill each consumer accurately without exposing your Anthropic key. --- -## Step 2: Cap LLM cost with a token-based rate limit +## Step 2: Attribute usage per consumer with GenAI Applications -Unlike a REST API, an LLM charges you per token, so a single expensive prompt can cost far more than a single cheap one. Attach a token-based rate limit to the AI proxy so each subscription is bounded by a token quota, not just a request count. +To bill each consumer, the gateway must know *which* consumer made each call. A GenAI Application groups the API keys an application uses, so Moesif can attribute tokens and cost to that application. -1. In the left navigation menu of your Claude AI proxy, click **Manage**, then click **Policies**. -2. Attach the **Token-Based Rate Limit** policy. -3. Set a per-subscription token quota and time unit — for example, `100000` tokens per **Month**. -4. Click **Save** and redeploy the proxy if prompted. +1. In the AI Workspace, generate an **API key** for the deployed Claude provider (**Security** tab of the provider). +2. Open **GenAI Applications** from the left navigation menu and click **+ Create Application**. Name it after the consumer — for example, `Support Copilot`. +3. Open the application, go to **API Keys**, click **Attach API Keys**, and select the key you generated. +4. Save the mapping. -**Expected result:** The gateway counts prompt and completion tokens per subscription and blocks calls once the quota is exhausted. +**Expected result:** Calls made with the mapped key are attributed to the `Support Copilot` GenAI Application in analytics events. !!! tip - Pair the token quota with the request-count limit in your subscription plan (Step 4). The request count controls how *often* a consumer can call the API; the token limit controls how *much* LLM work each consumer can consume — the real driver of your Anthropic bill. For details, see [Token-Based Rate Limit for AI APIs](../../cloud/create-api-proxy/third-party-apis/token-ratelimit.md). + Create one GenAI Application per paying consumer or workload, and map every key that consumer uses. Complete mappings keep the billing attribution accurate. See [GenAI Applications](../../cloud/ai-workspace/genai-applications.md) for details. --- -## Step 3: Connect Stripe +## Step 3: Protect your margin with a cost or token limit -Connect your Stripe account at the organization level. The platform uses these credentials to create Stripe products, prices, and usage records on your behalf — you don't write any billing code. +Unlike a REST API, an LLM charges you per token, so a single expensive prompt can cost far more than a cheap one. Bound each consumer so a runaway workload can't exceed what they pay for. -1. In the API Platform Console header, go to the **Organization** list and select your organization. -2. In the left navigation menu, click **Admin**, then click **Settings**. -3. Click the **Credentials** tab, then the **Stripe Credentials** sub-tab. -4. Click **Add Stripe Credentials**. -5. Enter your **Secret Key** and **Publishable Key** from the [Stripe Dashboard](https://dashboard.stripe.com/). -6. Click **Save**. +1. In the AI Workspace, open the Claude provider (or an App LLM proxy) and go to the rate-limit configuration. +2. Attach one of: + - **Token-Based Rate Limit** — cap prompt and completion tokens per time window. See [Token-Based Rate Limit](../../cloud/ai-workspace/policies/rate-limit/token-based-rate-limit.md). + - **LLM Cost-Based Rate Limit** — cap spend in USD per time window (pair it with the [LLM Cost](../../cloud/ai-workspace/policies/rate-limit/llm-cost.md) policy). See [LLM Cost-Based Rate Limit](../../cloud/ai-workspace/policies/rate-limit/llm-cost-based-rate-limit.md). +3. Set a per-consumer limit — for example, `100000` tokens per **Month** — then deploy the provider to apply it. -**Expected result:** Your Stripe account is connected and ready to process payments for AI API subscriptions. - -!!! note - You can use a Standard secret key or a Restricted secret key. For Restricted keys, see [Getting Started with API Monetization](../../monetization/getting-started.md) for the minimum permissions required. +**Expected result:** The gateway blocks calls with `HTTP 429` once a consumer exceeds the configured token or cost limit, protecting you from unbounded LLM spend. --- -## Step 4: Create a subscription plan - -Create a Pay-as-you-go subscription plan that charges consumers per API request. +## Step 4: Publish AI usage to Moesif -1. In the left navigation menu, click **Admin**, then click **Settings**. -2. Click the **Subscription Plans** tab, then click **+ Create**. -3. Enter the following details: +The AI Workspace Insights page is already Moesif-powered, but monetization needs the events in *your* Moesif organization where you control billing meters. Connect your Moesif Collector Application ID at the organization level. - | Field | Value | - |---|---| - | **Name** | Pay-as-you-go | - | **Description** | Pay $0.05 per Claude request, billed monthly | - | **Request Count** | 1000 | - | **Request Count Time Unit** | Minute | - | **Pricing Model** | Unit | - | **Currency** | USD | - | **Billing Period** | Monthly | - | **Unit Amount** | 0.05 | +Follow [Integrate API Platform with Moesif](../../cloud/monitoring-and-insights/integrate-bijira-with-moesif.md) to: -4. Click **Create**. +1. Copy your Moesif **Collector Application Id**. +2. In the API Platform Console, go to **Admin > Settings** at the organization level, open **Moesif Dashboard**, select your environment, paste the Application Id, and click **Add**. -**Expected result:** The Pay-as-you-go plan appears in the Subscription Plans list. +**Expected result:** The gateway publishes every LLM call — with token usage and the owning GenAI Application — to your Moesif organization. !!! note - In usage-based models, a unit equals one API request. With the Unit model, the total charge is request count × unit price. For tiered pricing, use Volume or Graduated instead. Set the unit price above your expected per-call Anthropic cost so each billed request stays profitable. - ---- - -## Step 5: Enable the plan on the AI API - -Enable the Pay-as-you-go plan on the Claude AI proxy so consumers can discover and subscribe to it in the Developer Portal. - -1. In the left navigation menu of your Claude AI proxy, click **Manage**, then click **Monetize**. -2. Enable the toggle for **Pay-as-you-go**. -3. Click **Save**. - -**Expected result:** The Pay-as-you-go plan is active on the AI API and appears in the Developer Portal subscription dialog. - -!!! tip - You can enable multiple plans on the same AI API to offer tiered pricing — for example, a free tier with a small token quota alongside this pay-as-you-go tier — without managing separate proxies. + After configuring the Moesif key, wait about five minutes before generating traffic so the integration is fully active. --- -## Step 6: Publish the AI API to the Developer Portal - -Publish the AI API so consumers can discover it, review available plans, and subscribe. +## Step 5: Generate LLM traffic -1. In the left navigation menu, click **Manage**, then click **Lifecycle**. -2. Click **Publish**. -3. In the **Publish API** dialog, confirm the details and click **Confirm**. +Call the Claude provider with the mapped API key so Moesif receives token-usage events attributed to your GenAI Application. -**Expected result:** The lifecycle state changes to **Published** and the AI API appears in the Developer Portal. +```python +import anthropic ---- +INVOKE_URL = "https:///" # from the provider's Invoke URL +API_KEY = "" # the key mapped to Support Copilot -## Step 7: Subscribe to the paid plan +client = anthropic.Anthropic(api_key=API_KEY, base_url=INVOKE_URL) -As an API consumer, subscribe to the Pay-as-you-go plan through the Developer Portal. +response = client.messages.create( + model="claude-opus-4-8", + max_tokens=256, + messages=[{"role": "user", "content": "In one sentence, what is API monetization?"}], +) -1. Go to [devportal.bijira.dev](https://devportal.bijira.dev) and sign in. -2. In the sidebar, click **APIs**. -3. Find the Claude AI API and click **Subscribe**. -4. In the **Choose Your Subscription Plan** dialog, select an application from the dropdown, or create one named `Claude App`. -5. Click **Subscribe** on the **Pay-as-you-go** plan. -6. A Stripe checkout window opens. Enter your payment details and complete the payment. +print(response.content[0].text) +``` -**Expected result:** The application is subscribed to the Claude AI API under the Pay-as-you-go plan. The Stripe checkout confirmation is shown. +Replace `/` with the provider's Invoke URL and `` with the mapped key. The Anthropic SDK sends the key as the `x-api-key` header automatically. -!!! note - Payments are processed by Stripe, and WSO2 API Platform doesn't store your payment details. If your Stripe account is in test mode, use the test card `4242 4242 4242 4242` with any future expiry date and any CVC to complete checkout. +**Expected result:** A successful Claude response. Within a few seconds, the call appears in your Moesif **Live Event Log** with token counts and the `Support Copilot` application. For other SDKs and languages, see [Invoke providers and proxies via SDKs](../../cloud/ai-workspace/using-sdks.md). --- -## Step 8: Generate API credentials +## Step 6: Create a usage-based billing meter in Moesif -Generate OAuth2 credentials for your application so you can make authenticated AI API calls. +In Moesif, define a billing meter that turns token usage into a billable quantity. This is where you decide what to charge for and how much. -1. In the Developer Portal, click **Applications** and open **Claude App**. -2. Click **Manage Keys**. -3. On the **Production** tab, click **Generate Key**. -4. Copy the **Consumer Key** and **Consumer Secret**. -5. Click **Generate** to generate an access token and copy it. +1. In the Moesif dashboard, go to **Billing Meters** and create a new meter. +2. Set the meter to aggregate token usage — for example, sum the total-tokens field on each event — and filter the events to your Claude traffic (by provider, endpoint, or company/user mapped from the GenAI Application). +3. Choose a pricing model (for example, a per-1K-token unit price, or tiered/volume pricing) and a billing period. +4. Save the meter. -**Expected result:** You have an access token ready to use in AI API calls. +**Expected result:** The meter aggregates incoming token-usage events into a billable quantity per consumer. !!! note - Bearer tokens expire after 3600 seconds by default. To extend the lifetime, click **Modify** on the Manage Keys page and increase the **Application Access Token Expiry Time** before generating. + Because the gateway publishes token counts and the consumer identity with each event, you can meter per token, per model, or per consumer. Set your price above your Anthropic per-token cost so each billed token stays profitable. See the [Moesif metered billing documentation](https://www.moesif.com/docs/metered-billing/) for meter configuration. --- -## Step 9: Invoke the AI API - -Make your first authenticated call to the monetized Claude AI API using the access token. The gateway authenticates the request, injects your backend Anthropic key, and forwards it to Claude. - -```bash -curl -X POST https:////v1/messages \ - -H "Authorization: Bearer " \ - -H "Content-Type: application/json" \ - -H "anthropic-version: 2023-06-01" \ - -d '{ - "model": "claude-opus-4-8", - "max_tokens": 256, - "messages": [ - { "role": "user", "content": "In one sentence, what is API monetization?" } - ] - }' -``` - -Replace `` and `` with the endpoint from the AI API's **Overview** page in the Developer Portal, and `` with the access token you just copied. - -**Expected result:** `HTTP 200` with a JSON message from Claude. Each successful call increments your usage meter in Stripe and counts against your token quota. - ---- +## Step 7: Connect Stripe as the billing provider -## Step 10: View billing and usage +Connect Moesif to Stripe so metered token usage is converted into invoices and payments automatically. -After making AI API calls, check your usage, upcoming charges, and invoices from the Developer Portal. +1. In the Moesif dashboard, open **Settings > Extensions** (or **Billing Provider**) and select **Stripe**. +2. Authorize Moesif to access your Stripe account, or enter your Stripe API key. +3. Map your Moesif billing meter to a Stripe product and price. +4. Save the integration. -1. In the Developer Portal, click your profile icon in the top right corner. -2. Click **Billing**. -3. On the **Usage Summary** tab, review your **Total Billed API Calls**, **Active Subscriptions**, and **Estimated Cost** for the current period. -4. Click the **Invoices** tab to view and download past invoices. -5. Click the **Billed Subscriptions** tab to see subscription details and click **Manage** to update or cancel. - -**Expected result:** Your Claude AI API calls appear in the usage breakdown with the Pay-as-you-go plan, and the estimated cost reflects your request count × $0.05. +**Expected result:** Moesif reports metered token usage to Stripe, which issues invoices and collects payment from subscribed consumers. WSO2 API Platform never stores payment details. !!! note - Allow a few minutes for usage to appear in the Billing page after the first request. + Moesif also integrates with Recurly, Chargebee, and Zuora. The same metered token usage drives billing regardless of the provider you choose. --- ## Verify -1. Confirm authenticated calls are billed. Call the AI API with your token and then check the Usage Summary — the call count should increment. - - **Expected result:** The request count in **Billing > Usage Summary** increases by the number of calls made. - -2. Confirm the token quota is enforced. Make repeated calls until the token quota configured in Step 2 is exhausted. - - **Expected result:** The gateway returns `HTTP 429` Too Many Requests once the token limit for the subscription is reached, protecting you from further LLM cost. +1. Confirm token usage is captured. Make a call with the mapped key, then open the Moesif **Live Event Log**. -3. Confirm unauthenticated requests are rejected. Call the AI API without an Authorization header. + **Expected result:** The call appears with token counts and the `Support Copilot` GenAI Application. - ```bash - curl -v -X POST https:////v1/messages - ``` +2. Confirm the cost/token limit is enforced. Make repeated calls until the limit from Step 3 is exceeded. - **Expected result:** `HTTP 401` Unauthorized. + **Expected result:** The gateway returns `HTTP 429` Too Many Requests, and no further LLM cost is incurred for that consumer in the period. -4. Confirm subscription enforcement. In the Developer Portal, cancel the Pay-as-you-go subscription under **Billing > Billed Subscriptions > Manage > Cancel**. Then attempt to call the AI API with the same token. +3. Confirm usage drives billing. Make several calls, then open the billing meter in Moesif. - **Expected result:** `HTTP 403` Forbidden — the gateway revokes access when the subscription lapses. + **Expected result:** The meter quantity increases by the tokens consumed, and the projected charge reflects your configured price. --- @@ -264,31 +228,29 @@ After making AI API calls, check your usage, upcoming charges, and invoices from | Symptom | Resolution | |---|---| -| Stripe Credentials save fails | Confirm your Secret Key and Publishable Key are from the same Stripe account and that the secret key has the required permissions. | -| AI API calls return `HTTP 401` from the backend | Confirm the backend Anthropic API key is configured on the proxy and is valid in the Anthropic Console. | -| Plans don't appear in Developer Portal subscription dialog | Confirm the plan toggles are enabled in **Manage > Monetize** and the AI API is in the **Published** lifecycle state. | -| Stripe checkout doesn't open | Confirm your Stripe account is active and not in restricted mode. Check the Stripe Dashboard for any pending account verification. | -| `HTTP 401` on every call after subscribing | Confirm your access token is not expired. Generate a new token in **Manage Keys** and update your request. | -| `HTTP 403` after subscribing | Confirm the subscription is active in **Billing > Billed Subscriptions**. If payment failed, the subscription may be inactive. | -| `HTTP 429` sooner than expected | Confirm the token quota in the Token-Based Rate Limit policy matches your intended per-subscription budget. Large prompts and completions consume tokens quickly. | -| Usage not appearing in Billing page | Allow a few minutes after making calls. Usage reporting to Stripe is near-real-time but not instantaneous. | +| Calls return `HTTP 401` from the gateway | Confirm you are sending the gateway API key in the location set on the provider's **Security** tab (default `X-API-Key`). | +| Calls return `HTTP 401` from the backend | Confirm the backend Anthropic API key on the provider is valid in the Anthropic Console. | +| Usage not attributed to a GenAI Application | Confirm the API key used for the call is attached to the application in **GenAI Applications > API Keys**. | +| No events appear in Moesif | Confirm the Moesif Collector Application Id is configured under **Admin > Settings > Moesif Dashboard**, and that you waited a few minutes after adding it. | +| Events appear in Moesif but the meter stays at zero | Confirm the billing meter's filter matches your Claude traffic and that it aggregates the token-usage field. | +| `HTTP 429` sooner than expected | Confirm the token or cost limit matches your intended per-consumer budget. Large prompts and completions consume tokens quickly. | +| Stripe invoices not generated | Confirm the Stripe integration is authorized in Moesif and the billing meter is mapped to a Stripe product and price. | --- ## What you learned -- Fronted the Anthropic Claude API with a WSO2 API Platform AI proxy so the gateway authenticates consumers and injects the backend key. -- Capped per-subscription LLM cost with a token-based rate limit — the metering dimension that matters most for AI APIs. -- Connected a Stripe account so the platform manages all billing infrastructure without custom code. -- Created a Unit-priced Pay-as-you-go plan, then enabled and published it to the Developer Portal for consumer self-service. -- Invoked a monetized AI API using OAuth2 credentials, with each request automatically metered and reported to Stripe. -- Viewed real-time usage, invoices, and subscription management from the Developer Portal Billing page. +- Deployed an Anthropic Claude LLM provider through the AI Workspace so the gateway authenticates consumers and injects the backend key. +- Attributed usage per consumer with GenAI Applications — the basis for per-consumer billing. +- Bounded per-consumer LLM spend with a token-based or cost-based rate limit — the metering dimension that matters most for AI APIs. +- Published token-usage events to Moesif and created a usage-based billing meter that counts tokens per consumer. +- Connected Stripe as the billing provider so metered token usage is invoiced and collected automatically, without billing code. --- ## Next steps -- [Token-Based Rate Limit for AI APIs](../../cloud/create-api-proxy/third-party-apis/token-ratelimit.md) — tune per-subscription token quotas to balance consumer access against your LLM cost. -- [Manage paid subscription plans](../../monetization/manage-paid-subscription-plans.md) — edit, version, or deactivate your plans as your pricing evolves. -- [Monetize a REST API with Stripe](api-monetization.md) — compare the monetization flow for a standard REST API. -- [Monetize MCP Tools with the Self-Hosted Gateway](mcp-tool-monetization.md) — bill AI agents per MCP tool call with the self-hosted AI gateway and Moesif. +- [Insights](../../cloud/ai-workspace/insights.md) — analyze token usage, cost, and per-application activity to tune your meters and limits. +- [LLM Cost-Based Rate Limit](../../cloud/ai-workspace/policies/rate-limit/llm-cost-based-rate-limit.md) — enforce USD spending budgets per consumer. +- [Monetize MCP Tools with the Self-Hosted Gateway](mcp-tool-monetization.md) — bill AI agents per MCP tool call with Moesif and Stripe. +- [Monetize a REST API with Stripe](api-monetization.md) — compare the subscription-plan monetization flow for standard REST APIs. diff --git a/en/docs/llms.txt b/en/docs/llms.txt index cc18f79cd..38c1b0b24 100644 --- a/en/docs/llms.txt +++ b/en/docs/llms.txt @@ -356,7 +356,7 @@ - [Configure OpenAI Codex CLI with AI Gateway](https://wso2.com/api-platform/docs/guides/ai-and-mcp/ai-coding-assistants/codex-configuration-with-ai-gateway.md): Configure OpenAI Codex CLI to route LLM traffic through the WSO2 AI Gateway - [Go from Zero to a Working API Call Using the Developer Portal](https://wso2.com/api-platform/docs/guides/developer-portal/api-discovery-and-tryout.md): End-to-end walkthrough: discover an API in the Developer Portal, try it with an API key, subscribe to a plan, and invoke it with rate limiting applied - [Monetize a REST API with Stripe](https://wso2.com/api-platform/docs/guides/monetization/api-monetization.md): End-to-end walkthrough: publish a REST API with a Pay-as-you-go plan and let WSO2 API Platform sync per-request usage to Stripe for metering and payments, with no billing code -- [Monetize an AI API with Stripe](https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization.md): End-to-end walkthrough: front the Anthropic Claude API with an AI proxy, cap LLM cost with a token-based rate limit, publish a Pay-as-you-go plan, and sync per-request usage to Stripe for metering and payments +- [Monetize an AI API with the AI Workspace and Moesif](https://wso2.com/api-platform/docs/guides/monetization/ai-api-monetization.md): End-to-end walkthrough: expose an Anthropic Claude LLM through the AI Workspace, attribute usage per consumer with GenAI Applications, publish token usage to Moesif, and connect Stripe to bill consumers for the tokens they consume - [Monetize MCP Tools with the Self-Hosted Gateway](https://wso2.com/api-platform/docs/guides/monetization/mcp-tool-monetization.md): End-to-end walkthrough: front an MCP server with the self-hosted AI gateway, publish per-tool-call usage to Moesif, and connect Stripe to bill AI agents for the MCP tools they call ## Tools