Billing Account

Manage account billing, balance tracking, and credit usage. Billing accounts hold the prepaid credit balance that is consumed by chargeable operations such as calls, messages, and number purchases.

API Reference: Billing endpoints

Overview

Note

AI Context

  • Complexity: Medium

  • Cost: Free (reading billing data incurs no charges; adding balance is an admin-only operation)

  • Async: No. All billing account operations are synchronous and return immediately. Balance changes from service usage (calls, SMS) happen asynchronously as services are consumed.

VoIPBIN’s Billing Account API provides balance management, token tracking, and usage monitoring for your account. The billing system uses a State+Ledger architecture where the account holds the live state (current balance and tokens) and the billings table records every transaction as an immutable ledger entry with signed deltas and post-transaction snapshots.

With the Billing Account API you can:

  • Check current credit balance and token balance

  • View billing history as a ledger of transactions

  • Add funds to your account (admin only)

  • View rate information for different service types

  • Monitor usage and charges

  • Track all transactions via the immutable billing ledger

How Billing Works

VoIPBIN uses a hybrid billing model with two cost mechanisms: token balance and credit balance.

Each plan tier includes a monthly allocation of tokens that cover certain service types (virtual number calls, TTS, and recording). When tokens are exhausted, usage overflows to the credit balance. PSTN calls, SMS, email, and number purchases are always charged to the credit balance.

All monetary values are stored as int64 micros (1 USD = 1,000,000 micros) to prevent floating-point rounding errors.

Note

AI Implementation Hint

The balance_credit field is in micros (int64), not dollars. To convert: divide by 1,000,000 for USD (e.g., 69772630 micros = $69.77). When displaying balance to users, always convert from micros to the currency unit. When estimating costs, multiply the rate in micros by the number of billable units.

Billing Architecture

+-----------------------------------------------------------------------+
|                     State + Ledger Architecture                       |
+-----------------------------------------------------------------------+

+-------------------+     +-------------------+
|  Account (State)  |     |  Billings (Ledger)|
|  balance_token    |     |  Immutable entries |
|  balance_credit   |     |  with deltas and   |
+--------+----------+     |  snapshots         |
         |                +--------+----------+
         |                         |
         | live state              | transaction history
         v                         v
+--------+----------+     +--------+----------+
|                   |     |                   |
v                   v     v                   v
+----------+  +----------+  +----------+  +----------+  +----------+  +----------+  +----------+
| VN Calls |  |   TTS    |  |Recording |  |PSTN Calls|  |   SMS    |  |  Email   |  | Numbers  |
| 1 tok/min|  | 3 tok/min|  | 3 tok/min|  | per min  |  | per msg  |  | per msg  |  | per num  |
+----------+  +----------+  +----------+  +----------+  +----------+  +----------+  +----------+
     |             |             |             |             |              |             |
     | token first | token first | token first |             |              |             |
     | then credit | then credit | then credit | credit only | credit only  | credit only | credit only
     v             v             v             v             v              v             v
+---------+   +---------+   +---------+   +---------+   +---------+   +---------+   +---------+
| $0.001  |   |  $0.03  |   |  $0.03  |   |  $0.01  |   |  $0.01  |   |  $0.01  |   |  $5.00  |
| /minute |   | /minute |   | /minute |   | /minute |   | /message|   | /message|   | /number |
+---------+   +---------+   +---------+   +---------+   +---------+   +---------+   +---------+

Key Components

  • Account State: The billing_accounts table holds the live balance_credit (int64 micros) and balance_token (int64). This is the single source of truth for current balances.

  • Billing Ledger: The billing_billings table records every transaction as an immutable entry with signed deltas (amount_token, amount_credit) and post-transaction snapshots (balance_token_snapshot, balance_credit_snapshot).

  • Monthly Token Top-Up: Tokens are replenished monthly via a cron-driven top-up process. The top-up is recorded as a top_up transaction in the ledger.

  • Token-Eligible Services: VN calls (1 token/minute), TTS (3 tokens/minute), and recording (3 tokens/minute) consume tokens first, then overflow to credits.

  • Credit-Only Services: PSTN calls, SMS, email, and number purchases always use credits directly.

  • Free Services: Extension-to-extension calls and direct extension calls incur no charges.

Token Top-Up Process

Token replenishment happens via an automated monthly cron process:

  1. Selection: The system selects accounts where tm_next_topup <= NOW().

  2. State Update: The account’s balance_token is set to the plan’s allocation. tm_last_topup and tm_next_topup are updated.

  3. Ledger Entry: A billing record is inserted with transaction_type: top_up and reference_type: monthly_allowance, recording the positive token delta and the resulting balance snapshot.

