Skip to content
tiergate/

Guide

Integrate your backend

Connect your application's server to a Tiergate project to register customers, take payments, and keep access in sync.

Tiergate holds your plans, payment provider accounts, and subscriptions. Your backend calls Tiergate’s API and decides what each customer can access. This guide covers the full loop:

  1. Register each customer as a customer.
  2. Start a checkout and send the buyer to the provider’s payment page.
  3. Tiergate receives the provider’s confirmation and updates the subscription.
  4. Your backend reads the subscription, or receives an event, and grants access.

All calls in this guide come from your server. Never call the API from browser or mobile code, because that would expose your API key.

Before you start

You need:

  • A project in the console.
  • A connected payment provider. Open Payment providers, connect an account, and enable it. Each connected account has a connection ID, shown on its card. You pass it when you start a checkout.
  • Plans. Open Plans and create what customers can buy. Each plan has a permanent key (for example pro-monthly), a RUB price for the whole period, and a monthly or annual interval. For Polar, add the Polar product ID too. Every project also has a built-in free plan.
  • An API key. Open API keys and create a key with Read and write permission. The secret is shown once, so store it in your server’s secret storage. The same page shows your tenant ID and project ID.

The examples use these environment variables:

TIERGATE_API_URL=https://api.tiergate.io
TIERGATE_API_KEY=...        # project API key
TIERGATE_TENANT_ID=...      # tenant ID from the API keys page
TIERGATE_PROJECT_ID=...     # project ID from the API keys page

Every project endpoint starts with the same prefix. Some examples below call it $BASE:

BASE="$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID"

1. Authenticate requests

Send the API key as a bearer token:

curl "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/customers/$CUSTOMER_UUID/subscription" \
  -H "Authorization: Bearer $TIERGATE_API_KEY"
Permission Allows
Read only GET requests: reading payment orders and subscriptions, and listing your plans for a pricing page (GET $TIERGATE_API_URL/v1/control/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/plans).
Read and write Everything above, plus registering customers, starting checkouts, syncing payments, and managing subscriptions.

A key works only for the project that created it. A missing, revoked, or expired key returns 401. A key without the needed permission, or a request to a different project, returns 403.

To rotate a key, create a new one, deploy it, then revoke the old one.

2. Register customers as customers

A customer is the customer who pays: a user, or an organization if you bill teams. Register the customer when the customer signs up, or just before their first checkout:

curl -X PUT "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/customers" \
  -H "Authorization: Bearer $TIERGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "customerType": "user", "externalId": "user_8f2c", "locale": "en" }'
{
  "customerUuid": "6f1d4c1e-2a7b-4c8e-9d3a-0b5e7f9a1c2d",
  "tenantUuid": "…",
  "projectUuid": "…",
  "customerType": "user",
  "externalId": "user_8f2c",
  "locale": "en",
  "status": "active"
}

externalId is your own ID for the customer. The call is an upsert: sending the same customerType and externalId again returns the same customer, and it never changes the customer’s plan. Calling it on every sign-in is safe.

Save customerUuid next to your customer record. Every later call uses it.

3. Start a checkout

Create the checkout from your server, then redirect the buyer to the returned checkoutUrl:

curl -X POST "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/checkout/yookassa/$CONNECTION_ID" \
  -H "Authorization: Bearer $TIERGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: checkout-user_8f2c-2026-11-04-1" \
  -d '{
    "customerUuid": "6f1d4c1e-2a7b-4c8e-9d3a-0b5e7f9a1c2d",
    "userId": "user_8f2c",
    "planKey": "pro-monthly",
    "customerEmail": "[email protected]"
  }'
{
  "orderId": "0b9e2f4a-…",
  "connectionId": "…",
  "customerUuid": "6f1d4c1e-…",
  "provider": "yookassa",
  "status": "processing",
  "checkoutUrl": "https://…",
  "amount": 99000,
  "currency": "RUB",
  "planKey": "pro-monthly",
  "billingInterval": "monthly",
  "refundedAmount": 0
}
  • Provider and connection. The path ends with the provider (yookassa, platega, tbank, polar, or stripe) and then the connection ID, which selects which account of that provider to use.
  • Amounts are in minor units. 99000 is 990.00 RUB. A plan’s price covers the whole period, including for annual plans.
  • Idempotency-Key is required, 8–255 characters. Retrying the same request with the same key returns the same checkout, so a network retry never creates a second payment. Reusing a key with a different body returns 409 PAYMENT_CONFLICT. Use a new key for each new purchase.
  • customerEmail receives the provider’s receipt where receipts apply.
  • userId is your reference for the buyer. It usually matches externalId.

