> ## Documentation Index
> Fetch the complete documentation index at: https://alguna.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Launch PLG in 15 Minutes

> Go from zero to accepting payments with trials, usage tracking, and customer portal

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

| Phase       | What Happens                                                     |
| ----------- | ---------------------------------------------------------------- |
| **Trial**   | User signs up → Create account → Grant trial credits             |
| **Upgrade** | Credits depleted → Redirect to hosted checkout → User subscribes |
| **Ongoing** | Send usage events → Alguna bills automatically                   |
| **Portal**  | User 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`

```json theme={null}
{
  "name": "Acme Corp",
  "email": "billing@acme.com",
  "alias": "your-internal-id-123"
}
```

**Response:**

```json theme={null}
{
  "id": "acc_abc123",
  "name": "Acme Corp",
  "email": "billing@acme.com",
  "alias": "your-internal-id-123"
}
```

<Tip>
  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.
</Tip>

***

## Step 2: Grant Trial Credits

Give new users trial credits to try your product before subscribing.

**Endpoint:** `POST /accounts/{id}/credits/grants`

```json theme={null}
{
  "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`

```json theme={null}
{
  "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`

```json theme={null}
{
  "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

```json theme={null}
{
  "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}
```

| Parameter   | Description                                  |
| ----------- | -------------------------------------------- |
| `flowId`    | Your checkout flow ID from the dashboard     |
| `accountId` | The Alguna account ID                        |
| `pt`        | Optional 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`

```json theme={null}
{
  "accountId": "acc_abc123",
  "accountEmail": "billing@acme.com",
  "currency": "USD",
  "successUrl": "https://yourapp.com/welcome",
  "passThroughToken": "your-internal-reference"
}
```

**Response:**

```json theme={null}
{
  "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

```json theme={null}
{
  "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`

```json theme={null}
{
  "uniqueId": "evt_123456",
  "account": "acc_abc123",
  "eventName": "api_call",
  "timestamp": "2025-03-09T15:03:17Z",
  "properties": {
    "endpoint": "/v1/analyze",
    "tokens": 1500
  }
}
```

| Field        | Required | Description                                         |
| ------------ | -------- | --------------------------------------------------- |
| `account`    | Yes      | Alguna account ID or your internal ID (alias)       |
| `eventName`  | Yes      | The type of event (must match your billable metric) |
| `timestamp`  | Yes      | When the event occurred                             |
| `uniqueId`   | No       | For idempotency (prevents duplicate processing)     |
| `properties` | No       | Custom data for filtering and aggregation           |

<Tip>
  For trial users, consider adding a property like `"isTrial": true` to distinguish trial usage from paid usage in your analytics.
</Tip>

### Usage Aggregation

Alguna can aggregate your events in different ways:

| Aggregation      | Use Case                                   |
| ---------------- | ------------------------------------------ |
| **Count**        | Count every event (e.g., API calls)        |
| **Count Unique** | Count unique values (e.g., unique users)   |
| **Sum**          | Sum a property value (e.g., total minutes) |
| **Max**          | Maximum 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`

```json theme={null}
{
  "accountId": "acc_abc123",
  "planOverviewSettings": {
    "showSection": true,
    "allowSubscriptionCancel": true
  },
  "invoiceListSettings": {
    "showSection": true
  },
  "billingDetailsSettings": {
    "showSection": true
  }
}
```

**Response:**

```json theme={null}
{
  "sessionUrl": "https://billing.yourcompany.com/portal/..."
}
```

Redirect the user to `sessionUrl` when they click "Manage Billing" in your app.

### Portal Configuration

| Setting                                        | Default | Description                           |
| ---------------------------------------------- | ------- | ------------------------------------- |
| `planOverviewSettings.showSection`             | `true`  | Show subscription details             |
| `planOverviewSettings.allowSubscriptionCancel` | `true`  | Allow self-service cancellation       |
| `invoiceListSettings.showSection`              | `true`  | Show invoice history                  |
| `billingDetailsSettings.showSection`           | `true`  | Show billing info and payment methods |

<Tip>
  Use `allowSubscriptionCancel: false` for enterprise customers who should contact sales to cancel.
</Tip>

***

## 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**:

| Event                              | When It Fires            |
| ---------------------------------- | ------------------------ |
| `checkout.session.completed`       | User completes payment   |
| `account.credits.balance_depleted` | Trial credits hit zero   |
| `subscription.created`             | New subscription starts  |
| `invoice.paid`                     | Invoice 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

<CardGroup cols={2}>
  <Card title="Billable Metrics" icon="chart-bar" href="/billable-metrics/define-metrics">
    Define how usage is measured and billed.
  </Card>

  <Card title="Customer Portal" icon="browser" href="/hosted/customer-portal">
    Full portal configuration options.
  </Card>

  <Card title="Webhooks" icon="webhook" href="/api-reference/webhooks">
    Complete webhook reference.
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/overview">
    Full API documentation.
  </Card>
</CardGroup>