The tm_next_topup field on the account indicates when the next top-up is scheduled.

Plan Tiers

Each billing account is assigned a plan tier that determines both resource creation limits and monthly token allocations. New accounts default to the free tier.

Monthly Token Allocations

Plan

Free

Basic

Professional

Unlimited

Tokens per month

100

1,000

10,000

unlimited

Tokens are replenished at the scheduled top-up date. The current token balance is available in the balance_token field of the account.

Resource Limits

Resource

Free

Basic

Professional

Unlimited

Extensions

5

50

500

unlimited

Agents

5

50

500

unlimited

Queues

2

10

100

unlimited

Conferences

2

10

100

unlimited

Trunks

1

5

50

unlimited

Virtual Numbers

5

50

500

unlimited

  • When a resource limit is reached, further creation of that resource type is denied.

  • Only platform admins can change a customer’s plan tier.

  • The current plan tier is returned in the plan_type field of the billing account.

Rate Structure

VoIPBIN uses per-minute billing for calls (rounded up to the next whole minute) and per-unit billing for other services.

Token Rates

Service

Token Cost

Unit

VN Calls

1 token

Per minute (ceiling-rounded)

TTS (Text-to-Speech)

3 tokens

Per minute (ceiling-rounded)

Recording

3 tokens

Per minute (ceiling-rounded)

Credit Rates (Overflow and Credit-Only)

All credit rates are stored internally as int64 micros.

Service

Rate (USD)

Rate (micros)

Unit

VN Calls (overflow)

$0.001

1,000

Per minute

PSTN Outgoing Calls

$0.01

10,000

Per minute

PSTN Incoming Calls

$0.01

10,000

Per minute

SMS

$0.01

10,000

Per message

Email

$0.01

10,000

Per message

Number Purchase

$5.00

5,000,000

Per number

Number Renewal

$5.00

5,000,000

Per number

TTS (overflow)

$0.03

30,000

Per minute

Recording (overflow)

$0.03

30,000

Per minute

Extension Calls

Free

0

No charge

How Token Consumption Works

When a token-eligible service is used (VN call, TTS, or recording):

  1. The system checks the account’s balance_token.

  2. If tokens are available, they are consumed first.

  3. If tokens are partially available, the available tokens are consumed and the remainder overflows to credits.

  4. If no tokens remain, the full cost is charged to credits.

Each transaction is recorded in the billing ledger with the token and credit amounts as signed deltas.

Rate Calculation Examples

VN Call (2 minutes 15 seconds) with tokens available:
+--------------------------------------------+
| Duration: 2 min 15 sec -> 3 minutes        |
| (ceiling-rounded to next whole minute)      |
| Token cost: 3 x 1 = 3 tokens               |
| Credit cost: 0 micros (covered by tokens)   |
| Ledger entry:                               |
|   amount_token: -3                          |
|   amount_credit: 0                          |
+--------------------------------------------+

VN Call (5 minutes) with NO tokens remaining:
+--------------------------------------------+
| Duration: 5 minutes                         |
| Token cost: 0 (exhausted)                   |
| Credit cost: 5 x 1,000 = 5,000 micros      |
| Ledger entry:                               |
|   amount_token: 0                           |
|   amount_credit: -5000                      |
+--------------------------------------------+

PSTN Outgoing Call (2 minutes 30 seconds):
+--------------------------------------------+
| Duration: 2 min 30 sec -> 3 minutes        |
| (ceiling-rounded to next whole minute)      |
| Credit cost: 3 x 10,000 = 30,000 micros    |
| Ledger entry:                               |
|   amount_token: 0                           |
|   amount_credit: -30000                     |
+--------------------------------------------+

TTS Session (1 minute 15 seconds) with tokens available:
+--------------------------------------------+
| Duration: 1 min 15 sec -> 2 minutes        |
| (ceiling-rounded to next whole minute)      |
| Token cost: 2 x 3 = 6 tokens               |
| Credit cost: 0 micros (covered by tokens)   |
| Ledger entry:                               |
|   amount_token: -6                          |
|   amount_credit: 0                          |
+--------------------------------------------+

Recording (3 minutes 45 seconds) with NO tokens remaining:
+--------------------------------------------+
| Duration: 3 min 45 sec -> 4 minutes        |
| (ceiling-rounded to next whole minute)      |
| Token cost: 0 (exhausted)                   |
| Credit cost: 4 x 30,000 = 120,000 micros   |
| Ledger entry:                               |
|   amount_token: 0                           |
|   amount_credit: -120000                    |
+--------------------------------------------+

Monthly Token Top-Up (Free plan):
+--------------------------------------------+
| Transaction type: top_up                    |
| Reference type: monthly_allowance           |
| Ledger entry:                               |
|   amount_token: +100                        |
|   amount_credit: 0                          |
|   balance_token_snapshot: 100               |
+--------------------------------------------+