Save orderId. You need it to check the payment.

If checkout creation fails

Status and code Meaning What to do
502 CHECKOUT_UNRESOLVED The provider did not answer, so the payment may or may not exist. The message contains the reserved order ID. Do not start a new checkout with a new key. Check the order (step 4); the provider’s confirmation can still settle it.
422 CHECKOUT_REJECTED The provider refused the checkout. Show an error. A new attempt needs a new key.
409 PROVIDER_DISABLED The connected account is disabled in the console. Enable it under Payment providers.
404 NOT_FOUND Unknown customer, plan, or connection, or the plan is archived or has no price for this provider. Check the IDs and the plan under Plans.
400 INVALID_REQUEST A required field is missing or malformed, for example an invalid email or a short Idempotency-Key. Fix the request.

4. Handle the buyer’s return

After paying, the provider sends the buyer back to the return URL configured on the provider account. Arriving at the return URL does not prove the buyer paid. Only the provider’s verified confirmation to Tiergate does.

On your return page, show a “confirming payment” state and check the order:

curl "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/payment-orders/$ORDER_ID" \
  -H "Authorization: Bearer $TIERGATE_API_KEY"
  • confirmed: the payment succeeded and the subscription is updated.
  • cancelled or failed: the payment did not go through, or the provider rejected the checkout. Offer a new checkout with a new idempotency key.
  • refunded: the payment was fully refunded.
  • processing or unknown: not settled yet. Poll every few seconds for a short while, then rely on events (step 6).

If an order stays unresolved, ask Tiergate to re-read it from the provider:

curl -X POST "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/payment-orders/$ORDER_ID/sync" \
  -H "Authorization: Bearer $TIERGATE_API_KEY"

5. Decide access from the subscription

The subscription is the source of truth for what a customer has paid for:

curl "$TIERGATE_API_URL/v1/tenants/$TIERGATE_TENANT_ID/projects/$TIERGATE_PROJECT_ID/customers/$CUSTOMER_UUID/subscription" \
  -H "Authorization: Bearer $TIERGATE_API_KEY"
{
  "id": "…",
  "customerUuid": "6f1d4c1e-…",
  "provider": "yookassa",
  "planKey": "pro-monthly",
  "status": "active",
  "currentPeriodStart": "2026-11-04T10:12:00Z",
  "currentPeriodEnd": "2026-12-04T10:12:00Z",
  "cancelAtPeriodEnd": false,
  "providerPortal": false
}

Grant the plan in planKey while status is active or past_due and currentPeriodEnd is in the future. past_due means an automatic renewal was declined and is being retried, and the customer keeps access during the retries. A 404 means the customer has never had a paid subscription, so treat them as free.

You can cache this response, and refresh it when you receive an event (step 6) or when currentPeriodEnd passes.

How renewals work depends on the provider:

  • YooKassa, Platega, T-Bank: each checkout pays for one period. To extend, the customer pays again before currentPeriodEnd, and the new period starts from the current end date.
  • T-Bank with automatic renewal: the first checkout saves the card, and Tiergate charges it at each period end.
  • Polar: Polar charges renewals itself, and Tiergate mirrors the subscription.

6. Receive events

Tiergate can POST an event to your backend whenever a subscription changes. You then don’t need to poll. Open Webhooks in the console, enter your endpoint URL, and generate a signing secret (at least 24 characters). Copy the secret into your server’s secret storage before saving, because it can’t be shown again.

Each delivery is a JSON body with these headers:

