Skip to main content
This guide walks you through launching a complete self-serve billing flow: free trials with credits, hosted checkout for upgrades, usage-based billing, and a customer portal for account management.

What You’ll Build

PhaseWhat Happens
TrialUser signs up → Create account → Grant trial credits
UpgradeCredits depleted → Redirect to hosted checkout → User subscribes
OngoingSend usage events → Alguna bills automatically
PortalUser manages subscription, invoices, and payment methods

Prerequisites

Before starting:
  1. API Key: Get your API key from Settings → API Keys
  2. Webhook Endpoint: Have a URL ready to receive webhooks
  3. Checkout Flow: Create a checkout flow in Settings → Hosted Pages → Checkout Flows

Step 1: Create Customer Account

When a user signs up in your application, create a corresponding account in Alguna. Endpoint: POST /accounts
{
  "name": "Acme Corp",
  "email": "[email protected]",
  "alias": "your-internal-id-123"
}
Response:
{
  "id": "acc_abc123",
  "name": "Acme Corp",
  "email": "[email protected]",
  "alias": "your-internal-id-123"
}
Store the Alguna id in your database. You’ll need it for granting credits, creating checkout sessions, and generating portal links. Alternatively, use alias to reference accounts by your internal ID.

Step 2: Grant Trial Credits

Give new users trial credits to try your product before subscribing. Endpoint: POST /accounts/{id}/credits/grants
{
  "creditType": "units",
  "amount": "50",
  "reason": "Welcome credits"
}
This grants 50 units (e.g., API calls, runs, minutes) to the account.

Check Credit Balance

Endpoint: GET /accounts/{accountId}/credits/balance?type=units
{
  "accountId": "acc_abc123",
  "creditType": "units",
  "balance": "50"
}

Optional: Check Credit Availability

Before performing an action, verify the user has sufficient credits. Endpoint: GET /accounts/{accountId}/credits/availability?type=units&required=10
{
  "available": true,
  "balance": "50",
  "required": "10",
  "shortfall": "0"
}

Step 3: Handle Credit Depletion

When trial credits run out, Alguna sends a webhook so you can prompt the user to upgrade.

Configure Webhook

  1. Navigate to Settings → Webhooks
  2. Add your endpoint URL
  3. Subscribe to account.credits.balance_depleted

Webhook Payload

{
  "type": "account.credits.balance_depleted",
  "timestamp": "2025-03-03T17:06:07.473879Z",
  "data": {
    "accountId": "acc_abc123",
    "amount": "0",
    "type": "units"
  }
}
When you receive this webhook, redirect the user to your upgrade page or directly to hosted checkout.

Step 4: Redirect to Hosted Checkout

When users are ready to subscribe, redirect them to Alguna’s hosted checkout.

Option A: Simple Redirect (No Code)

Redirect users directly to your checkout flow URL:
https://billing.yourcompany.com/checkout?flowId={flowId}&accountId={accountId}
ParameterDescription
flowIdYour checkout flow ID from the dashboard
accountIdThe Alguna account ID
ptOptional pass-through token for verification

Option B: Server-Side Session (More Control)

Create a checkout session via API for more flexibility. Endpoint: POST /customer-session/checkout
{
  "accountId": "acc_abc123",
  "accountEmail": "[email protected]",
  "currency": "USD",
  "successUrl": "https://yourapp.com/welcome",
  "passThroughToken": "your-internal-reference"
}
Response:
{
  "checkoutSessionId": "chk_xyz789",
  "url": "https://billing.yourcompany.com/checkout/session/..."
}
Redirect the user to the returned url.

Step 5: Handle Checkout Completion

When a user completes checkout, Alguna sends a webhook confirming the subscription.

Webhook Payload

{
  "type": "checkout.session.completed",
  "timestamp": "2025-03-03T17:06:07.473879Z",
  "data": {
    "id": "chk_xyz789",
    "accountId": "acc_abc123",
    "status": "completed",
    "amount": "49.00",
    "currency": "USD",
    "invoiceId": "inv_abc123",
    "paymentId": "pay_def456",
    "passThroughToken": "your-internal-reference"
  }
}
When you receive this:
  1. Update the user’s status in your application
  2. Grant access to paid features
  3. Optionally send a welcome email

