feat(payments): Telegram Stars payment rail
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 22s
CI / integration (pull_request) Successful in 20s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m57s

Accept real money via Telegram Stars (XTR) — the third intake rail
alongside Robokassa (direct) and VK Votes.

Only the bot reaches Telegram, so the rail funnels through the reverse
mTLS bot-link:
- the gateway mints the invoice on a CreateInvoice command (the bot
  calls createInvoiceLink, XTR; the link goes to WebApp.openInvoice);
- the bot gates each pre_checkout_query via a ValidatePreCheckout unary
  (the order must exist, be still creditable and not already paid — the
  reusable-invoice double-pay guard; the decline reason is localised to
  the order account's language);
- a completed successful_payment is queued in a durable pure-Go SQLite
  outbox and forwarded via a ForwardPayment unary, credited once
  (idempotent on telegram_payment_charge_id, honours an expired order),
  re-driven on restart and every 30s.

The rail is wired by TELEGRAM_STARS_OUTBOX_DIR (default /data) but stays
inert until a chip pack carries an XTR price, so seeding a Stars price in
the admin is the go-live.

Tests: backend integration (order->forward->credit once, duplicate,
pre_checkout gate) + bot outbox unit (idempotent, restart re-drive) +
executor createInvoice. Docs: PAYMENTS(+ru) §9, ARCHITECTURE, the
platform/telegram README, PLAN.
This commit is contained in:
Ilia Denisov
2026-07-09 21:35:29 +02:00
parent 5612bb624d
commit 6e03ce0131
32 changed files with 1830 additions and 94 deletions
+120
View File
@@ -13,6 +13,7 @@ import (
"strconv"
"sync"
"sync/atomic"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
@@ -31,6 +32,11 @@ var ErrNoBot = errors.New("botlink: no bot connected")
// (at-most-once under backpressure).
const outboundBuffer = 64
// invoiceMintTimeout bounds one synchronous invoice-mint round-trip (the gateway commands the bot
// and awaits the Ack carrying the createInvoiceLink result), so a hung or slow bot cannot stall the
// caller's wallet-order request indefinitely.
const invoiceMintTimeout = 15 * time.Second
// EligibilityResolver answers a Telegram identity's moderated-chat write eligibility
// for the bot's join-time ResolveChatEligibility query: registered reports whether the
// identity maps to an account, eligible is the final gate the bot acts on (registered
@@ -38,6 +44,17 @@ const outboundBuffer = 64
// chat-access endpoint.
type EligibilityResolver func(ctx context.Context, externalID string) (registered, eligible bool, err error)
// PreCheckoutResolver validates a Telegram Stars pre_checkout_query for the bot's
// ValidatePreCheckout query: it answers whether the order may still be charged (ok) and, when not,
// a short reason to show the payer. The gateway backs it with the backend intake.
type PreCheckoutResolver func(ctx context.Context, orderID string, amount int64, currency string) (ok bool, reason string, err error)
// PaymentForwarder delivers a completed Telegram Stars payment for the bot's ForwardPayment call:
// it credits the order through the backend intake and reports whether it was credited (or already
// had been). A non-nil error is a transient failure the bot retries. The gateway backs it with the
// backend intake.
type PaymentForwarder func(ctx context.Context, orderID, chargeID string, amount, telegramUserID int64) (credited bool, err error)
// Hub registers connected bots and routes send commands to them. A single bot is
// expected today; the registry already holds a set so adding more later needs no
// rewrite.
@@ -46,6 +63,10 @@ type Hub struct {
log *zap.Logger
eligibility EligibilityResolver
// precheck and forward back the Telegram Stars payment RPCs; nil until SetPaymentBridge wires
// them, in which case the RPCs report Unavailable. Set once before the gRPC server serves.
precheck PreCheckoutResolver
forward PaymentForwarder
mu sync.Mutex
links map[*link]struct{}
@@ -147,6 +168,105 @@ func (h *Hub) ResolveChatEligibility(ctx context.Context, req *botlinkv1.ChatEli
return &botlinkv1.ChatEligibilityResponse{Registered: registered, Eligible: eligible}, nil
}
// SetPaymentBridge wires the Telegram Stars payment resolvers, backing ValidatePreCheckout and
// ForwardPayment. It must be called before the gRPC server starts serving (the fields are read
// without a lock, relying on that happens-before). A nil resolver leaves its RPC reporting
// Unavailable.
func (h *Hub) SetPaymentBridge(precheck PreCheckoutResolver, forward PaymentForwarder) {
h.precheck = precheck
h.forward = forward
}
// ValidatePreCheckout serves the bot's pre_checkout validation over the same mTLS channel: it
// delegates to the configured resolver (the backend intake) and returns whether the order may be
// charged. A resolver failure maps to Internal, which the bot treats as a decline (fail-closed).
func (h *Hub) ValidatePreCheckout(ctx context.Context, req *botlinkv1.PreCheckoutRequest) (*botlinkv1.PreCheckoutResponse, error) {
if h.precheck == nil {
return nil, status.Error(codes.Unavailable, "payment bridge not configured")
}
ok, reason, err := h.precheck(ctx, req.GetOrderId(), req.GetAmount(), req.GetCurrency())
if err != nil {
h.log.Warn("validate pre_checkout failed", zap.String("order", req.GetOrderId()), zap.Error(err))
return nil, status.Error(codes.Internal, "validate pre_checkout")
}
return &botlinkv1.PreCheckoutResponse{Ok: ok, Reason: reason}, nil
}
// ForwardPayment serves the bot's completed-payment delivery: it credits the order through the
// configured forwarder (the backend intake) and reports the durable outcome. A forwarder failure
// maps to Internal, which the bot treats as transient and retries; a clean response (credited true
// or false) lets the bot forget the outbox row.
func (h *Hub) ForwardPayment(ctx context.Context, req *botlinkv1.ForwardPaymentRequest) (*botlinkv1.ForwardPaymentResponse, error) {
if h.forward == nil {
return nil, status.Error(codes.Unavailable, "payment bridge not configured")
}
credited, err := h.forward(ctx, req.GetOrderId(), req.GetTelegramPaymentChargeId(), req.GetAmount(), req.GetTelegramUserId())
if err != nil {
h.log.Warn("forward telegram payment failed", zap.String("order", req.GetOrderId()), zap.Error(err))
return nil, status.Error(codes.Internal, "forward payment")
}
return &botlinkv1.ForwardPaymentResponse{Credited: credited}, nil
}
// MintInvoice commands the connected bot to mint a Telegram Stars invoice link for the order and
// returns the link. It is a bounded, synchronous round-trip (invoiceMintTimeout): no bot connected
// returns ErrNoBot, and a bot error or an empty link is an error the caller surfaces as a failed
// order launch.
func (h *Hub) MintInvoice(ctx context.Context, title, description, orderID string, amountStars int64) (string, error) {
cctx, cancel := context.WithTimeout(ctx, invoiceMintTimeout)
defer cancel()
ack, err := h.sendAwaitAck(cctx, CreateInvoiceCommand(title, description, orderID, amountStars))
if err != nil {
return "", err
}
if ack.GetResult() == "" {
return "", errors.New("botlink: bot returned an empty invoice link")
}
return ack.GetResult(), nil
}
// sendAwaitAck enqueues a command and waits for the bot's full Ack (or ctx). It mirrors SendAwait
// but returns the Ack — the invoice-mint path needs its result field — and reports ctx expiry as an
// error rather than a not-delivered, since a timed-out mint has no link to return.
func (h *Hub) sendAwaitAck(ctx context.Context, cmd *botlinkv1.Command) (*botlinkv1.Ack, error) {
l, ok := h.pick()
if !ok {
h.count("dropped")
return nil, ErrNoBot
}
id := h.nextID()
cmd.CommandId = id
ackc := make(chan *botlinkv1.Ack, 1)
h.mu.Lock()
h.pending[id] = ackc
h.mu.Unlock()
defer func() {
h.mu.Lock()
delete(h.pending, id)
h.mu.Unlock()
}()
select {
case l.out <- &botlinkv1.ToBot{Command: cmd}:
case <-ctx.Done():
h.count("dropped")
return nil, ctx.Err()
}
select {
case ack := <-ackc:
if e := ack.GetError(); e != "" {
h.count("error")
return nil, errors.New(e)
}
h.count(deliveredLabel(ack.GetDelivered()))
return ack, nil
case <-ctx.Done():
h.count("error")
return nil, ctx.Err()
}
}
// register adds a connected bot.
func (h *Hub) register(l *link) {
h.mu.Lock()