Note: Rates are subject to change. Check the API for current pricing.

Managing Balance

Check and manage your account balance.

Check Balance

$ curl -X GET 'https://api.voipbin.net/v1.0/billing_accounts?token=<token>'

Response:

{
    "id": "billing-uuid-123",
    "customer_id": "customer-uuid-456",
    "plan_type": "free",
    "balance_credit": 150500000,
    "balance_token": 70,
    "tm_last_topup": "2024-01-01T00:00:00Z",
    "tm_next_topup": "2024-02-01T00:00:00Z",
    "tm_create": "2024-01-01T00:00:00Z",
    "tm_update": "2024-01-15T10:30:00Z"
}

The balance_credit is in micros (150500000 = $150.50). The balance_token is the current token count.

View Billing Ledger

$ curl -X GET 'https://api.voipbin.net/v1.0/billings?token=<token>&page_size=10'

Returns a paginated list of billing ledger entries showing all transactions (usage, top-ups, adjustments).

Add Balance (Admin Only)

$ curl -X POST 'https://api.voipbin.net/v1.0/billing_accounts/<account-id>/balance_add_force?token=<token>' \
    --header 'Content-Type: application/json' \
    --data '{
        "balance": 100.00
    }'

Note: Balance addition is restricted to users with admin permissions for security.

Balance Lifecycle

Account balance changes through specific operations. Token balances are replenished monthly via the automated top-up process.

Balance and Token Flow

+-------------------+     +-------------------+
| Add Balance       |     | Monthly Top-Up    |
| (admin only)      |     | (automated cron)  |
+--------+----------+     +--------+----------+
         |                         |
         v                         v
+-------------------+     +-------------------+
|  balance_credit   |     |  balance_token    |
|  150,500,000      |     |      100          |
+--------+----------+     +--------+----------+
         |                         |
         | PSTN calls, SMS,        | VN calls,
         | email, numbers,         | TTS, recording
         | overflow                |
         v                         v
+-------------------+     +-------------------+
|   Credit Charges  |     |  Token Usage      |
| - 30000 PSTN call |     | - 3 tokens call   |
| - 10000 SMS       |     | - 6 tokens TTS    |
| - 5000000 number  |
+--------+----------+     +--------+----------+
         |                         |
         v                         | exhausted
+-------------------+              |
|  Updated Balance  |<-------------+
|  145,460,000      |   overflow charges
+-------------------+

All transactions recorded in billing ledger
with signed deltas and balance snapshots.

Balance Monitoring

Monitor balance and token usage to avoid service interruption.

Balance Check Flow

Before Service Execution:
+--------------------------------------------+
| 1. Identify service type                   |
| 2. If token-eligible: check balance_token  |
|    - If tokens available -> proceed         |
|    - If no tokens -> check balance_credit   |
| 3. If credit-only: check balance_credit    |
|    - If balance >= cost -> proceed          |
|    - If balance < cost -> deny service      |
+--------------------------------------------+

Common Scenarios

Scenario 1: Token-Based Monthly Usage

Track token consumption via the billing ledger.

Monthly Usage (Free Plan, 100 tokens):
+--------------------------------------------+
| Week 1:                                    |
| - 10 VN calls (avg 3 min) = 30 tokens      |
| - 2 TTS sessions (avg 5 min) = 30 tokens   |
| - 5 SMS = 50,000 micros credit (credit-only)|
| balance_token: 40                          |
|                                            |
| Week 2:                                    |
| - 20 VN calls (avg 2 min) = 40 tokens      |
| balance_token: 0                           |
|                                            |
| Week 3 (tokens exhausted):                 |
| - 5 VN calls (avg 3 min) = overflow        |
|   5 x 3 x 1,000 = 15,000 micros credit    |
| - 2 SMS = credit                           |
|   2 x 10,000 = 20,000 micros credit        |
+--------------------------------------------+

Scenario 2: Mixed Token and Credit Usage

Plan for costs across token-eligible and credit-only services.

Campaign: Customer Outreach (Basic plan, 1000 tokens)
+----------------------------------------------+
| VN Calls: 200 calls (avg 3 min)              |
| - Tokens needed: 200 x 3 = 600               |
| - If 400 tokens remaining:                   |
|   - 400 tokens consumed (= 400 min covered)  |
|   - 200 min overflow x 1,000 micros/min      |
|     = 200,000 micros ($0.20)                 |
|                                              |
| PSTN Calls: 50 calls (avg 2 min)             |
| - Credit: 50 x 2 x 10,000 = 1,000,000 micros|
|   ($1.00)                                    |
|                                              |
| SMS: 100 messages (credit-only)              |
| - Credit: 100 x 10,000 = 1,000,000 micros   |
|   ($1.00)                                    |
|                                              |
| Total credit: 2,200,000 micros ($2.20)       |
+----------------------------------------------+