Header Value
X-Billing-Signature t=<unix seconds>,v1=<hex HMAC-SHA256>
X-Billing-Event-Id Unique event ID
X-Billing-Event-Type Event type, for example subscription.renewed
{
  "eventId": "3c6f…",
  "eventType": "tenant.plan_changed",
  "occurredAt": "2026-11-04T10:12:03Z",
  "idempotencyKey": "yookassa:0b9e2f4a-…:payment.succeeded",
  "data": {
    "customerUuid": "6f1d4c1e-…",
    "tenantId": "user_8f2c",
    "orderId": "0b9e2f4a-…",
    "provider": "yookassa",
    "planId": "pro-monthly",
    "amount": 99000,
    "currency": "RUB",
    "subscriptionId": "…",
    "currentPeriodEnd": "2026-12-04T10:12:00Z"
  }
}

In data, tenantId is the customer’s externalId and planId is the plan key. The exact fields depend on the event type.

Verify the signature

Compute HMAC-SHA256 with your signing secret over <t>.<raw request body>, then compare it in constant time with v1. Reject timestamps more than five minutes old. Always use the raw body bytes: parsing and re-serialising the JSON changes them.

import crypto from "node:crypto";

export function verifyTiergateSignature(rawBody, header, secret) {
  const parts = Object.fromEntries(
    header.split(",").map((part) => part.trim().split("=")),
  );
  const timestamp = Number(parts.t);
  if (!timestamp || Math.abs(Date.now() / 1000 - timestamp) > 300) return false;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest("hex");
  const received = Buffer.from(parts.v1 ?? "", "utf8");
  const computed = Buffer.from(expected, "utf8");
  return (
    received.length === computed.length &&
    crypto.timingSafeEqual(received, computed)
  );
}

Respond, deduplicate, and re-read

  • Answer with any 2xx status quickly. Do slow work after responding.
  • Failed deliveries are retried after 30 seconds, 2 minutes, 10 minutes, and 30 minutes, up to five attempts in total.
  • A retried event keeps its eventId, so store processed IDs and ignore repeats.
  • Events can arrive out of order. Instead of applying an event’s data directly, re-read the subscription (step 5) and use that as the current state.

Event types

Event When
tenant.plan_changed A purchase activated a plan, or a full refund of the latest payment removed access.
subscription.renewed A same-plan payment extended the current period.
subscription.cancellation_scheduled The subscription will end at the period end.
subscription.reactivated A scheduled cancellation was withdrawn.
subscription.expired The period ended without payment, and the customer is back on free.
subscription.renewal_upcoming T-Bank automatic renewal: the card will be charged in about a day. Use this to notify the customer, which T-Bank requires.
subscription.past_due T-Bank automatic renewal: the charge was declined and will be retried.
subscription.renewal_stopped T-Bank automatic renewal: renewal was stopped (for example the price changed), so the subscription will lapse at period end.

7. Let customers manage their subscription

These calls back a billing page in your app. Each one returns the updated subscription:

# Cancel at the end of the paid period. Access lasts until then.
curl -X POST "$BASE/customers/$CUSTOMER_UUID/subscription/cancel" -H "Authorization: Bearer $TIERGATE_API_KEY"

# Undo a scheduled cancellation while the period is still running.
curl -X POST "$BASE/customers/$CUSTOMER_UUID/subscription/reactivate" -H "Authorization: Bearer $TIERGATE_API_KEY"

Here $BASE is the project endpoint prefix from Before you start. Both calls are safe to repeat. Once the period has ended they return 409 SUBSCRIPTION_NOT_ACTIVE.

When the subscription has providerPortal: true (Polar), POST $BASE/customers/$CUSTOMER_UUID/subscription/provider-portal returns a short-lived portalUrl to the provider’s own customer portal. Other providers return 409 UNSUPPORTED_BY_PROVIDER.

Go-live checklist

  • The API key is stored only on your server, with Read and write permission.
  • Customers are registered with a stable externalId, and customerUuid is saved.
  • Each checkout uses a fresh Idempotency-Key, and retries reuse it.
  • Access is granted from the subscription, never from the return URL alone.
  • CHECKOUT_UNRESOLVED never triggers a second checkout.
  • The event endpoint verifies signatures, deduplicates by eventId, and re-reads the subscription.
  • If you use T-Bank automatic renewal, subscription.renewal_upcoming notifies your customer.