# Create a new account
Source: https://docs.easybilling.cloud/api-reference/account/create-a-new-account
/billing.openapi.json post /api/accounts
# Get an account by Accoumt Number
Source: https://docs.easybilling.cloud/api-reference/account/get-an-account-by-accoumt-number
/billing.openapi.json get /api/accounts/number/{accountNumber}
# Get an account by id
Source: https://docs.easybilling.cloud/api-reference/account/get-an-account-by-id
/billing.openapi.json get /api/accounts/{id}
# Update an account by id
Source: https://docs.easybilling.cloud/api-reference/account/update-an-account-by-id
/billing.openapi.json put /api/accounts/{id}
# Get credit memo details by id
Source: https://docs.easybilling.cloud/api-reference/billing-document/get-credit-memo-details-by-id
/billing.openapi.json get /api/credit-memos/{memoId}
# Get invoice details by id
Source: https://docs.easybilling.cloud/api-reference/billing-document/get-invoice-details-by-id
/billing.openapi.json get /api/invoices/{invoiceId}
# Query invoices & credit memos
Source: https://docs.easybilling.cloud/api-reference/billing-document/query-invoices-&-credit-memos
/billing.openapi.json post /api/data-query
# Create Contract Action
Source: https://docs.easybilling.cloud/api-reference/contract-action/create-contract-action
/billing.openapi.json post /api/contract-actions
# generate customer portal account token
Source: https://docs.easybilling.cloud/api-reference/customer-portal/generate-customer-portal-account-token
/billing.openapi.json post /api/authenticate/account-auth
# Preset payment method by account
Source: https://docs.easybilling.cloud/api-reference/customer-portal/preset-payment-method-by-account
/billing.openapi.json post /api/payment-methods/account
Presets a payment method for a customer on the selected payment gateway and returns
the gateway-hosted setup page URL.
The request body is polymorphic and is selected by paymentGatewayType.
# download pdf
Source: https://docs.easybilling.cloud/api-reference/invoice-pdf/download-pdf
/billing.openapi.json get /template-engine/api/pdf/{id}
# generate pdf
Source: https://docs.easybilling.cloud/api-reference/invoice-pdf/generate-pdf
/billing.openapi.json post /template-engine/api/pdf/generate
# get pdf list by invoice id
Source: https://docs.easybilling.cloud/api-reference/invoice-pdf/get-pdf-list-by-invoice-id
/billing.openapi.json get /template-engine/api/pdf/object/{id}
# preview pdf
Source: https://docs.easybilling.cloud/api-reference/invoice-pdf/preview-pdf
/billing.openapi.json post /template-engine/api/pdf/preview
# Close transaction
Source: https://docs.easybilling.cloud/api-reference/payment-hub/close-transaction
/payment.openapi.json put /api/transactions/{transactionId}/status
# Get payment list
Source: https://docs.easybilling.cloud/api-reference/payment-hub/get-payment-list
/payment.openapi.json post /api/data-query
# Initiate refund
Source: https://docs.easybilling.cloud/api-reference/payment-hub/initiate-refund
/payment.openapi.json post /api/refund
# Initiate transaction
Source: https://docs.easybilling.cloud/api-reference/payment-hub/initiate-transaction
/payment.openapi.json post /api/transactions
Creates a new payment request and returns the gateway redirect URL and the payment transaction status. Idempotent on transactionId — re-issuing an already-PROCESSING / FAILED transaction may reuse the existing gateway link or re-issue depending on each gateway's shouldReissuePaymentOnFailed policy.
# Preset payment method
Source: https://docs.easybilling.cloud/api-reference/payment-hub/preset-payment-method
/payment.openapi.json post /api/payment-methods
Presets a payment method for a customer on the selected payment gateway and returns
the gateway-hosted setup page URL.
The request body is polymorphic and is selected by paymentGatewayType.
# Refresh refund status
Source: https://docs.easybilling.cloud/api-reference/payment-hub/refresh-refund-status
/payment.openapi.json post /api/refund/{refundRequestId}/status
# Refresh Transaction Status
Source: https://docs.easybilling.cloud/api-reference/payment-hub/refresh-transaction-status
/payment.openapi.json post /api/transactions/{transactionId}/status
# Preset payment method
Source: https://docs.easybilling.cloud/api-reference/payment-method/preset-payment-method
/billing.openapi.json post /api/payment-methods
Set up a payment method for a customer on the selected payment gateway and returns the gateway-hosted setup page URL.
The request body is polymorphic and is selected by paymentGatewayType.
# Get Credit Schedule by Account
Source: https://docs.easybilling.cloud/api-reference/prepaid-credits/get-credit-schedule-by-account
/billing.openapi.json get /api/credit-schedules/by-account
# Ingest usage events
Source: https://docs.easybilling.cloud/api-reference/usage-event/ingest-usage-events
/billing.openapi.json post /api/usage-events
support atomic operation: all or nothing
max number of usage events: 50 per request
# Who is Easybilling?
Source: https://docs.easybilling.cloud/index
EasyBilling is a global all-in-one billing and payments platform purpose-built for AI and AI Agent companies, focused on solving the most complex and mission-critical monetization infrastructure challenges in global expansion.
Benchmarked against Metronome — the billing platform powering global AI companies like OpenAI — EasyBilling serves foundation model providers, AI infrastructure companies, AI applications, and Agent businesses with an end-to-end solution covering flexible pricing, real-time usage-based billing, invoicing, cross-border payments, and tax compliance. We help companies build a complete global monetization stack at the lowest possible cost, supporting everything from simple subscriptions to highly complex usage-based pricing models.
EasyBilling is more than just a billing + payment tool — it is the operating system for global monetization of AI businesses.
## Company History
Easybilling is founded in July 2025. Driven by the founding team’s deep insight into the explosive growth of generative AI and the critical window for AI companies to expand globally.
Through long-term collaboration and conversations with foundation model teams, AI application developers, and AI infrastructure companies, we discovered that:
**Flexible pricing, subscriptions and real-time usage-based billing, cross-border payments, and tax compliance have become some of the biggest systemic bottlenecks in AI commercialization.**
Traditional subscription billing systems cannot support complex usage models, while building in-house is costly, slow to deploy, and expensive to maintain — significantly slowing down time to monetization.
As a result, the founding team came together to build EasyBilling — a global, AI-native billing and payments infrastructure platform designed for modern AI business models, delivering truly end-to-end solutions for AI companies going global.
## Our Mission
Accelerating global expansion for generative AI companies and empowering intelligent transformation across industries.
By providing a standardized, AI-native global billing platform built for modern AI business models, EasyBilling enables companies to monetize globally quickly, securely, and compliantly — without building complex systems in-house — so they can focus on product innovation and market expansion.
## Key Competitive Advantages
EasyBilling’s key competitive advantages include:
Designed for the global expansion of generative AI companies, EasyBilling provides an intelligent billing platform with native support for complex usage-based pricing, deeply integrated with payments and tax capabilities to deliver a true end-to-end monetization loop.
##### Core capabilities include:
* Flexible and composable multi-dimensional pricing models (subscription, usage-based, hybrid, and prepaid).
* Real-time, high-throughput usage metering and billing.
* Automated billing and invoicing management.
* Intelligent payment routing and orchestration across multiple gateways.
* Multi-country tax calculation and cross-border compliance support.
Through a unified platform, we help companies enter global markets at lower cost and higher efficiency, driving sustainable and scalable revenue growth.
## Ecosystem & Industry Partnerships
EasyBilling actively integrates into both domestic and global AI ecosystems, building deep partnerships with cloud service providers, compute platforms, and innovation incubators to continuously expand our product capabilities and market connections.
* Member of the AWS Partner Network (APN)
EasyBilling became an AWS Partner and launched simultaneously on both China and global AWS Marketplace seller platforms in December, serving as a billing and payment ecosystem tool for AI businesses on AWS and supporting developers and companies expanding globally.
* Member of the NVIDIA Inception Program
By actively participating in NVIDIA’s global AI startup ecosystem, EasyBilling gains access to technical resources, marketing programs, and industry partnerships, accelerating both product development and international market expansion.
* Supercomputing Internet Ecosystem Partner
Officially listed on the AI ecosystem marketplace of a national-level computing infrastructure platform, EasyBilling provides standardized billing and monetization capabilities for companies offering model training, inference, and compute services.
## Awards & Industry Recognition
EasyBilling has received strong recognition across multiple prestigious innovation and entrepreneurship competitions both in China and internationally, demonstrating the combined strength of its technology, business model, and industry impact.
—1st Prize, AI Track
*The only AI track First Prize winner in 2025*
These honors, awarded by government agencies, universities, industrial parks, and international innovation platforms, strongly validate EasyBilling’s technological leadership and market potential in AI monetization infrastructure.
# Who should use EasyBilling?
Source: https://docs.easybilling.cloud/index-copied-1
## Foundation Model & AI Infrastructure Companies
**Who It’s For**\
Teams that provide model training, inference services, compute resources, or AI APIs.
**Common Requirements**
* Support multi-dimensional usage-based billing, including tokens, API calls, and GPU/compute time.
* Multi-currency pricing and multi-region tax compliance.
* Quickly connect to global payment networks to improve overseas payment success rates.
* Reduce billing system development costs and accelerate time to monetization.
**Markets Covered**\
Covering major AI application markets including China, North America, Europe, Southeast Asia, and the Middle East.
## AI Applications & Agent Companies
**Who It’s For**\
AI tool and agent startups targeting global B2B and B2C markets with rapid product iteration.
**Common Requirements**
* Flexible billing based on conversation count, task volume, API calls, and other usage metrics.
* Support seamless switching between subscription, usage-based, and hybrid billing models.
* Reduce the complexity of payment integration and financial operations.
* Be ready for future agent-driven transactions and closed-loop autonomous payments.
## AI Hardware & Global Expansion Companies (Expanding)
As our platform capabilities continue to grow, EasyBilling is expanding its services to support more global expansion scenarios, including:\
Electric vehicles and charging networks, IoT devices, telecommunications services, fintech, energy, and industrial internet sectors.\
Providing unified billing, payment, and compliance infrastructure for companies expanding into international markets.
## In Summary
If you’re an AI company looking to scale globally and monetize at scale, EasyBilling is your monetization infrastructure.
# Key Challenges for AI Company Expanding Globally
Source: https://docs.easybilling.cloud/index-copied-2
As AI and Agent applications accelerate into global markets, business models and technical architectures are becoming increasingly complex, and companies are widely facing the following key challenges in monetization and compliance:
## Highly complex usage-based and subscription billing models
AI and Agent services often involve multiple billing dimensions at the same time, including subscriptions, token consumption, API calls, and compute time.\
Many companies struggle to convert complex usage data into billable data in real time and with high accuracy, lacking flexible, automated, and scalable billing infrastructure — which severely limits monetization efficiency.
## High Barriers to Global Tax and Compliance
Cross-border operations must handle multi-currency settlement, varying VAT, GST, and sales tax rules across countries and regions, as well as constantly evolving regulatory requirements.\
Lack of unified tax and compliance capabilities often leads to complex invoicing processes, higher compliance risks, and even delays in international market expansion.
## High Cost and Long Timelines for Building Billing Systems In-House
From usage data collection and pricing engines to billing systems and integrations with payments and tax services, building a complete billing stack in-house requires significant engineering investment and long-term maintenance costs.\
This not only puts significant financial pressure on teams, but also diverts focus away from core product innovation and slows down international expansion.
## Limited Scalability of Traditional Billing Systems
Traditional subscription-based billing systems struggle to support real-time metering, multi-dimensional pricing, and complex plan configurations required by AI use cases.\
When business models and customer requirements evolve rapidly, frequent custom development is often required, resulting in limited flexibility and scalability.
## Highly Fragmented Payment and Revenue Systems
Companies often need to integrate with multiple payment gateways, tax platforms, and ERP or financial systems at the same time. Without unified orchestration and automated reconciliation,\
this leads to fragmented data, complex reconciliation, and difficulties in revenue recognition, ultimately impacting overall financial and operational efficiency.
# Platform Capabilities
Source: https://docs.easybilling.cloud/index-copied-3
## Customer Management
Centralize customer account information for billing and payments, support multiple accounts and multiple subscriptions, and provide full visibility into the customer lifecycle — laying the foundation for refined operations and revenue management.
## Pricing & Plan Management
Built-in support for mainstream billing models including subscriptions, usage-based pricing, tiered pricing, bundled plans, minimum commitments, and prepaid credits — all configurable visually and freely composable — enabling companies to quickly launch complex business models and support diverse pricing needs for token- and API-based services.
## Usage & Metering
Provides high-performance and scalable metering and usage processing, supporting multi-dimensional usage collection, real-time aggregation, and rule-based transformations to efficiently convert raw business events into billable data — enabling true real-time and near real-time usage-based billing.
## Invoicing & Billing
Automatically generate bills and invoices based on pricing plans and actual usage, with support for billing cycles, invoice splitting and consolidation, and real-time unbilled revenue preview — helping companies gain early visibility into revenue and improve financial control.
## Payment Orchestration & Routing
Seamlessly integrate with leading domestic and global payment gateways including WeChat Pay, Alipay, Stripe, and PayerMax, with support for intelligent payment routing and retry strategies to significantly improve global payment success rates and reduce transaction costs.
## Tax & Compliance
Integrate with leading global tax platforms such as Avalara, Stripe Tax, and TaxJar to automate VAT, sales tax, and GST calculation and filing support across multiple countries and regions — helping companies reduce cross-border compliance risks and expand into global markets with confidence.
# AI Pricing Models
Source: https://docs.easybilling.cloud/index-copied-4
Different business stages and business models require different billing approaches. EasyBilling supports a wide range of mainstream billing models, enabling companies to flexibly match their product offerings with customer payment preferences.
## **Subscription-Based Pricing**
##### **Definition**
Charge a fixed fee on a recurring billing cycle (such as monthly or annually), independent of actual usage, making it suitable for products where access to features is the primary value.
* Basic Plan: \$10/per month or \$100/per year
* Premium Plan: \$30/per month or \$300/per year
##### **Key Features**
* Stable revenue with highly predictable cash flow.
* Clear billing structure that is easy for customers to understand and accept.
* Suitable for standardized products and long-term contract models.
##### **Typical Use Cases**
* Platform-based products that require continuous access to core features.
* Usage intensity is relatively stable, and businesses prefer predictable budgeting.
* Enterprise software and core SaaS feature subscriptions.
##### **Target Customer Types**
Medium and large enterprises that prefer a fixed cost structure and seek long-term, stable partnerships.
##### **Complexities in Actual Billing**
Although subscription billing may seem straightforward, there are still various complex rules in real-world business scenarios that require system support.
* Plan Upgrades and Downgrades: Pricing and settlement rules for plan changes mid-cycle.
* Proration for Incomplete Billing Cycles: Pro-rated billing for customers upgrading or changing plans mid-cycle.
* Cancellation and Refunds: Refund policies and financial reconciliation for early subscription terminations.
* Discounts and Promotions: Different discount rates applied based on customer or billing cycle.
* Contract Pricing and Custom Quotes: Exclusive pricing and contract terms management for key customers.
Relying on manual processing for these rules not only leads to inefficiency but also increases the risk of billing disputes and financial discrepancies.
## **Hybrid Pricing**
##### **Definition**
A certain amount of usage (such as credits, tokens, or API calls) is included in the base subscription fee. Once the included quota is exceeded, additional usage can be charged on a pay-as-you-go basis or covered by prepaid packages.
This model ensures stable recurring subscription revenue while also capturing incremental revenue from business growth.
* Basic Plan: \$100/month (includes 1,000 credits)
* Premium Plan: \$300/month (includes 5,000 credits)
* Top-up: \$100 for 1,000 credits; \$200 for 2,500 credits
##### **Key Features**
* Provides stable subscription revenue with potential for usage-based growth.
* Supports a combination of tiered plans, minimum spend, overage billing, and top-up packages.
* Aligns with the real business models of enterprise AI and API services.
##### **Typical Use Cases**
* Basic platform features billed via subscription, while advanced capabilities are billed based on usage.
* AI platform services with a combined model of token/API usage.
* Products and platforms with a wide range of customer scales and highly varied usage patterns.
##### **Target Customer Types**
B2B product teams and platform-based companies that need both stable long-term customers and the ability to support high-usage, fast-growing clients.
##### **Complexities in Actual Billing**
While hybrid billing increases business flexibility, it also raises higher demands on the billing system:
* Plan Upgrades and Downgrades: When upgrading or downgrading, both the consumption of included usage and remaining balance must be considered.
* Usage Expiry Management: Different expiry rules for subscription and top-up credits.
* Cancellation and Refund Logic: How to handle remaining credits when canceling a subscription and whether pro-rated refunds are supported.
* Complex Usage Pricing Models: Does the system support tiered pricing, volume discounts, or multi-dimensional metrics?
**Without automated billing capabilities, businesses are prone to reconciliation challenges and billing disputes with customers.**
## **Currency-Based Prepayment**
##### **Definition**
Customers prepay to their accounts to obtain a balance equivalent to the deposit amount. The system deducts the account balance in real-time or near-real-time based on actual usage, according to the unit price.
Common measurement dimensions include token quantity, API calls, compute time, task count, bandwidth usage, etc., and are suitable for high-frequency, quantifiable resource consumption services.
* Deposit Amount: Deposit \$100 to get a \$100 balance; deposit \$200 to get a \$200 balance.
* Usage Charges: \$0.5 per 1M tokens, automatically deducted from the balance based on actual consumption.
##### **Key Features**
* Prepaid system reduces bad debt and collection risks.
* Scalable costs that align with business growth, offering flexible usage-based expansion.
* Supports high-frequency, real-time billing, naturally fitting AI and API services.
##### **Typical Use Cases**
* Token consumption billing for large model ToB clients
* Compute resource consumption for AI infrastructure and compute platforms
* Resource-based services such as data processing, video transcoding, and bulk task execution
##### **Target Customer Types**
Enterprise-level service providers who convert service usage into direct cash consumption and prefer to collect payment upfront, thus reducing financial and credit risks.
##### **Complexities in Actual Billing**
While prepaid models offer clear advantages in cash flow and risk control, there are still several key challenges in system implementation:
* Balance Expiry Management: Should the deposit be permanently valid, or should expiration and reset rules be applied?
* Low Balance and Service Interruption: Should services automatically stop, be throttled, or prompt users to top up when the balance is insufficient?
* Overage Handling: Should overdrawing be allowed, or should the system switch to a postpaid billing model?
* Real-time Charging and Delayed Reconciliation: How to ensure accurate charges and billing consistency under high-concurrency usage?
* Financial Entry Rules for Deposits and Consumption: Revenue recognition and deferred revenue processing logic.
Without a mature billing system, these issues can lead to significant financial risks and customer disputes.
## **Unit-Based Prepayment Pricing**
##### **Definition**
Customers prepay to receive a certain number of usage credits (Credits / Units). The system converts service consumption into credits according to usage rules and automatically deducts the balance based on actual consumption.
This model maps various types of services into a unified credit system, abstracting complex metering logic and creating a simple, intuitive pricing structure.Common measurement dimensions include token count, API calls, compute time, task count, and content generation volume.
##### **Sample**
* Top-up Packages:**\$100 for 1,000 credits; \$200 for 2,500 credits**
* Usage Charges:**3 Credits/Per Video**
- Top-up Packages: \$100 for 1,000 credits; \$200 for 2,500 credits
- Usage Charges: 3 Credits/Per Video
##### **Key Features**
* Prepay credits before usage, providing more control over cash flow
* Scalable costs that grow with business size, supporting high-frequency use cases
* Abstracts complex usage models into a unified credit system, making pricing clearer
##### **Typical Use Cases**
* AI application products billed based on functions or tasks (e.g., generation, analysis, transcription, etc.)
* AI Agents billed based on task execution, tool usage, or workflow completion
* Products that bundle multiple capabilities but wish to maintain a unified pricing unit for external communication
##### **Target Customer Types**
AI product and platform companies that wish to convert different service capabilities into a credit system for sale, while using a prepaid model to reduce bad debt risks and enhance cash flow stability.
##### **Complexities in Actual Billing**
Although the credit system may seem simple, there are various key rules that need system support for scaled operations:
* Credit Expiry Management: Should credits be permanently valid, or should expiration dates be set for each batch?
* Multi-batch Credit Consumption Order: Strategies such as "first to expire, first to consume" or "first credited, first consumed."
* Bonus Credits and Promotional Activities: Rules for distinguishing and redeeming marketing credits versus paid credits.
* Refunds and Cancellations: How to handle returning used and unused credits upon refunds or cancellations.
* Complex Usage Conversion Rules: Different services may have different credit consumption rates.
* Multi-currency Recharge and Credit Pricing Linkage: Credit conversion systems under various regional pricing strategies.
**Without a unified billing engine and account system, these issues can lead to financial and customer experience challenges.**
## **Usage-Based Pricing / Pay-As-You-Go**
##### **Definition**
Charges are based on the customer’s actual usage, with costs directly tied to resource consumption.
Common measurement dimensions include token count, API calls, compute time, task volume, bandwidth usage, etc. Billing is typically aggregated and settled at the end of each billing period.
* Unit Price: \$0.5 per 1M tokens
* Invoice: invoice at the end of month based on usage tokens
##### **Key Features**
* True pay-as-you-go pricing with strong alignment between value and cost
* No upfront commitment required, lowering the barrier to adoption
* Naturally scales with business growth, supporting high-growth workloads
##### **Typical Use Cases**
* AI inference and model invocation services with highly variable usage
* Data and compute platforms billed by compute, bandwidth, or task volume
* Low-friction API products targeting startups and SMB customers
##### **Target Customer Types**
Growth-stage customers who are highly cost-sensitive, prefer on-demand scaling, and seek flexible usage with predictable budgets.
##### **Complexities in Actual Billing**
At scale, usage-based billing places higher demands on metering, pricing, and settlement systems:
* Multi-Currency Pricing and Settlement: Different regions use different currencies and pricing models, requiring unified conversion and reconciliation
* Price Change Effective Rules: How to correctly rate usage across different time periods when prices change mid-cycle
* Advanced Pricing Model Support:
* Tiered pricing (lower unit price at higher volumes)
* Volume pricing (single unit price per usage tier)
* Price caps, minimum spend, and hybrid rule combinations
* Real-Time Metering with Delayed Posting: Ensuring billing accuracy and financial consistency under high concurrency
* Invoice Transparency: Clearly presenting usage details and cost breakdowns to reduce billing disputes
Without a professional billing system, companies often rely on heavy manual reconciliation, leading to high operational costs and increased financial risk.
## **How does EasyBilling support these models?**
EasyBilling natively supports subscription billing, usage-based billing, and hybrid models, all of which can be flexibly combined.
* Supports multi-dimensional metering metrics such as tokens, API calls, usage duration, number of devices, and more
* Supports tiered pricing, minimum spend, prepaid balances, and credit limits
* Deeply integrated with billing, payments, and tax systems to enable end-to-end automated monetization
This allows businesses to launch global pricing and monetization models quickly, without building complex billing systems in-house.
# Benefits of Payment Routing
Source: https://docs.easybilling.cloud/index-copied-5
Through unified payment orchestration and intelligent routing, EasyBilling helps companies collect payments globally at lower cost and with higher success rates, significantly improving international monetization efficiency.
## Faster integration with lower engineering costs
With standardized APIs and a modular payment routing architecture, a single integration connects you to multiple payment gateways — shortening payment onboarding from 1–2 months to just 1–2 weeks, significantly reducing engineering effort and integration complexity so your team can focus on core product development.
## More competitive processing rates with continuously lower payment costs
By aggregating transaction volume across the platform and leveraging unified pricing negotiations, EasyBilling secures better rates with the same payment gateways — helping companies continuously optimize their overall payment cost structure without adding operational complexity.
## Broader global coverage, easier market expansion
Unified access to mainstream payment methods and localized acquiring channels across regions enables coverage in more countries and markets — allowing companies to enter new markets quickly without repeatedly integrating with local PSPs or complex settlement systems.
## More stable and secure, with stronger business continuity
With multi-PSP parallel routing and automatic failover, transactions are rerouted automatically when a single channel is restricted, blocked by risk controls, or experiences outages — effectively reducing the risk of payment disruptions caused by account suspensions, throttling, or system failures, and ensuring revenue stability.
# EasyBilling Integration Guide
Source: https://docs.easybilling.cloud/integration-guide
This document is for new merchants. It provides a structured overview of all key points required to integrate with the EasyBilling billing platform, including environment setup, API workflows, field mapping notes, and common pitfalls.
## 1. Overview
EasyBilling is the subscription billing platform used by this system. It is responsible for:
* Managing customer accounts and subscription contracts
* Supporting usage-based billing
* Processing actual payments through Stripe Connect
* Providing invoice generation and a customer self-service portal
**Sandbox Base URL:**
```text theme={null}
https://sbx.api.easybilling.cloud/billing
```
**Production Base URL:**
```text theme={null}
https://app.api.easybilling.cloud/billing
```
All requests must include these headers:
* `Authorization: Bearer `
* `trace-id: `
## 2. API Key
There are two ways to create an API Key in EasyBilling:
### Option 1: From System Configuration
1. Navigate to **System Configuration** → **Users & API Keys**.
2. Locate your user and click the **Edit** (pencil) icon.
3. Click **New API Key**.
4. Enter a name for the API Key.
5. Save to generate the API Key.
### Option 2: From Your Profile
1. Click your user avatar in the bottom-left corner.
2. Select **Profile**.
3. Click **New API Key**.
4. Enter a name for the API Key .
5. Save to generate the API Key.
### Copying Your API Key
After the API Key is created:
1. Locate the newly generated API Key in the list.
2. Click the **Copy** button next to the API Key.
3. Store the API Key securely, as it will be used to authenticate API requests.
## 3. Environment Variable Configuration
Required:
| Variable | Description |
| --------------------------------- | ------------------------------------------------------------------- |
| `EASYBILLING_BASE_URL` | API base URL (sandbox: `https://sbx.api.easybilling.cloud/billing`) |
| `EASYBILLING_API_KEY` | API key obtained from EasyBilling in step 2 |
| `EASYBILLING_DEFAULT_PLAN_ID` | Default (free/starter) plan UUID |
| `EASYBILLING_UPGRADE_PLAN_ID` | Paid upgrade plan UUID |
| `EASYBILLING_USAGE_SCHEMA_NAME` | Usage event schema name. Must be defined in EasyBilling first |
| `EASYBILLING_PAYMENT_SUCCESS_URL` | Redirect URL after Stripe payment success |
| `EASYBILLING_PAYMENT_CANCEL_URL` | Redirect URL after Stripe payment cancellation |
| `EASYBILLING_INVOICE_TEMPLATE_ID` | Invoice PDF template UUID |
## 4. Account Creation
When a user registers, create the corresponding account in EasyBilling.
**Endpoint:** `POST /api/accounts`
**Request body:**
```json theme={null}
{
"name": "User Name",
"number": "SM-ACC-00000001",
"email": "user@example.com",
"addressLine1": "123 Main St",
"addressLine2": "",
"country": "US",
"state": "CA",
"city": "San Francisco",
"postalCode": "94102"
}
```
**Key notes:**
* The account number field name is `number`, **not** `accountNumber`.
* The account number should use your own system's customer account number.
* If you do not pass an account number, EasyBilling will generate its own.
* If you do not use your own customer account number, you must store EasyBilling `number` in your user table. All follow-up EasyBilling operations depend on this field.
* Always query the account by accountNumber before creating one. If the account already exists, reuse its accountNumber and proceed to create the contract. Only create a new account when no existing account is found. This prevents duplicate accounts and avoids integration errors when a previous request successfully created the account but failed to create the contract.
## 5. Contract Creation
After registration (or on demand), create a contract for the default plan.
**Endpoint:** `POST /api/contract-actions`
**Request body:**
```json theme={null}
{
"accountNumber": "SM-ACC-00000001",
"actions": [
{
"type": "create-contract-with-plan",
"createContractWithPlan": [
{
"planId": "",
"effectiveDate": "2026-04-13",
"currency": ["USD"]
}
],
"immediatelyPay": true,
"paymentInfo": {
"paymentGatewayType": "stripe-connect",
"paymentSuccessUrl": "",
"paymentCancelUrl": ""
}
}
]
}
```
**Key notes:**
* `Idempotency-Key: `is required for this http request header.
* `effectiveDate` must be **today** in `YYYY-MM-DD` format. Do not use a fixed date such as the first day of a month.
* Set `expirationDate` as needed. For a one-year contract, set one year later (for example, `2027-04-13`).
* `expirationDate` means the contract expires at 00:00 on that date, so that date is not included.
* `createContractWithPlan` must be an array.
**Response (must be persisted):**
```json theme={null}
{
"contractActionNumber": "CA-000001",
"contractInfo": {
"id": "contract-uuid",
"contractNumber": "CT-000001",
"status": "active"
},
"paymentResults": []
}
```
Persist `contractInfo.id` to your user table as `easyBillingContractId`. This field is required for both upgrade and cancellation.
## 6. Plan Upgrade
Switch a user from the current plan to a paid plan.
**Endpoint:** `POST /api/contract-actions`
**Request body:**
```json theme={null}
{
"accountNumber": "SM-ACC-00000001",
"actions": [
{
"type": "switch-plan",
"switchPlan": {
"contractId": "",
"planId": "",
"effectiveDate": "2026-04-13",
"currency": ["USD"]
},
"externalReferenceId": "Order-123-upgrade",
"immediatelyPay": true,
"paymentInfo": {
"paymentGatewayType": "stripe-connect",
"paymentSuccessUrl": "",
"paymentCancelUrl": ""
}
}
]
}
```
**Response handling:**
```json theme={null}
{
"contractActionNumber": "CA-000002",
"paymentResults": [
{
"sessionUrl": "https://checkout.stripe.com/..."
}
]
}
```
**Key notes:**
* `Idempotency-Key: `is required for this http request header.
* Extract the Stripe Checkout URL from `paymentResults[].sessionUrl` and return it to the frontend.
* If contract creation failed during registration and `contractId` is empty, please refer to **Step 5: Contract Creation** to create a contract with the default plan first and then call `switch-plan`. Then extract `sessionUrl` from the response.
* Use `externalReferenceId` for later payment succeeded reference if needed.
## 7. Contract Cancellation
Cancel the active contract immediately.
**Endpoint:** `POST /api/contract-actions`
**Request body:**
```json theme={null}
{
"accountNumber": "SM-ACC-00000001",
"actions": [
{
"type": "cancel",
"cancel": {
"contractId": "",
"effectiveOption": "immediately"
}
}
]
}
```
**Key notes:**
* `Idempotency-Key: `is required for this http request header.
* If today's usage has already been uploaded, the earliest possible cancellation is tomorrow.
* EasyBilling automatically handles refunds and tax reversal. No separate backend calculation is required.
* After cancellation succeeds, update user `subscriptionStatus` to `CANCELED` in your own system.
## 8. Usage Event Reporting
Whenever a user completes a billable action (for example, one AI analysis), report usage to EasyBilling.
**Endpoint:** `POST /api/usage-events`
**Important:** The request body must be an array.
```json theme={null}
[
{
"eventId": "uuid-v4",
"schemaName": "speech-master",
"eventTime": "2026-04-13T08:00:00.000Z",
"accountNumber": "SM-ACC-00000001",
"attributes": [
{ "name": "quantity", "value": "1" }
]
}
]
```
**Key notes:**
* `Idempotency-Key: `is required for this http request header.
* `eventTime` must be ISO 8601 UTC format.
* Use UUID v4 for `eventId` to ensure idempotency.
* Asynchronous reporting is recommended. On failure, log the error in your business table and do not block the main flow.
* `attributes` must match the usage event schema definition. The sample above is only an example.
## 9. Invoice List Query
**Endpoint:** `POST /api/data-query`
**Request body:**
```json theme={null}
{
"queryObject": "invoice",
"filters": [
{
"fieldName": "accountNumber",
"fieldValues": [
"SM-ACC-00000001"
]
}
]
}
```
**Response field mapping (important):**
| EasyBilling Field | Meaning | Suggested Mapping |
| ----------------- | ---------------------------------- | ----------------- |
| `number` | Invoice number (e.g. `INV-000001`) | `invoiceNumber` |
| `id` | Invoice UUID | `invoiceId` |
| `date` | Invoice date | `invoiceDate` |
| `totalAmount` | Total amount (numeric) | `amount` |
| `dueDate` | Due date | `dueDate` |
| `currency` | Currency | `currency` |
## 10. Invoice PDF Generation
**Endpoint:** `POST /template-engine/api/pdf/generate`
**Request body:**
```json theme={null}
{
"name": "INV-000000325",
"objectId": "9efc7d38-0d97-4cc3-a861-fdf4613d9d75",
"objectType": "invoice",
"templateId": ""
}
```
**Notes:**
* `name` should use the invoice `number` field, i.e. `invoiceNumber`.
* `objectId` should use the invoice `id` field, i.e. `invoiceId`.
* Before calling PDF API, verify the invoice belongs to the current user account by checking the invoice list.
* The response `id` is `pdfId`. Download PDF via `GET /template-engine/api/pdf/{pdfId}`.
## 11. Customer Portal
The customer portal allows your end users to self-manage subscriptions and view invoices. Instead of navigating to EasyBilling's url, we support to embed the customer portal into your own website with iFrame.
### Step 1: Maintain your domain
You must maintain your own domain in EasyBilling's `System Configuration` → `Customer Portal Security` so that you can access EasyBilling's customer portal with your own domain.
### Step 2: Get a Short-lived Token
**Endpoint:** `POST /api/authenticate/account-auth`
```json theme={null}
{
"accountNumber": "SM-ACC-00000001"
}
```
**Response:**
```json theme={null}
{
"token": "eyJhbGciOiJSUzI1NiJ9...",
"tokenType": "Bearer",
"expiresIn(seconds)": 1800
}
```
### Step 3: Embed into your own website
Embed the iframe into your own website page, and use the token obtained above for it.
```html wrap theme={null}
```
**Important:** The portal URL contains sensitive token data. It must be returned by a backend endpoint and must not be hardcoded or persisted on frontend.
When goes to production, the source URL should be replaced with:
```html wrap theme={null}
src="https://app.easybilling.cloud/customer/portal?token="
```
## 12. Notification Configuration
EasyBilling supports webhook notifications for the following events:
| Event | Description |
| :------------------ | :---------------------------------------------------- |
| **Prepaid Credits** | Sent when your prepaid credits balance reaches **0**. |
| **Payment Success** | Sent when a payment is successfully processed. |
### Configure a Webhook Endpoint
1. Navigate to **System Configuration** → **Notifications**.
2. Locate the notification event you want to configure.
3. Click the **Edit** (pencil) icon.
4. Enter your webhook HTTP URL.
5. Click **Save**.
After the webhook URL has been saved, you can view and copy the webhook secret to verify that incoming webhook requests were sent by EasyBilling.
### Webhook Delivery & Retries
EasyBilling will attempt to deliver each webhook event to your configured endpoint.
If a delivery attempt fails (for example, due to a network error or a non-success HTTP response), EasyBilling will automatically retry the notification:
* **Retry Attempts:** 2 additional retries
* **Retry Interval:** 1 minute between each retry
**Prepaid Credits Delivery:**
```json theme={null}
{
"id": "1aba9755-d5e6-43b4-9a86-b2294e69f42d",
"type": "credit_schedule.depleted",
"createdAt": "2026-07-27T07:54:01Z",
"data": {
"object": {
"basicInfo": {
"contractId": "b492c672-890f-4fd8-aab6-ab36c72900f4",
"accountId": "f3978fb9-2d3a-43cc-a49e-7151ab6a15b8",
"accountNumber": "SM-ACC-00000001",
"contractSegmentId": "9cb1b340-7eaa-4d66-b4ae-261ab3fa9611"
},
"businessInfo": {
"CreditSchedule": {
"totalBalance": "20000.000000000",
"remainingBalance": "0.000000000",
"bucketId": "75f35768-a110-422b-9352-847ec3504a41",
"creditScheduleId": "aabe90c9-91a0-4359-882f-cd64c6aa02d5",
"validFrom": "2026-07-01",
"validTo": "2026-08-01",
"originalTotalBalance": "20000.000000000",
"uom": "Token",
"bucketType": "resource-based-credit"
}
}
}
}
}
```
**Payment Success Delivery:**
```json theme={null}
{
"id": "0e41a324-0da2-4ba4-a3e4-c5126c81a05c",
"type": "payment.succeeded",
"createdAt": "2026-07-05T11:04:02Z",
"data": {
"object": {
"basicInfo": {
"contractId": "144fc477-0c79-4908-84d8-7501a06caf73",
"accountNumber": "SM-ACC-00000001",
"accountId": "c780170e-3737-4ec7-91d3-972c660820e9"
},
"businessInfo": {
"Payment": {
"externalReferenceId": "Order-123-upgrade",
"invoiceId": "fa73013c-1bd9-421b-8fbb-bfb6bbf37343",
"paymentStatus": "succeeded",
"invoiceNumber": "INV-000000121",
"currency": "USD",
"totalAmount": "99.00"
}
}
}
}
}
```
## 13. Common Notes
| # | Issue | Correct Approach |
| - | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| 1 | `effectiveDate` set to start of month (e.g. `2026-04-01`) | Always use today's date |
| 2 | Reading `accountNumber` from account creation response | Response field is `number` |
| 3 | Treating account creation and contract creation as one step | If account creation succeeds but contract creation fails, retry contract creation separately |
| 4 | Forgetting array wrapper for usage event body | `POST /api/usage-events` body must be an array |
| 5 | Not handling token field variants | Check all 6 candidate locations in `account-auth` response |
| 6 | Generating PDF without ownership verification | Confirm `(name, objectId)` exists in current user's invoice list first |
## Quick Checklist
For new project integration, verify:
* Environment variables are configured (8 required items)
* Account creation response uses `number`, not `accountNumber`
* Contract creation uses today's `effectiveDate`
* `contractInfo.id` is persisted in user table
* Usage event body is an array
* `account-auth` token extraction supports all 6 response formats
* Portal URL containing token is returned only from backend
# Quickstart
Source: https://docs.easybilling.cloud/quickstart
Through standardized data models and a flexible billing engine, EasyBilling automatically converts complex AI usage data into billable revenue, delivering a complete closed loop from product usage to cash collection.
## Get started in few steps
### Step 1: Usage Event Schema
Configure usage event templates based on your business data format to define how the system parses the raw usage data you send. Customizable fields and attributes, such as model, request\_type, tokens, region, etc., provide the data foundation for complex pricing models.
### Step 2: Billable Metrics
Based on the usage event template, define core metrics that can be used for billing, such as:
* Total Token Consumption
* Number of Calls for a Specific Model
* Usage Aggregated by Region or Time Period
In this step, raw data is filtered, aggregated, and transformed, converting business events into standardized billing metrics.Your preview updates automatically as you edit files.
### Step 3: Billing Plan
Combine one or more charge items into a complete pricing plan, for example:
* Token-based Pricing
* Subscription Fee
* Prepayment and Minimum Commitment
And configure the billing cycle, billing date, currency, and discount strategy to match different customer contracts and product plans.
### Step 4: Customer Account
Create a separate account for each customer in the system to manage:
* Contract Lifecycle
* Usage Event
* Invoice
* Payment Method and Balance
Support enterprise-level customer hierarchies and multiple subscription structures.
### Step 5: Contract Activation
Assign the configured pricing plan to the customer account to activate the contract. Once active, the system automatically starts metering and billing according to the plan rules.
### Step 6: Usage Ingestion
Continuously send customer usage data to EasyBilling via APIs or batch interfaces in real time. Based on billing metrics and pricing rules, the system performs real-time or near real-time rating and billing, while synchronously updating usage and balance status.
### Step 7: Invoicing
The system automatically generates invoices based on billing cycles or real-time rules:
* Prepaid model: charges are deducted from the balance in real time.
* Postpaid model: invoices are generated after the billing period ends.
Supports billing details, usage visualization, and invoice generation, making it easier for customers to verify and for finance teams to reconcile.
### Step 8: Payment & Reconciliation
Automatically handle payments, refunds, and retries with integrated payment gateways, while updating payment status in real time. Billing, collection, and financial data remain consistent, providing a reliable foundation for revenue recognition and reconciliation.
## One system that integrates billing, payments, and compliance
Through the above process, EasyBilling helps businesses achieve:\
**Usage Collection → Pricing & Billing → Invoice Generation → Global Payments → Financial Reconciliation** A fully automated closed-loop.\
Enable AI teams to have global commercialization capabilities without the need to build complex systems in-house.
# Webhook
Source: https://docs.easybilling.cloud/webhook
## 1. Overview
When business state changes occur, EasyBilling sends webhook notifications as HTTP `POST` requests with a JSON body.
### 1.1 Supported Event Types
| Event Type (`type`) | Description |
| ------------------------------------- | ------------------------------------------------------------------ |
| `payment.succeeded` | Invoice payment succeeds (auto-charge or manual payment) |
| `credit_schedule.depleted` | Prepaid credits are depleted (balance reaches zero) |
| `invoice.posted`/`credit_memo.posted` | Invoice or credit memo is posted |
| `contract.created` | New customer contract becomes effective |
| `contract.updated` | Contract change takes effect: update/switch-plan/early-renew/renew |
| `contract.cancelled` | Contract is cancelled/terminated |
### 1.2 Standard Payload Structure
All webhook events are wrapped in a common envelope:
* `id`: Globally unique event ID (`UUID v4`)
* `type`: Event type
* `createdAt`: Event creation timestamp
* `data.object`: Event business payload
The `id` remains unchanged across retries and should be used as your idempotency key for deduplication.
#### Example: `payment.succeeded`
```json theme={null}
{
"id": "0e41a324-0da2-4ba4-a3e4-c5126c81a05c",
"type": "payment.succeeded",
"createdAt": "2026-07-05T11:04:02Z",
"data": {
"object": {
"basicInfo": {
"contractId": "144fc477-0c79-4908-84d8-7501a06caf73",
"accountNumber": "SM-ACC-00000001",
"accountId": "c780170e-3737-4ec7-91d3-972c660820e9"
},
"businessInfo": {
"Payment": {
"externalReferenceId": "Order-123-upgrade",
"invoiceId": "fa73013c-1bd9-421b-8fbb-bfb6bbf37343",
"paymentStatus": "succeeded",
"invoiceNumber": "INV-000000121",
"currency": "USD",
"totalAmount": "99.00"
}
}
}
}
}
```
#### Example: `credit_schedule.depleted`
```json theme={null}
{
"id": "1aba9755-d5e6-43b4-9a86-b2294e69f42d",
"type": "credit_schedule.depleted",
"createdAt": "2026-07-27T07:54:01Z",
"data": {
"object": {
"basicInfo": {
"contractId": "b492c672-890f-4fd8-aab6-ab36c72900f4",
"accountId": "f3978fb9-2d3a-43cc-a49e-7151ab6a15b8",
"accountNumber": "SM-ACC-00000001",
"contractSegmentId": "9cb1b340-7eaa-4d66-b4ae-261ab3fa9611"
},
"businessInfo": {
"CreditSchedule": {
"totalBalance": "20000.000000000",
"remainingBalance": "0.000000000",
"bucketId": "75f35768-a110-422b-9352-847ec3504a41",
"creditScheduleId": "aabe90c9-91a0-4359-882f-cd64c6aa02d5",
"validFrom": "2026-07-01",
"validTo": "2026-08-01",
"originalTotalBalance": "20000.000000000",
"uom": "Token",
"bucketType": "resource-based-credit"
}
}
}
}
}
```
#### Example: `invoice.posted, credit_memo.posted`
```json theme={null}
{
"id": "771e8400-f29b-41d4-b716-556655441111",
"type": "invoice.posted",
"createdAt": "2026-08-03T11:00:00Z",
"data": {
"object": {
"basicInfo": {
"accountId": "f3978fb9-2d3a-43cc-a49e-7151ab6a15b8",
"accountNumber": "SM-ACC-00000001",
"documentId": "fa73013c-1bd9-421b-8fbb-bfb6bbf37343",
"documentNumber": "INV-000000121"
},
"businessInfo": {
"billingDocument": {
"amount": "299.00",
"totalAmount": "316.94",
"discountAmount": "0.00",
"taxAmount": "17.94",
"currency": "USD",
"postStatus": "succeeded"
}
}
}
}
}
```
#### Example: `contract.created, contract.updated, contract.cancelled`
```json theme={null}
{
"id": "882e8400-a29b-41d4-c716-666655442222",
"type": "contract.created",
"createdAt": "2026-08-03T11:15:00Z",
"data": {
"object": {
"basicInfo": {
"accountId": "f3978fb9-2d3a-43cc-a49e-7151ab6a15b8",
"accountNumber": "SM-ACC-00000001",
"contractId": "b492c672-890f-4fd8-aab6-ab36c72900f4"
},
"businessInfo": {
"ContractAction": {
"contractActionType": "create-contract-with-plan",
"contractInfo": {
"contractNumber": "CT-0000000085",
"effectiveDate": "2026-08-01",
"expirationDate": "2027-07-31",
"status": "active",
"paymentGatewayType": "stripe-connect",
"contractSegments": [
{
"id": "9cb1b340-7eaa-4d66-b4ae-261ab3fa9611",
"effectiveDate": "2026-08-01",
"expirationDate": "2027-07-31",
"planId": "d3e40eb2-c5d4-4141-b9d2-c8ebdad3c542"
}
]
}
}
}
}
}
}
```
## 2. Signature Verification (HMAC-SHA256)
To prevent tampering and spoofing, each webhook request includes this header:
* Header name: `X-Webhook-Signature`
* Header format: `t=,v1=`
* String to sign: `timestamp + "." + rawBody`
* Algorithm: `HMAC-SHA256` with your webhook secret
### Critical Validation Rule
Always compute the signature using the **raw HTTP request body bytes**. Do not re-serialize parsed JSON before verification, or signature checks may fail due to formatting/key-order differences.
### Python Example
```python theme={null}
import hmac
import hashlib
import time
def verify_webhook_signature(raw_body: str, signature_header: str, secret: str, tolerance_seconds=300) -> bool:
if not signature_header or not secret:
return False
parts = dict(part.split('=', 1) for part in signature_header.split(','))
timestamp_str = parts.get('t')
provided_sig = parts.get('v1')
if not timestamp_str or not provided_sig:
return False
try:
timestamp = int(timestamp_str)
except ValueError:
return False
# 1) Replay protection via timestamp tolerance window
if abs(time.time() - timestamp) > tolerance_seconds:
return False
# 2) Recompute HMAC-SHA256
to_sign = f"{timestamp}.{raw_body}".encode("utf-8")
expected_sig = hmac.new(secret.encode("utf-8"), to_sign, hashlib.sha256).hexdigest()
# 3) Constant-time comparison to avoid timing attacks
return hmac.compare_digest(expected_sig, provided_sig)
```
## 3. Retry Policy and Time Window
### Timestamp Tolerance
* Recommended tolerance: `300` seconds (5 minutes)
* If request timestamp is outside the tolerance window, reject the request
* This helps prevent replay attacks
### Delivery Retry Policy
EasyBilling automatically retries webhook delivery when:
* Receiver returns non-2xx HTTP status
* Network timeout/failure occurs
Defaults and behavior:
* Default max retries: `3`
* Retry intervals: 1 minute
* Retry with the same webhook id
* If all retries fail, event status is marked as `FAILED`
## 5. Receiver Best Practices
1. Return `2xx` quickly after minimal validation, then process asynchronously.
2. Use webhook `id` for deduplication across retries.
3. Verify signature before any business processing.
4. Enforce timestamp tolerance (recommended: 5 minutes).
5. Log key metadata (`id`, `type`, `createdAt`, delivery timestamp, verification result).
6. Implement safe retry handling in your own downstream processing.
## 6. Go-Live Checklist
* [ ] Webhook endpoint is reachable from Billing
* [ ] Signature verification is implemented with raw body
* [ ] Replay protection window is enabled
* [ ] Event deduplication by webhook `id` is implemented
* [ ] Non-2xx handling and observability are in place
* [ ] Sandbox event triggering is tested end-to-end