Best Practices

1. Token Monitoring

  • Check balance_token on the account regularly

  • Plan upgrades to higher tiers if tokens are consistently exhausted before the next top-up

  • Review billing ledger entries to understand consumption patterns

2. Balance Monitoring

  • Maintain credit balance for PSTN calls, number purchases, and token overflow

  • Set up low balance alerts

  • Plan for buffer above minimum needed

3. Cost Estimation

  • Separate estimates into token-eligible and credit-only services

  • Account for token overflow in budget planning

  • Include retry costs in estimates

  • Note all credit amounts are in micros (divide by 1,000,000 for USD)

4. Security

  • Restrict balance add permissions to admins

  • Monitor for unusual usage patterns via the billing ledger

  • Review billing history regularly for anomalies

5. Plan Selection

  • Choose plan tier based on expected VN call, TTS, and recording volume

  • Compare token allocation cost vs. credit-only cost at each tier

  • Consider upgrading if monthly overflow charges are significant

Troubleshooting

Balance Issues

Token Issues

Billing Issues

Tutorial

Before managing billing accounts, you need:

  • An authentication token. Obtain one via POST /auth/login or use an access key from GET /accesskeys.

  • The billing account ID (UUID). Obtain it via GET /billing_accounts which lists all billing accounts for the authenticated customer.

  • (For adding balance) Admin-level permissions on the account.

Note

AI Implementation Hint

The balance_credit field is in micros (int64), not dollars. To convert: divide by 1,000,000 for USD (e.g., 69772630 micros = $69.77). The balance_token field is a plain integer representing remaining tokens. When estimating costs, multiply the per-unit rate in micros by billable units. Call durations are ceiling-rounded to the next whole minute for billing purposes (e.g., a 2 minute 15 second call is billed as 3 minutes).

Check Account Balance

Check your billing account balance before initiating calls or sending messages to ensure sufficient funds.

Get Billing Account:

$ curl --location --request GET 'https://api.voipbin.net/v1.0/billing_accounts/<billing-account-id>?token=<YOUR_AUTH_TOKEN>'

{
    "id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
    "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
    "name": "Primary Account",
    "detail": "Main billing account",
    "plan_type": "free",
    "balance_credit": 69772630,
    "balance_token": 70,
    "payment_type": "",
    "payment_method": "",
    "tm_last_topup": "2024-01-01T00:00:00Z",
    "tm_next_topup": "2024-02-01T00:00:00Z",
    "tm_create": "2024-01-01T00:00:00Z",
    "tm_update": "2024-01-15T10:30:00Z"
}

The balance_credit field is in micros (69772630 = $69.77). The balance_token field is the current token count.

List All Billing Accounts:

$ curl --location --request GET 'https://api.voipbin.net/v1.0/billing_accounts?token=<YOUR_AUTH_TOKEN>'

{
    "result": [
        {
            "id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
            "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
            "name": "Primary Account",
            "detail": "Main billing account",
            "plan_type": "free",
            "balance_credit": 69772630,
            "balance_token": 70,
            "payment_type": "",
            "payment_method": "",
            "tm_last_topup": "2024-01-01T00:00:00Z",
            "tm_next_topup": "2024-02-01T00:00:00Z",
            "tm_create": "2024-01-01T00:00:00Z",
            "tm_update": "2024-01-15T10:30:00Z"
        }
    ]
}

Add Balance (Admin Only)

Only users with admin permissions can add balance to accounts. This ensures account security and prevents unauthorized access.

Add Balance:

$ curl --location --request POST 'https://api.voipbin.net/v1.0/billing_accounts/<billing-account-id>/balance?token=<YOUR_AUTH_TOKEN>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "amount": 100.00
    }'

{
    "id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
    "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
    "name": "Primary Account",
    "detail": "Main billing account",
    "plan_type": "free",
    "balance_credit": 169772630,
    "balance_token": 70,
    "payment_type": "",
    "payment_method": "",
    "tm_last_topup": "2024-01-01T00:00:00Z",
    "tm_next_topup": "2024-02-01T00:00:00Z",
    "tm_create": "2024-01-01T00:00:00Z",
    "tm_update": "2024-01-15T10:30:00Z"
}

Important: This operation requires admin permissions. Regular users will receive a permission error.

Understanding Service Rates

VoIPBIN uses a hybrid billing model: token-eligible services (VN calls, TTS) consume tokens first, then overflow to credits. Credit-only services (PSTN calls, SMS, email, numbers) always charge the credit balance directly. All calls are billed per minute with ceiling rounding.