Step 6: Send Usage Events

Track usage by sending events to Alguna. Events are processed within 15 minutes. Endpoint: POST /events
{
  "uniqueId": "evt_123456",
  "account": "acc_abc123",
  "eventName": "api_call",
  "timestamp": "2025-03-09T15:03:17Z",
  "properties": {
    "endpoint": "/v1/analyze",
    "tokens": 1500
  }
}
FieldRequiredDescription
accountYesAlguna account ID or your internal ID (alias)
eventNameYesThe type of event (must match your billable metric)
timestampYesWhen the event occurred
uniqueIdNoFor idempotency (prevents duplicate processing)
propertiesNoCustom data for filtering and aggregation
For trial users, consider adding a property like "isTrial": true to distinguish trial usage from paid usage in your analytics.

Usage Aggregation

Alguna can aggregate your events in different ways:
AggregationUse Case
CountCount every event (e.g., API calls)
Count UniqueCount unique values (e.g., unique users)
SumSum a property value (e.g., total minutes)
MaxMaximum value in period
Configure aggregation in Billable Metrics in the dashboard.

Step 7: Add Customer Portal

Let users manage their subscription, view invoices, and update payment methods. Endpoint: POST /portal/customer-session/customer-portal
{
  "accountId": "acc_abc123",
  "planOverviewSettings": {
    "showSection": true,
    "allowSubscriptionCancel": true
  },
  "invoiceListSettings": {
    "showSection": true
  },
  "billingDetailsSettings": {
    "showSection": true
  }
}
Response:
{
  "sessionUrl": "https://billing.yourcompany.com/portal/..."
}
Redirect the user to sessionUrl when they click “Manage Billing” in your app.

Portal Configuration

SettingDefaultDescription
planOverviewSettings.showSectiontrueShow subscription details
planOverviewSettings.allowSubscriptionCanceltrueAllow self-service cancellation
invoiceListSettings.showSectiontrueShow invoice history
billingDetailsSettings.showSectiontrueShow billing info and payment methods
Use allowSubscriptionCancel: false for enterprise customers who should contact sales to cancel.

Complete Integration Flow

┌─────────────────────────────────────────────────────────────────────┐
│                         YOUR APPLICATION                            │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  1. User signs up ──────► Create account in Alguna                  │
│                                    │                                │
│  2. Grant trial credits ◄──────────┘                                │
│           │                                                         │
│           ▼                                                         │
│  3. User uses product ──► Send usage events to Alguna               │
│           │                                                         │
│           ▼                                                         │
│  4. Credits depleted ◄─── Webhook: balance_depleted                 │
│           │                                                         │
│           ▼                                                         │
│  5. Redirect to checkout ──► Alguna hosted checkout                 │
│           │                                                         │
│           ▼                                                         │
│  6. User subscribes ◄──── Webhook: checkout.session.completed       │
│           │                                                         │
│           ▼                                                         │
│  7. Continue sending usage ──► Alguna bills automatically           │
│           │                                                         │
│           ▼                                                         │
│  8. "Manage Billing" ──► Redirect to customer portal                │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Key Webhooks

Subscribe to these webhooks in Settings → Webhooks:
EventWhen It Fires
checkout.session.completedUser completes payment
account.credits.balance_depletedTrial credits hit zero
subscription.createdNew subscription starts
invoice.paidInvoice payment succeeds

What You Don’t Need to Store

Alguna handles these for you:
  • Subscription IDs and status
  • Product and plan details
  • Usage calculations and overages
  • Invoice generation and payment processing
You only need to store the Alguna account ID (or use your internal ID as an alias).

Testing

  1. Use your Sandbox environment for testing
  2. Create test accounts and grant credits
  3. Deplete credits by sending test events
  4. Complete a test checkout
  5. Verify webhooks are received

Next Steps