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
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:
@@ -0,0 +1,104 @@
|
||||
// Package outbox is the Telegram Stars payment outbox: a small SQLite store on the bot host's
|
||||
// writable volume that durably records each completed Stars payment the moment Telegram delivers it,
|
||||
// so a gateway or backend outage cannot lose it. The bot forwards pending rows to the gateway and
|
||||
// marks them delivered; rows still undelivered are re-driven on restart. It is pure-Go SQLite
|
||||
// (modernc.org/sqlite, no CGO) so it runs on the distroless image.
|
||||
package outbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Record is one completed Stars payment awaiting delivery to the gateway.
|
||||
type Record struct {
|
||||
// ChargeID is the telegram_payment_charge_id — the primary key here and the credit idempotency
|
||||
// key at the backend, so a re-delivered or retried payment is never credited twice.
|
||||
ChargeID string
|
||||
// OrderID is the invoice payload (our order id) the payment settles.
|
||||
OrderID string
|
||||
// Amount is the stars paid (the XTR minor unit is the whole star).
|
||||
Amount int64
|
||||
// UserID is the payer's Telegram user id.
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// Store is the SQLite-backed payment outbox.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// Open opens (creating if absent) the outbox database at path and ensures its schema. The parent
|
||||
// directory must exist and be writable by the container user.
|
||||
func Open(path string) (*Store, error) {
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("outbox: open %s: %w", path, err)
|
||||
}
|
||||
// A single connection serialises writes and sidesteps SQLite's "database is locked" under the
|
||||
// bot's low, bursty payment volume.
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS stars_payments (
|
||||
charge_id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
amount INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
forwarded INTEGER NOT NULL DEFAULT 0
|
||||
)`); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("outbox: init schema: %w", err)
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
// Close closes the database.
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// Add records a completed payment. It is idempotent on the charge id: a payment Telegram re-delivers
|
||||
// (or one already recorded and forwarded) is ignored, so it is never forwarded — and credited —
|
||||
// twice.
|
||||
func (s *Store) Add(ctx context.Context, r Record) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO stars_payments (charge_id, order_id, amount, user_id, created_at, forwarded)
|
||||
VALUES (?, ?, ?, ?, ?, 0)
|
||||
ON CONFLICT(charge_id) DO NOTHING`,
|
||||
r.ChargeID, r.OrderID, r.Amount, r.UserID, time.Now().Unix())
|
||||
if err != nil {
|
||||
return fmt.Errorf("outbox: add %s: %w", r.ChargeID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pending returns up to limit payments not yet forwarded, oldest first.
|
||||
func (s *Store) Pending(ctx context.Context, limit int) ([]Record, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT charge_id, order_id, amount, user_id FROM stars_payments
|
||||
WHERE forwarded = 0 ORDER BY created_at LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("outbox: read pending: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Record
|
||||
for rows.Next() {
|
||||
var r Record
|
||||
if err := rows.Scan(&r.ChargeID, &r.OrderID, &r.Amount, &r.UserID); err != nil {
|
||||
return nil, fmt.Errorf("outbox: scan: %w", err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MarkForwarded flags a payment as delivered so it is not forwarded again.
|
||||
func (s *Store) MarkForwarded(ctx context.Context, chargeID string) error {
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`UPDATE stars_payments SET forwarded = 1 WHERE charge_id = ?`, chargeID); err != nil {
|
||||
return fmt.Errorf("outbox: mark forwarded %s: %w", chargeID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package outbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// openTemp opens a fresh outbox in a temp dir.
|
||||
func openTemp(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := Open(filepath.Join(t.TempDir(), "stars.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestOutboxAddPendingMark(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := openTemp(t)
|
||||
|
||||
rec := Record{ChargeID: "ch1", OrderID: "ord1", Amount: 40, UserID: 777}
|
||||
if err := s.Add(ctx, rec); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
pending, err := s.Pending(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if len(pending) != 1 || pending[0] != rec {
|
||||
t.Fatalf("pending = %+v, want [%+v]", pending, rec)
|
||||
}
|
||||
|
||||
if err := s.MarkForwarded(ctx, "ch1"); err != nil {
|
||||
t.Fatalf("mark: %v", err)
|
||||
}
|
||||
pending, err = s.Pending(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pending after mark: %v", err)
|
||||
}
|
||||
if len(pending) != 0 {
|
||||
t.Fatalf("pending after mark = %+v, want empty", pending)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboxAddIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := openTemp(t)
|
||||
|
||||
rec := Record{ChargeID: "dup", OrderID: "ord1", Amount: 80, UserID: 1}
|
||||
if err := s.Add(ctx, rec); err != nil {
|
||||
t.Fatalf("add 1: %v", err)
|
||||
}
|
||||
// A re-delivered payment (same charge id) must not add a second row, even with different fields.
|
||||
if err := s.Add(ctx, Record{ChargeID: "dup", OrderID: "other", Amount: 999, UserID: 2}); err != nil {
|
||||
t.Fatalf("add 2: %v", err)
|
||||
}
|
||||
pending, err := s.Pending(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if len(pending) != 1 || pending[0] != rec {
|
||||
t.Fatalf("pending = %+v, want the single original row", pending)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboxAddIgnoresForwarded(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := openTemp(t)
|
||||
|
||||
rec := Record{ChargeID: "ch", OrderID: "o", Amount: 40, UserID: 5}
|
||||
if err := s.Add(ctx, rec); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
if err := s.MarkForwarded(ctx, "ch"); err != nil {
|
||||
t.Fatalf("mark: %v", err)
|
||||
}
|
||||
// A re-delivery after forwarding must not resurrect the row as pending (no double credit).
|
||||
if err := s.Add(ctx, rec); err != nil {
|
||||
t.Fatalf("re-add: %v", err)
|
||||
}
|
||||
pending, err := s.Pending(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if len(pending) != 0 {
|
||||
t.Fatalf("pending = %+v, want empty (already forwarded)", pending)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOutboxReopenReDrives proves a restart re-drives undelivered payments: a payment persisted but
|
||||
// not marked forwarded is still pending after the store is reopened from the same file.
|
||||
func TestOutboxReopenReDrives(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "stars.db")
|
||||
|
||||
s, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
rec := Record{ChargeID: "persist", OrderID: "o1", Amount: 40, UserID: 9}
|
||||
if err := s.Add(ctx, rec); err != nil {
|
||||
t.Fatalf("add: %v", err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
|
||||
reopened, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen: %v", err)
|
||||
}
|
||||
defer func() { _ = reopened.Close() }()
|
||||
pending, err := reopened.Pending(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if len(pending) != 1 || pending[0] != rec {
|
||||
t.Fatalf("pending after reopen = %+v, want the undelivered payment", pending)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user