For the complete rate table, see Rate Structure.

Calculate VN Call Cost (with tokens):

# Example: 5 minute VN call with tokens available
Duration: 5 minutes
Token cost: 5 x 1 = 5 tokens
Credit cost: $0.00 (covered by tokens)

Calculate VN Call Cost (tokens exhausted):

# Example: 5 minute VN call with no tokens remaining
Duration: 5 minutes
Credit cost: 5 x $0.001 = $0.005

Calculate PSTN Call Cost:

# Example: 2 minute 30 second PSTN outgoing call
Duration: 2 min 30 sec -> 3 minutes (ceiling-rounded)
Credit cost: 3 x $0.01 = $0.03

Calculate SMS Cost:

# Example: 10 messages (SMS is always credit-only)
Credit cost: 10 x $0.01 = $0.10

Check Balance Before Call

Programmatically verify balance before initiating calls to ensure successful completion.

Python Example:

import requests
import math

def check_balance_and_call(billing_account_id, call_duration_minutes, call_type="vn"):
    base_url = "https://api.voipbin.net/v1.0"
    params = {"token": "<YOUR_AUTH_TOKEN>"}

    # Get billing account
    account = requests.get(
        f"{base_url}/billing_accounts/{billing_account_id}",
        params=params
    ).json()

    balance_credit = account['balance_credit']  # int64 micros
    balance_token = account['balance_token']     # int64 token count
    duration = math.ceil(call_duration_minutes)  # ceiling-rounded

    if call_type == "vn":
        # VN call: check tokens first, then credit for overflow
        tokens_needed = duration * 1  # 1 token per minute
        if balance_token >= tokens_needed:
            print(f"VN call covered by tokens: {tokens_needed} tokens")
            return True
        # Tokens insufficient — estimate credit overflow
        overflow_minutes = duration - balance_token
        estimated_cost_micros = overflow_minutes * 1000  # 1,000 micros/min
        print(f"VN call overflow: {overflow_minutes} min x 1,000 = {estimated_cost_micros} micros")
        can_proceed = balance_credit >= estimated_cost_micros

    elif call_type == "pstn":
        # PSTN call: always credit
        estimated_cost_micros = duration * 10000  # 10,000 micros/min
        print(f"PSTN call cost: {duration} min x 10,000 = {estimated_cost_micros} micros")
        can_proceed = balance_credit >= estimated_cost_micros

    if not can_proceed:
        print(f"Insufficient credit: {balance_credit} micros (${balance_credit / 1_000_000:.2f})")
        return False

    print(f"Balance OK: {balance_credit} micros (${balance_credit / 1_000_000:.2f})")
    return True

# Check for a 10 minute VN call
check_balance_and_call("62918cd8-0cd7-11ee-8571-b738bed3a5c4", 10, "vn")

# Check for a 5 minute PSTN call
check_balance_and_call("62918cd8-0cd7-11ee-8571-b738bed3a5c4", 5, "pstn")

Node.js Example:

const axios = require('axios');

async function checkBalanceAndCall(billingAccountId, callDurationMinutes, callType = 'vn') {
    try {
        const baseUrl = 'https://api.voipbin.net/v1.0';
        const params = { token: '<YOUR_AUTH_TOKEN>' };

        // Get billing account
        const accountResponse = await axios.get(
            `${baseUrl}/billing_accounts/${billingAccountId}`,
            { params }
        );
        const account = accountResponse.data;

        const balanceCredit = account.balance_credit;  // int64 micros
        const balanceToken = account.balance_token;     // int64 token count
        const duration = Math.ceil(callDurationMinutes);  // ceiling-rounded

        let canProceed = false;

        if (callType === 'vn') {
            // VN call: check tokens first, then credit for overflow
            const tokensNeeded = duration * 1;  // 1 token per minute
            if (balanceToken >= tokensNeeded) {
                console.log(`VN call covered by tokens: ${tokensNeeded} tokens`);
                return true;
            }
            const overflowMinutes = duration - balanceToken;
            const estimatedCostMicros = overflowMinutes * 1000;  // 1,000 micros/min
            console.log(`VN call overflow: ${overflowMinutes} min x 1,000 = ${estimatedCostMicros} micros`);
            canProceed = balanceCredit >= estimatedCostMicros;
        } else if (callType === 'pstn') {
            // PSTN call: always credit
            const estimatedCostMicros = duration * 10000;  // 10,000 micros/min
            console.log(`PSTN call cost: ${duration} min x 10,000 = ${estimatedCostMicros} micros`);
            canProceed = balanceCredit >= estimatedCostMicros;
        }

        if (!canProceed) {
            console.log(`Insufficient credit: ${balanceCredit} micros ($${(balanceCredit / 1000000).toFixed(2)})`);
            return null;
        }

        console.log(`Balance OK: ${balanceCredit} micros ($${(balanceCredit / 1000000).toFixed(2)})`);
        return true;

    } catch (error) {
        console.error('Error:', error.message);
        return null;
    }
}

