▶Stream4US

Billing integration

For administrators and the billing site's developers: sell plans on encrypted.com (or any billing system) and let castgate create and pause accounts.

castgate does not take payments. A billing site, for example encrypted.com, sells the castgate plans, and tells castgate what happened through signed webhooks. castgate turns those into accounts and access. This guide is for the castgate administrator (part 1) and for the developers of the billing site (part 2, the contract). Any billing system that follows part 2 works.

Part 1: setting it up (administrator)

  1. In castgate open Admin → Billing. Tick Accounts are sold through the billing site, enter the billing site address (https://encrypted.com), the customer portal address (where customers manage their subscription, for example https://encrypted.com/account) and the grace period (days an account keeps working after a failed payment; 7 by default). Save: castgate makes a shared secret.
  2. At the billing site, create one product per castgate plan (recurring, monthly or yearly). Use the castgate plan id (Admin → Plans: starter, standard, plus, channel, or your own) as the product's reference, so the billing site can send it back.
  3. Give the billing site the webhook address (https://your-castgate/billing/webhook) and the shared secret shown on Admin → Billing.
  4. Back in castgate, enter each plan's checkout link (the billing site's page that sells it). The home page's plan buttons become "Subscribe" and lead there; owners see "Change plan" and "Manage subscription" on their Billing page.
  5. Press Send a test event: castgate signs a test event with the secret, checks it and logs it. Then make a test purchase at the billing site (in its test mode) and watch the Events list.
  6. Email must work (Admin → Settings → Email): new customers receive their sign-up link by email.
Accounts created with signup codes keep working as before. Billing only acts on accounts it is linked to.

What happens

At the billing siteIn castgate
A new customer subscribes on the home pageA one-use sign-up code for the plan is emailed to the buyer; the account they create is linked to the subscription
An owner subscribes or changes plan from their Billing pageThe plan applies to that account at once
A renewal is paidThe paid period is extended; a paused account resumes
A payment failsThe account keeps working for the grace period and the owner is emailed; then it pauses
No renewal arrives (the billing site is silent)Two days after the paid period ends it is treated like a failed payment
The subscription is canceledThe account works until the end of the paid period, then pauses
The subscription ends at onceThe account pauses now
A refundNoted in the log; access follows the subscription events

A paused account cannot stream or be watched, but its recordings and settings are kept. Only billing lifts a billing pause; an administrator's suspension is never lifted by billing. The account owner's Billing page explains why it is paused and links to the customer portal.

Part 2: the contract (billing site developers)

castgate links to the plan's checkout address and adds query parameters:

ParameterMeaning
plancastgate plan id (standard)
return_urlwhere to send the customer after paying (https://your-castgate/billing/thanks)
accountcastgate account id, when an existing customer comes from their Billing page
account_sigcastgate's signature of the account id
emailthe customer's email, to prefill

Keep account and account_sig with the subscription and send them back unchanged in every webhook for it (for example in the subscription's metadata). castgate links a subscription to an existing account only when account_sig is valid, so an edited link cannot attach a payment to someone else's account.

Webhooks

POST https://your-castgate/billing/webhook with a JSON body and the header:

Content-Type: application/json
X-Castgate-Signature: t=1763060000,v1=5f2b...e9

t is the current Unix time in seconds; v1 is the lowercase hex HMAC-SHA256 of the string <t>.<raw body> with the shared secret as key. castgate refuses signatures more than five minutes old or new (keep the clock synchronized) and wrong signatures (401). Several v1= values are allowed (useful while changing the secret).

The event

{
  "id": "evt_8f2c1a",
  "type": "subscription.activated",
  "created": 1763060000,
  "customer": { "id": "cus_123", "email": "pastor@gracechurch.org", "name": "Grace Church" },
  "subscription": {
    "id": "sub_456",
    "plan": "standard",
    "status": "active",
    "current_period_end": 1765652000,
    "trial_end": 0
  },
  "payment": { "amount_cents": 7900, "currency": "USD" },
  "account": "a1b2c3d4e5f6",
  "account_sig": "9c1e..."
}
FieldRequiredNotes
idyesunique per event; castgate applies each id once (a repeat answers "duplicate")
typeyessee the list below
creatednoUnix seconds
customer.id, customer.email, customer.nameemail for new subscriptionsthe sign-up code is sent to customer.email
subscription.idyes (except test.ping)links later events to the account
subscription.planfor activated and plan changesa castgate plan id
subscription.statusnoactive, trialing, past_due, canceled, ended
subscription.current_period_endfor activated and renewedUnix seconds: access is paid until then
subscription.trial_endfor trialsUnix seconds
payment.amount_cents, payment.currencynoshown to the owner
account, account_sigwhen the checkout link had themsend back unchanged

Event types

TypeWhencastgate does
subscription.activateda subscription starts (paid or trial)links or creates the account (sign-up code by email), sets the plan and the paid period
subscription.reneweda renewal is paidextends the paid period, resumes a paused account
payment.succeededany successful payment for the subscriptionsame as renewed
subscription.updatedplan or period changedapplies the new plan, period and status
payment.faileda payment failedstarts the grace period (once), emails the owner
subscription.past_duethe subscription is overduesame as payment.failed
subscription.canceledcanceled (at the period end)access until current_period_end, then pause
subscription.endedended now (expired, or canceled immediately)pauses now
payment.refundeda refundlogged
test.pinga connection testanswers ok

Other types are answered 200 ignored, so the billing site can send all its events.

Answers

StatusBodyMeaningRetry?
200{"result":"..."}applied, a duplicate, or ignoredno
400{"error":"..."}not JSON, or no id or typeno: fix the sender
401{"error":"..."}bad or old signatureafter fixing the secret or the clock
404billing is off in castgateno
422{"result":"..."}cannot be applied (unknown plan, no linked account, no email)after fixing; the event is not marked as applied
500castgate could not saveyes, with backoff

Example: PHP sender

<?php
function castgate_notify(array $event, string $url, string $secret): array {
    $body = json_encode($event, JSON_UNESCAPED_SLASHES);
    $t = time();
    $sig = hash_hmac('sha256', $t . '.' . $body, $secret);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            "X-Castgate-Signature: t=$t,v1=$sig",
        ],
    ]);
    $out = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$code, json_decode((string)$out, true)];
}

