Developer docs
17. Telvoro Premium, Stars and payments
On this page
Services: PaymentsService (payments.proto) and PremiumService (premium.proto). Money
never travels through the Telvoro protocol. A payment is one of three things:
- a store in-app purchase that the server verifies with the store;
- a card payment tokenised by the PSP’s own SDK;
- a hosted checkout page.
In every case the store/PSP notification (webhook) is the source of truth. A client
redirect or “success” callback only means “go and check”. Charging can be switched off
entirely: with no providers configured, GetPaymentOptions.enabled is false and premium
and Stars come only from the operator (admin API, §17.7).
17.1 Entitlement
An account is Premium while now < users.premium_until. That value is a cache of
premium_periods (one row per store/PSP subscription, renewed in place, or per one-off
grant), and only the server’s recomputePremium writes it. Every premium-dependent
decision in the server goes through one lookup (entOf / limitsOf, 5 s cache).
Handlers never test a premium flag themselves.
User.premium(the badge) is visible to everyone.User.premium_untilappears only on the self user.User.emoji_statusandUser.photo_videoare shown only while the owner is premium.ServerHello.config.limits/.premiumcarry the connection user’s effective limits.UserEvent.premium(aPremiumState) is pushed whenever the entitlement or the limits change: purchase, renewal, grace, expiry (announced exactly once by a sweeper), refund or operator grant.UserEvent.starsis pushed whenever the Stars balance changes.PremiumService/GetPremiumState: premium, until, source, auto_renew, in_grace, the effectivelimits, thefree_limitsandpremium_limits(for “X → Y” upsells), the perk ids and amanage_url.
Errors:
| Error | Meaning |
|---|---|
403 PREMIUM_ACCOUNT_REQUIRED, capability = perk id | the action is a premium perk |
(usual limit error), capability = limit:<UserLimits field> | e.g. PINNED_DIALOGS_TOO_MUCH with limit:pinned_chats. Set only when the user is free and Premium would raise the limit. Clients show an upsell instead of a dead end |
402 PAYMENT_REQUIRED, message = price | paid message (§17.2) |
400 BALANCE_TOO_LOW | not enough Stars |
403 STARS_DEBT | Stars spending blocked until a chargeback debt is repaid |
420 PURCHASE_FLOOD, retry_after | purchase velocity limit |
420 TRANSCRIPTION_QUOTA_EXCEEDED, capability voice_to_text | free weekly voice-to-text uses spent |
503 PAYMENTS_DISABLED / TRANSCRIPTION_UNAVAILABLE | no provider configured |
409 PURCHASE_ACCOUNT_MISMATCH | the store purchase belongs to another account |
400 RECEIPT_INVALID | the receipt failed verification; the client must not finish the store transaction |
17.2 Perks and limits
Limits (UserLimits; 0 = unlimited). Free values are today’s Telvoro defaults. Premium
values double them, as Telegram does: caption length goes to 4096 and file size to
4 GiB. Each value can be overridden in the config (limits.free, limits.premium).
| Limit | Free | Premium | Enforced in |
|---|---|---|---|
file_size | 2 GiB (TELEVO_MAX_FILE_SIZE) | 4 GiB | FilesService/CreateUpload |
folders | 20 | 40 | ChatsService/UpdateFolder |
chats_per_folder | 100 | 200 | folder include/pinned lists |
pinned_chats | 5 | 10 | UpdateDialog, ReorderPinnedDialogs |
pinned_in_folder (and archive) | 100 | 200 | same |
public_chats (owned public @usernames) | 10 | 20 | SetChatUsername |
channels_joined (groups + channels) | 500 | 1000 | join / join by link |
saved_gifs | 200 | 400 | reserved: Telvoro has no saved-GIFs list yet |
fave_stickers | 50 | 100 | FaveSticker (oldest trimmed) |
bio_length | 140 | 280 | UpdateProfile (bots: 512) |
caption_length | 1024 | 4096 | send, album, edit, scheduled edit, web-app answers |
download_speed | download_throttle_bps (default 0 = off) | unthrottled | FilesService/GetFile |
transcriptions_weekly | 2 | unlimited | TranscribeAudio |
Perk ids (PremiumState.perks, Error.capability):
| Perk | What it does |
|---|---|
double_limits | the table above |
faster_download | no download throttle |
voice_to_text | PremiumService/TranscribeAudio: voice notes and video notes. Provider pluggable (TELEVO_TRANSCRIBE_PROVIDER=openai, any OpenAI-compatible endpoint incl. self-hosted Whisper servers). Results are cached per message (sealed). Free users get transcriptions_weekly uses per rolling week. Clients may transcribe on device where the OS allows it and never call the server |
no_ads | entitlement only. Sponsored messages in channels are deferred (§17.9); premium accounts will not receive them |
chat_translation | turning on Dialog.auto_translate (whole-chat translation). Translating single messages stays free |
badge | User.premium |
emoji_status | PremiumService/SetEmojiStatus (a custom emoji id, optional until) |
premium_stickers | stickers and custom emoji from sticker sets flagged StickerSet.premium (the operator sets the flag) |
profile_video | SetProfilePhotoRequest.video_file_id (MP4 ≤ 10 MB, needs a photo) |
app_icons | client-side alternative app icons |
message_effects | SendMessageRequest.effect_id, effects from GetMessageEffects, private chats only. premium effects need Premium |
saved_tags | reactions used as tags in Saved Messages |
last_seen | reciprocity exemption. A free user who hides their own last seen (anything but EVERYBODY) sees others’ last seen only approximately (“recently”…). Premium users see exact times anyway |
message_privacy | PrivacySettings.new_chats: CONTACTS_AND_PREMIUM (others get 403 PRIVACY_PREMIUM_REQUIRED) or PAID, where non-contacts pay message_price_stars per message. The sender sets allow_paid_stars ≥ price, otherwise the send fails with 402 PAYMENT_REQUIRED. The charge goes to the recipient’s revenue and Message.paid_stars records it. The rule lapses when the recipient’s premium lapses |
Gifting Premium: pay with Stars (GiftPremium), or with money via
CreatePayment.gift_user_id (one-off months, never a subscription, only over the
methods routed to the platform). The recipient gets a PremiumGifted service message.
Gifts are gated. ServerConfig.payments_available is true when a payment provider is
configured. ServerConfig.gifts_enabled defaults to the same value; the payments config’s
gifts_enabled overrides it. While it is false, sending gifts fails with 403
GIFTS_UNAVAILABLE: GetStarGifts, SendStarGift, GiftPremium,
CreatePayment(gift_user_id) and the Bot API’s getAvailableGifts / sendGift
(“Forbidden: gifts unavailable”). Receiving is never gated: GetUserGifts and
ConvertStarGift keep working (the owner’s gifts privacy key decides who else sees the
list), and the operator can always give a gift (POST /admin/v1/users/{id}/gift). The
reference app also shows gift entry points only in official distribution builds
(TELEVO_OFFICIAL_BUILD).
17.3 Payment channels
GetPaymentOptions(platform, region) returns the methods for this client. The config’s
routes decide them: the most specific of platform + region, platform, or * wins.
Clients render exactly what is offered.
| Platform | Default methods | Notes |
|---|---|---|
| iOS / macOS | App Store (+ Stars) | external links (web_checkout) only where a route lists them for the region (e.g. US) |
| Android | Google Play, native card (+ Stars) | |
| web, Windows, Linux | web checkout, native card where the PSP SDK exists (+ Stars) |
In-app purchase (App Store / Google Play).
- The client passes
PaymentOptions.app_account_tokento the store: AppleappAccountToken, GoogleobfuscatedAccountId. The token is an HMAC of the account id and lets server notifications map back to the account. - After the purchase, the client sends
ConfirmIapPurchase:- Apple: the StoreKit 2 JWS (
jwsRepresentation) and the transaction id. - Google: the purchase token and the product id.
- Apple: the StoreKit 2 JWS (
- The server verifies the purchase:
- Apple: ES256 over the
x5cchain to the Apple Root CA G3, with Apple’s marker extensions on the leaf (1.2.840.113635.100.6.11.1) and the intermediate (…100.6.2.1). The bundle id and the environment must match. - Google:
purchases.subscriptionsv2.get/purchases.products.getwith the service account.
- Apple: ES256 over the
- The server binds the purchase to the account and delivers it. Google purchases are acknowledged (subscriptions) or consumed (Stars packs) server-side.
- The client finishes the store transaction only on
finish_transaction = true. RestorePurchasesre-submits what the store lists. Entitlement is per account, so every device of the account sees it (cross-device).
Renewals, grace periods and refunds arrive as webhooks:
- App Store Server Notifications v2 at
/v1/payments/webhook/apple. Handled:SUBSCRIBED,DID_RENEW,DID_FAIL_TO_RENEW/GRACE_PERIOD,GRACE_PERIOD_EXPIRED,EXPIRED,DID_CHANGE_RENEWAL_STATUS,REFUND,REVOKE,REFUND_REVERSED,ONE_TIME_CHARGE. - Google RTDN through a Pub/Sub push subscription at
/v1/payments/webhook/google, authenticated by the push’s OIDC token (service-account e-mail + audience) or a shared?token=. Notifications carry no state, so the server re-reads the purchase from the API.
In a grace period the account stays premium (in_grace) until the grace end. A late
EXPIRED for an older period never ends a renewed one. Family sharing: an Apple
FAMILY_SHARED subscription may be claimed by up to 5 further accounts
(family_sharing: false disables this).
Native card (Stripe PaymentSheet: card, Apple Pay, Google Pay).
CreatePayment(method = NATIVE_CARD)returnsclient_secret,customer_id,ephemeral_keyandpublishable_key. One-off purchases use a PaymentIntent; subscriptions use the first invoice of a Stripe Billing subscription (payment_behavior = default_incomplete).- The client presents the sheet. Card data stays inside the Stripe SDK (PCI SAQ-A).
payment_intent.succeeded/invoice.paidsettles the payment.
Web checkout. CreatePayment(method = WEB_CHECKOUT) returns a checkout_url
(Stripe Checkout, or any PSP behind the generic hosted adapter). The client opens it
in an in-app browser. The PSP returns to /v1/payments/return?payment=<id>, which
forwards to televo://payment?id=<id>&status=…. The client then polls GetPayment or
waits for UserEvent.premium / .stars.
Stars. CreatePayment(method = STARS) buys a premium product’s stars_price
immediately.
The provider abstraction is one Go interface (internal/payments.Provider: Checkout,
Verify, Webhook, Finish). Every adapter turns provider input into normalized
Events (purchase / subscribe / grace / expire / auto_renew / revoke / failed). The
service applies each event once: payment_events (provider, event_id) is recorded in
the same transaction as its effect, and each delivered charge is keyed by
(provider, transaction_id). A further PSP plugs in by config as a hosted provider:
a checkout URL template plus HMAC-signed webhooks
(X-Televo-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>).
17.4 Stars ledger
Stars are integers in a double-entry, append-only ledger (052_payments.sql).
ledger_txns(idem_key UNIQUE, charge_id UNIQUE, reverses UNIQUE)andledger_entries(txn_id, account, amount, available_at)cannot be updated or deleted (triggers).- A deferred constraint trigger requires every transaction’s entries to sum to 0.
ledger_accounts.balanceis changed only by the entry trigger. Direct writes raise.CHECK (allow_negative OR balance >= 0)covers user accounts. Two concurrent spends serialize on the account row, and the second fails withBALANCE_TOO_LOWinstead of overdrawing.
Accounts:
| Account | Holds |
|---|---|
user:<id> | spendable Stars |
debt:<id> | chargeback shortfall (≤ 0) |
rev:u:<id> | revenue of bots and of users who charge for messages |
rev:c:<id> | channel revenue |
sys:mint | Stars bought with money |
sys:grant | operator grants |
sys:fees | platform commission |
sys:premium | Stars spent on Premium |
sys:gifts | gift escrow |
sys:payout | withdrawn revenue |
LedgerAudit (admin GET /admin/v1/ledger/audit) checks four invariants: balances equal
the sum of their entries, every transaction balances, all balances sum to 0, and no
user account is negative.
| Flow | Entries |
|---|---|
| buy a pack | sys:mint −N, debt:u +min(N, debt), user:u +rest (a debt is repaid first) |
| spend (invoice, paid message, paid media, Star reaction) | user:u −N, payee rev:… +N·share (held for hold_days, via available_at), sys:fees +rest |
| premium / gift | user:u −N, sys:premium / sys:gifts +N. Converting a received gift: sys:gifts −c, user:r +c |
refund (refundStarPayment, rejected withdrawal) | the exact negation, reverses = original (at most once) |
| store/PSP refund or chargeback of a pack | sys:mint +N, user:u −min(N, balance), debt:u −rest. Spending is then blocked (STARS_DEBT) until the debt is repaid |
| withdrawal (stub) | rev:… −N, sys:payout +N, only from available (held-out) revenue, recorded for the operator |
Stars are non-transferable except as gifts. Every spend is idempotent by a
client-supplied random_id. Purchase and spend velocity are rate-limited per user
(purchases_per_hour, spends_per_minute).
Spending: GiftPremium / CreatePayment(STARS) (premium), SendStarGift,
SendMessage.allow_paid_stars (paid messages), PurchasePaidMedia,
SendPaidReaction (channels; shown as Reaction{emoji "⭐", paid, my_stars}) and bot
invoices. Revenue: GetRevenueStatus(owner) (a channel I own, a bot I own, or me) and
GetStarsTransactions(revenue_of).
Paid media (channels): InputMedia.paid_media { stars, media[], thumb }. The shared
message only carries PaidMediaInfo (price, count, blurred thumb). The real media is
stored apart, and its file ids leave the server only through PurchasePaidMedia (for
buyers and the channel’s admins).
17.5 Bot invoices and Bot API parity
Bots send an invoice with InputMedia.invoice (XTR only, exactly one price, payload
1–128 bytes) or create one with createInvoiceLink (https://<host>/invoice/<slug>,
which forwards to televo://invoice/<slug>). The payload is stored sealed, apart from
the shared message, so only the bot ever sees it.
- The user calls
GetInvoice(the form and whether they can pay), thenPayInvoice(idempotent perrandom_id). - The server enqueues
Update.pre_checkout_queryfor the bot and waits up to 10 s. - The bot answers with
AnswerPreCheckoutQuery/answerPreCheckoutQuery:- ok: the user’s Stars go to the bot’s revenue (
SpendStars), aPaymentSuccessfulservice message is posted from the user in their private chat with the bot, and the Bot API addsinvoice_payloadtosuccessful_payment. - error:
PayInvoicereturns FAILED with the bot’serror_message. - Unanswered checkouts fail after 30 s.
- ok: the user’s Stars go to the bot’s revenue (
Bot API methods: sendInvoice, createInvoiceLink, answerPreCheckoutQuery,
refundStarPayment (posts refunded_payment), getStarTransactions,
getMyStarBalance, getAvailableGifts, sendGift (paid from the bot’s own Stars). Updates: pre_checkout_query. Message fields: invoice,
successful_payment, refunded_payment. Inline keyboards accept pay buttons (the
default keyboard of sendInvoice is one “Pay ⭐️N” button).
Physical goods (provider_token, real currencies) are not supported:
CURRENCY_INVALID / PROVIDER_TOKEN_INVALID (deferred, §17.9).
17.6 Webhooks
POST /v1/payments/webhook/{provider} (public listener), body ≤ 1 MiB, rate-limited per
provider and IP. The adapter authenticates first:
- Apple: the JWS chain;
- Google: OIDC or the shared token;
- Stripe:
Stripe-Signature, HMAC-SHA256, 5-minute tolerance; - hosted:
X-Televo-Signature.
Unauthenticated → 400, never applied. Responses:
- applied, or a known duplicate → 200;
- transient error → 500, and the provider retries;
- a well-formed event the server refuses (e.g. a receipt owned by another account) → 200, logged.
PSP amounts are checked against the server’s own payment record (product, amount, currency), never against client or metadata claims.
17.7 Operator (admin API)
All on the admin listener, audit-logged:
| Endpoint | Body / effect |
|---|---|
GET /admin/v1/users/{id}/premium | premium state and Stars status |
POST /admin/v1/users/{id}/premium | {months, days, ref} grants (idempotent by ref); {revoke: true} ends all periods |
POST /admin/v1/users/{id}/stars | {stars, key, note}: an idempotent grant or (negative) correction from sys:grant |
GET /admin/v1/payments?user_id= | payments |
GET /admin/v1/ledger/audit | the ledger invariant check |
POST /admin/v1/users/{id}/gift | {gift_id, text, key}: a gift from the operator (paid from sys:grant), works with gifts switched off |
POST /admin/v1/withdrawals/{id} | {paid}; a rejection reverses the withdrawal |
POST /admin/v1/stickersets/{id}/premium | {premium} |
This works with zero credentials, so premium and Stars can be run without any provider.
17.8 Configuration
TELEVO_PAYMENTS_CONFIG holds a JSON file path or inline JSON, parsed strictly (unknown
fields are refused). Secrets are never inline: *_env names an environment variable,
*_file a file.
{
"products": [
{"id": "premium_1m", "kind": "premium", "months": 1, "subscription": true, "amount": 499, "currency": "USD",
"stars_price": 1000, "stripe_price": "price_…", "store_ids": {"apple": "org.televo.premium.1m", "google": "premium_1m"}},
{"id": "stars_250", "kind": "stars", "stars": 250, "amount": 499, "currency": "USD",
"store_ids": {"apple": "org.televo.stars.250", "google": "stars_250"}}
],
"routes": [
{"platform": "ios", "methods": ["app_store", "stars"]},
{"platform": "ios", "regions": ["US"], "methods": ["app_store", "web_checkout", "stars"]},
{"platform": "android", "methods": ["google_play", "native_card", "stars"]},
{"platform": "*", "methods": ["web_checkout", "native_card", "stars"], "providers": {"web_checkout": "stripe"}}
],
"providers": {
"apple": {"bundle_id": "org.televo.app", "app_apple_id": 123, "environment": "Production"},
"google": {"package_name": "org.televo.app", "service_account_file": "/etc/televo/play.json",
"rtdn_audience": "https://chat.example.org/v1/payments/webhook/google", "rtdn_service_account": "[email protected]"},
"stripe": {"secret_key_env": "STRIPE_SECRET_KEY", "webhook_secret_env": "STRIPE_WEBHOOK_SECRET", "publishable_key": "pk_live_…",
"merchant_name": "Televo", "merchant_country": "US", "apple_merchant_id": "merchant.org.televo", "google_pay": true,
"portal_url": "https://billing.stripe.com/p/login/…"},
"acme": {"type": "hosted", "checkout_url": "https://pay.acme/c?ref={payment_id}&amount={amount}&cur={currency}&return={return_url}",
"webhook_secret_env": "ACME_WEBHOOK_SECRET"}
},
"stars": {"hold_days": 21, "revenue_share_bp": 7000, "purchases_per_hour": 10, "max_stars_per_day": 100000,
"spends_per_minute": 60, "withdrawal_enabled": false, "min_withdrawal": 1000},
"gifts": [{"id": 1, "stars": 15, "convert_stars": 13, "emoji": "🧸"}],
"effects": [{"id": 4, "emoji": "🔥"}, {"id": 7, "emoji": "🤯", "premium": true}],
"limits": {"free": {"folders": 10}, "premium": {"folders": 20}},
"download_throttle_bps": 0,
"transcribe_free_weekly": 2,
"family_sharing": true,
"gifts_enabled": null
}
Without routes, every configured method is offered by platform (iOS/macOS: App Store;
Android: Play + card; others: web checkout). Transcription is configured with
TELEVO_TRANSCRIBE_PROVIDER=openai, TELEVO_TRANSCRIBE_URL, TELEVO_TRANSCRIBE_KEY and
TELEVO_TRANSCRIBE_MODEL.
17.9 Deferred
- Sponsored messages in channels (and their
no_adssuppression). - Physical goods via
provider_tokenand real-currency bot invoices. - Real payouts (Fragment/TON-like withdrawals); withdrawals are a recorded stub.
- Saved GIFs (no list exists yet; the limit is reserved).
- HTTP signed-URL downloads aren’t throttled (only
GetFile). - Apple consumption-request answers (
CONSUMPTION_REQUEST). - App Store Server API calls (only offline JWS verification is used), so StoreKit 1 receipts aren’t accepted.
- Price localisation per storefront for card/web prices (store prices come from the stores).
- Star subscriptions to channels, giveaways, gift upgrades/collectibles.
- Payment ids are per-DC sequences (payments stay on the account’s home DC).
Generated from docs/PROTOCOL.md in the Telvoro repository. Wire names such as televo.v1 are unchanged.