// Check for a 10 minute VN call
checkBalanceAndCall('62918cd8-0cd7-11ee-8571-b738bed3a5c4', 10, 'vn');

Monitor Balance with Webhooks

Set up webhooks to receive notifications when billing account state changes. You can implement client-side low balance alerts by checking the balance in the webhook payload.

Create Webhook for Billing Events:

$ curl --location --request POST 'https://api.voipbin.net/v1.0/webhooks?token=<YOUR_AUTH_TOKEN>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "name": "Balance Monitoring Webhook",
        "uri": "https://your-server.com/webhook/billing",
        "method": "POST",
        "event_types": [
            "account_updated"
        ]
    }'

Webhook Payload Example:

POST https://your-server.com/webhook/billing

{
    "event_type": "account_updated",
    "timestamp": "2024-01-15T10:30:00Z",
    "data": {
        "id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
        "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
        "name": "Primary Account",
        "plan_type": "free",
        "balance_credit": 15500000,
        "balance_token": 20
    }
}

Process Webhook with Low Balance Alert:

# Python Flask example
from flask import Flask, request, jsonify

app = Flask(__name__)

LOW_BALANCE_THRESHOLD_MICROS = 20_000_000  # $20.00 in micros

@app.route('/webhook/billing', methods=['POST'])
def billing_webhook():
    payload = request.get_json()
    event_type = payload.get('event_type')

    if event_type == 'account_updated':
        data = payload['data']
        balance_credit = data['balance_credit']  # int64 micros
        balance_token = data['balance_token']     # int64 token count
        account_id = data['id']

        # Check if credit balance is low
        if balance_credit < LOW_BALANCE_THRESHOLD_MICROS:
            send_low_balance_alert(account_id, balance_credit, balance_token)

    return jsonify({'status': 'received'}), 200

def send_low_balance_alert(account_id, balance_credit, balance_token):
    balance_usd = balance_credit / 1_000_000
    threshold_usd = LOW_BALANCE_THRESHOLD_MICROS / 1_000_000
    subject = f"Low Balance Alert: ${balance_usd:.2f}"
    body = f"""
    Your billing account credit balance is low.

    Account ID: {account_id}
    Current Credit Balance: ${balance_usd:.2f} ({balance_credit} micros)
    Current Token Balance: {balance_token}
    Threshold: ${threshold_usd:.2f}

    Note: Token-eligible services (VN calls, TTS) will continue
    working as long as monthly tokens are available. Credit balance
    is needed for PSTN calls, SMS, email, number purchases, and
    token overflow.
    """
    print(f"Sending low balance alert: {subject}")

Common Use Cases

1. Pre-Campaign Cost Estimation:

def estimate_campaign_cost(pstn_calls, pstn_avg_minutes, sms_count):
    """Estimate campaign credit cost in micros (1 USD = 1,000,000 micros)."""
    import math

    # PSTN calls: always credit (10,000 micros/min outgoing)
    pstn_total_minutes = pstn_calls * math.ceil(pstn_avg_minutes)
    pstn_credit_micros = pstn_total_minutes * 10000

    # SMS: always credit (10,000 micros/msg)
    sms_credit_micros = sms_count * 10000

    total_micros = pstn_credit_micros + sms_credit_micros

    return {
        'pstn_credit_micros': pstn_credit_micros,
        'sms_credit_micros': sms_credit_micros,
        'total_credit_micros': total_micros
    }

# Example: mixed campaign
costs = estimate_campaign_cost(
    pstn_calls=50, pstn_avg_minutes=2,
    sms_count=200
)
print(f"PSTN credit: {costs['pstn_credit_micros']} micros (${costs['pstn_credit_micros'] / 1_000_000:.2f})")
print(f"SMS credit: {costs['sms_credit_micros']} micros (${costs['sms_credit_micros'] / 1_000_000:.2f})")
print(f"Total credit needed: {costs['total_credit_micros']} micros (${costs['total_credit_micros'] / 1_000_000:.2f})")

2. Plan Tier Comparison:

