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)
- 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 examplehttps://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. - 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. - Give the billing site the webhook address (
https://your-castgate/billing/webhook) and the shared secret shown on Admin → Billing. - 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.
- 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.
- Email must work (Admin → Settings → Email): new customers receive their sign-up link by email.
What happens
| At the billing site | In castgate |
|---|---|
| A new customer subscribes on the home page | A 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 page | The plan applies to that account at once |
| A renewal is paid | The paid period is extended; a paused account resumes |
| A payment fails | The 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 canceled | The account works until the end of the paid period, then pauses |
| The subscription ends at once | The account pauses now |
| A refund | Noted 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)
Checkout links
castgate links to the plan's checkout address and adds query parameters:
| Parameter | Meaning |
|---|---|
plan | castgate plan id (standard) |
return_url | where to send the customer after paying (https://your-castgate/billing/thanks) |
account | castgate account id, when an existing customer comes from their Billing page |
account_sig | castgate's signature of the account id |
email | the 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..."
}
| Field | Required | Notes |
|---|---|---|
id | yes | unique per event; castgate applies each id once (a repeat answers "duplicate") |
type | yes | see the list below |
created | no | Unix seconds |
customer.id, customer.email, customer.name | email for new subscriptions | the sign-up code is sent to customer.email |
subscription.id | yes (except test.ping) | links later events to the account |
subscription.plan | for activated and plan changes | a castgate plan id |
subscription.status | no | active, trialing, past_due, canceled, ended |
subscription.current_period_end | for activated and renewed | Unix seconds: access is paid until then |
subscription.trial_end | for trials | Unix seconds |
payment.amount_cents, payment.currency | no | shown to the owner |
account, account_sig | when the checkout link had them | send back unchanged |
Event types
| Type | When | castgate does |
|---|---|---|
subscription.activated | a subscription starts (paid or trial) | links or creates the account (sign-up code by email), sets the plan and the paid period |
subscription.renewed | a renewal is paid | extends the paid period, resumes a paused account |
payment.succeeded | any successful payment for the subscription | same as renewed |
subscription.updated | plan or period changed | applies the new plan, period and status |
payment.failed | a payment failed | starts the grace period (once), emails the owner |
subscription.past_due | the subscription is overdue | same as payment.failed |
subscription.canceled | canceled (at the period end) | access until current_period_end, then pause |
subscription.ended | ended now (expired, or canceled immediately) | pauses now |
payment.refunded | a refund | logged |
test.ping | a connection test | answers ok |
Other types are answered 200 ignored, so the billing site can send all its events.
Answers
| Status | Body | Meaning | Retry? |
|---|---|---|---|
| 200 | {"result":"..."} | applied, a duplicate, or ignored | no |
| 400 | {"error":"..."} | not JSON, or no id or type | no: fix the sender |
| 401 | {"error":"..."} | bad or old signature | after fixing the secret or the clock |
| 404 | billing is off in castgate | no | |
| 422 | {"result":"..."} | cannot be applied (unknown plan, no linked account, no email) | after fixing; the event is not marked as applied |
| 500 | castgate could not save | yes, 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
idper event and reuse it on retries: castgate then applies it once. - Send
subscription.renewed(orpayment.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
v1values in one header during a change).
This guide is also in the castgate package as docs/BILLING.md.