// after a successful first payment:
castgate_notify([
    'id' => 'evt_' . bin2hex(random_bytes(8)),
    'type' => 'subscription.activated',
    'created' => time(),
    'customer' => ['id' => $customerId, 'email' => $email, 'name' => $name],
    'subscription' => ['id' => $subId, 'plan' => 'standard', 'status' => 'active',
                       'current_period_end' => $periodEnd],
    'payment' => ['amount_cents' => 7900, 'currency' => 'USD'],
    'account' => $meta['account'] ?? '', 'account_sig' => $meta['account_sig'] ?? '',
], 'https://live.example.org/billing/webhook', CASTGATE_SECRET);

Example: test with curl

SECRET='the shared secret'
BODY='{"id":"evt_test_1","type":"test.ping","created":'$(date +%s)'}'
T=$(date +%s)
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -r | cut -d' ' -f1)
curl -s https://live.example.org/billing/webhook -H 'Content-Type: application/json' \
  -H "X-Castgate-Signature: t=$T,v1=$SIG" -d "$BODY"

The answer is {"result":"ok: castgate received the test event"} and the event appears under Admin → Billing → Events.

Good practice

  • Send webhooks from a queue and retry 500 answers and timeouts with backoff (for example after 1, 5, 30 minutes, then hourly for a day). Never retry 200, 400 or 404.
  • Keep one id per event and reuse it on retries: castgate then applies it once.
  • Send subscription.renewed (or payment.succeeded) for every renewal; castgate pauses accounts whose paid period ended more than two days ago without one.
  • Keep the shared secret on the server only; change it on both sides at once (castgate accepts several v1 values in one header during a change).

This guide is also in the castgate package as docs/BILLING.md.