def recommend_plan(monthly_vn_minutes, monthly_tts_minutes):
    """Recommend the plan tier with the least overflow credit cost."""
    plans = {
        'free':         {'tokens': 100},
        'basic':        {'tokens': 1000},
        'professional': {'tokens': 10000},
    }

    for plan_name, plan in plans.items():
        vn_tokens = monthly_vn_minutes * 1    # 1 token per minute
        tts_tokens = monthly_tts_minutes * 3  # 3 tokens per minute
        total_tokens = vn_tokens + tts_tokens

        if total_tokens <= plan['tokens']:
            overflow_micros = 0
        else:
            # When tokens run out, remaining usage overflows to credit.
            overflow_tokens = total_tokens - plan['tokens']
            vn_ratio = vn_tokens / total_tokens if total_tokens > 0 else 0
            overflow_vn_micros = int(overflow_tokens * vn_ratio) * 1000
            overflow_tts_micros = int(overflow_tokens * (1 - vn_ratio) / 3) * 30000
            overflow_micros = overflow_vn_micros + overflow_tts_micros

        print(f"{plan_name}: {plan['tokens']} tokens, "
              f"need {total_tokens}, overflow: {overflow_micros} micros "
              f"(${overflow_micros / 1_000_000:.2f})")

recommend_plan(monthly_vn_minutes=500, monthly_tts_minutes=100)

Best Practices

1. Balance Verification:

  • Always check credit balance before high-cost operations

  • For PSTN calls and number purchases: check credit balance directly

  • Add a buffer (10-20%) to estimated credit costs for safety

2. Monitoring:

  • Set up webhooks for real-time balance updates

  • Monitor credit balance during campaigns

  • Generate regular cost reports for analysis

3. Cost Management:

  • Separate estimates into token-eligible and credit-only services

  • Calculate worst-case costs assuming full token overflow

  • Generate regular cost reports for analysis

4. Security:

  • Protect admin tokens used for balance operations

  • Implement role-based access for balance management

  • Audit balance changes regularly

Balance Management Workflow

1. Initial Setup:

# Check current balance
GET /v1.0/billing_accounts/<account-id>

# Set up webhook for balance monitoring
POST /v1.0/webhooks
-> Configure account_updated events

2. Before Operations:

# Determine service type
if service_type in ['pstn_call', 'number']:
    # Always check credit balance
    check_credit_balance()

3. During Operations:

# Monitor via webhooks
-> Receive balance update events

4. After Operations:

# Review credit charges (in micros)
actual_credit_micros = initial_balance_credit - current_balance_credit

Troubleshooting

Common Issues:

Insufficient balance error:

  • Check credit balance: GET /v1.0/billing_accounts/<account-id>

  • PSTN calls and number purchases require credit balance

Unexpected credit charges:

  • Verify call durations are ceiling-rounded to the next whole minute

  • Review PSTN call history (always charged to credit)

Permission denied when adding balance:

  • Ensure user has admin permissions

  • Verify authentication token is valid

  • Check user role in account settings

For more information about billing account management, see Billing Account Overview.

Struct

Billing account

{
    "id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
    "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
    "name": "",
    "detail": "",
    "plan_type": "free",
    "balance_credit": 69772630,
    "balance_token": 650,
    "payment_type": "",
    "payment_method": "",
    "tm_last_topup": "2024-01-01T00:00:00Z",
    "tm_next_topup": "2024-02-01T00:00:00Z",
    "tm_create": "2013-06-17 00:00:00.000000",
    "tm_update": "2023-06-30 19:18:08.466742",
    "tm_delete": null
}
  • id (UUID): The billing account’s unique identifier. Returned when listing billing accounts via GET /billing_accounts or retrieving a specific account via GET /billing_accounts/{id}.

  • customer_id (UUID): The customer that owns this billing account. Obtained from the id field of GET /customers.

  • name (String): The billing account’s display name. Optional.

  • detail (String): An optional description of the billing account.

  • plan_type (enum string): The plan tier of the account. Determines resource creation limits and monthly token allocations. Values: free, basic, professional, unlimited.

  • balance_credit (Integer, int64 micros): Credit balance in micros. 1 USD = 1,000,000 micros. Example: 69772630 = $69.77. Used for PSTN calls, number purchases, and token overflow charges.

  • balance_token (Integer, int64): Current token balance. Tokens are consumed by VN calls (1 token/minute) and TTS (3 tokens/minute). Replenished monthly via automated top-up.

  • payment_type (String): Payment type. Reserved for future use.

  • payment_method (String): Payment method. Reserved for future use.

  • tm_last_topup (string, ISO 8601): Timestamp of the last token top-up.

  • tm_next_topup (string, ISO 8601): Timestamp of the next scheduled token top-up.

  • tm_create (string, ISO 8601): Timestamp when the billing account was created.

  • tm_update (string, ISO 8601): Timestamp when the billing account was last updated.

  • tm_delete (string, ISO 8601 or null): Timestamp when the billing account was deleted. null indicates the account is active.

Note

AI Implementation Hint

Unlike other VoIPBIN resources that use 9999-01-01 00:00:00.000000 as the sentinel for “not deleted,” the billing account’s tm_delete field uses null to indicate an active account. Always check for null rather than the sentinel timestamp when determining if a billing account is active. The balance_credit field is in micros (int64) – divide by 1,000,000 to get USD.

Billing (Ledger Entry)

Each billing record is an immutable ledger entry recording a single transaction. The ledger tracks both the delta (change in balance) and a post-transaction snapshot.

{
    "id": "69cacd9e-f542-11ee-ab6d-afb3c2c93e56",
    "customer_id": "5e4a0680-804e-11ec-8477-2fea5968d85b",
    "account_id": "62918cd8-0cd7-11ee-8571-b738bed3a5c4",
    "transaction_type": "usage",
    "status": "end",
    "reference_type": "call",
    "reference_id": "a1b2c3d4-5678-abcd-ef12-345678901234",
    "cost_type": "call_pstn_outgoing",
    "usage_duration": 135,
    "billable_units": 3,
    "rate_token_per_unit": 0,
    "rate_credit_per_unit": 10000,
    "amount_token": 0,
    "amount_credit": -30000,
    "balance_token_snapshot": 650,
    "balance_credit_snapshot": 69742630,
    "idempotency_key": "b2c3d4e5-6789-bcde-f123-456789012345",
    "tm_billing_start": "2024-01-15T10:30:00Z",
    "tm_billing_end": "2024-01-15T10:32:15Z",
    "tm_create": "2024-01-15T10:32:15Z",
    "tm_update": "2024-01-15T10:32:15Z",
    "tm_delete": null
}
  • id (UUID): The unique identifier of this ledger entry. Returned when listing billings via GET /billings.

  • customer_id (UUID): The customer that owns this billing account. Obtained from the id field of GET /customers.

  • account_id (UUID): The billing account this entry belongs to. Obtained from the id field of GET /billing_accounts.

  • transaction_type (enum string): The nature of the transaction. Values: usage (service consumption), top_up (token replenishment), adjustment (manual correction), refund (credit return).

  • status (enum string): The billing entry status. Values: progressing (in progress), end (completed), pending (awaiting processing), finished (finalized).

  • reference_type (enum string): The source of the transaction. Values: call, call_extension, sms, email, number, number_renew, credit_free_tier, monthly_allowance.

  • reference_id (UUID): The ID of the originating resource (e.g., call ID, number ID). Obtained from the id field of the corresponding resource endpoint (e.g., GET /calls/{id}).

  • cost_type (enum string): Classification of the billing cost. Values include: call_pstn_outgoing, call_pstn_incoming, call_vn, call_extension, call_direct_ext, sms, email, number, number_renew.

  • usage_duration (Integer): Actual usage duration in seconds (for calls). Not applicable for non-call services.

  • billable_units (Integer): Number of billable units after ceiling rounding (e.g., 135 seconds becomes 3 minutes for call billing).

  • rate_token_per_unit (Integer, int64): Token rate per billable unit. Set to 0 for credit-only services.

  • rate_credit_per_unit (Integer, int64 micros): Credit rate per billable unit in micros. Example: 10000 = $0.01.

  • amount_token (Integer, int64): Token delta for this transaction. Negative for usage, positive for top-up.

  • amount_credit (Integer, int64 micros): Credit delta in micros for this transaction. Negative for usage, positive for top-up/refund.

  • balance_token_snapshot (Integer, int64): The token balance immediately after this transaction was applied.

  • balance_credit_snapshot (Integer, int64 micros): The credit balance in micros immediately after this transaction was applied.

  • idempotency_key (UUID): Unique key to prevent duplicate billing entries for the same event.

  • tm_billing_start (string, ISO 8601): Timestamp marking the start of the billing period for this transaction.

  • tm_billing_end (string, ISO 8601): Timestamp marking the end of the billing period for this transaction.

  • tm_create (string, ISO 8601): Timestamp when this ledger entry was created.

  • tm_update (string, ISO 8601): Timestamp when this ledger entry was last updated.

  • tm_delete (string, ISO 8601 or null): Timestamp when this ledger entry was deleted. null indicates the entry is active.

Note

AI Implementation Hint

All monetary fields (rate_credit_per_unit, amount_credit, balance_credit_snapshot) are in micros (int64). Divide by 1,000,000 to convert to USD. The amount_token and amount_credit fields are signed: negative values represent charges/consumption, positive values represent top-ups or refunds. Call durations are ceiling-rounded to the next whole minute for billing (e.g., 135 seconds = 3 billable minutes).