Phase 4: Telegram Stars payments

- Stars as a second payment method for passes and credit packs, next to
  Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set
  on their own). Invoices in XTR with no provider token and one price;
  pre-checkout checks payer, state, currency and amount;
  successful_payment settles through the same transaction as Lightning,
  so entitlement is identical. Idempotent by telegram_payment_charge_id
  (unique index).
- Migration 00009: payment_method on purchases and ledger entries, plus
  stars_amount, tg_charge_id and refunded_at on purchases. Stars
  purchases never reach LNbits.
- Chat: buy screen, /credits, /account and the over-limit offer show
  Lightning first and a Pay with Stars button.
- Mini App: Lightning and Stars switch on Buy; Stars use
  createInvoiceLink and WebApp.openInvoice, confirmed by the server-side
  payment event.
- Owner /refund <purchase or charge ID> calls refundStarPayment and takes
  back the credits or pass; refunded_payment messages do the same once.
  /stats shows revenue by payment method.
- The sats referral reward counts Lightning purchases only.
- The bot now asks Telegram for pre_checkout_query updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 21:20:03 +00:00
co-authored by Claude Opus 5.5
parent f7ceadc462
commit 2b5625e9d4
37 changed files with 1915 additions and 114 deletions
+106 -12
View File
@@ -117,9 +117,13 @@ func (s *Store) AddLedger(ctx context.Context, e *LedgerEntry) (applied bool, er
if e.CreatedAt == 0 {
e.CreatedAt = NowMilli()
}
if e.PaymentMethod == "" {
e.PaymentMethod = PayLightning
}
_, err = s.exec(ctx, `INSERT INTO ledger (id, wallet_id, kind, amount, balance_after, reason, ref,
dedupe_key, actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt)
dedupe_key, actor_id, created_at, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt,
e.PaymentMethod)
if isUniqueViolation(err) {
// Lost a race against the same key on another connection. The
// surrounding transaction must roll back, which undoes the balance.
@@ -171,7 +175,7 @@ func (s *Store) VerifyWallets(ctx context.Context) ([]WalletMismatch, error) {
// ListLedger returns the newest entries of a wallet.
func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*LedgerEntry, error) {
rows, err := s.rows(ctx, `SELECT id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key,
actor_id, created_at FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`,
actor_id, created_at, payment_method FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`,
walletID, limit)
if err != nil {
return nil, err
@@ -181,7 +185,7 @@ func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*
for rows.Next() {
var e LedgerEntry
if err := rows.Scan(&e.ID, &e.WalletID, &e.Kind, &e.Amount, &e.BalanceAfter, &e.Reason, &e.Ref,
&e.DedupeKey, &e.ActorID, &e.CreatedAt); err != nil {
&e.DedupeKey, &e.ActorID, &e.CreatedAt, &e.PaymentMethod); err != nil {
return nil, err
}
out = append(out, &e)
@@ -237,13 +241,14 @@ func (s *Store) ExtendPass(ctx context.Context, walletID string, lengthMS, now i
const purchaseCols = `id, user_id, wallet_id, product, amount_sats, status, payment_hash, bolt11, chat_id,
message_id, message_is_photo, lang, request_id, profile, delivery_id, fulfilled, created_at,
expires_at, paid_at`
expires_at, paid_at, payment_method, stars_amount, tg_charge_id, refunded_at`
func scanPurchase(sc interface{ Scan(...any) error }) (*Purchase, error) {
var p Purchase
err := sc.Scan(&p.ID, &p.UserID, &p.WalletID, &p.Product, &p.AmountSats, &p.Status, &p.PaymentHash,
&p.Bolt11, &p.ChatID, &p.MessageID, &p.MessageIsPhoto, &p.Lang, &p.RequestID, &p.Profile,
&p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt)
&p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt,
&p.PaymentMethod, &p.StarsAmount, &p.ChargeID, &p.RefundedAt)
if err != nil {
return nil, notFound(err)
}
@@ -268,11 +273,14 @@ func scanPurchases(rows *sql.Rows, err error) ([]*Purchase, error) {
// InsertPurchase stores a new purchase.
func (s *Store) InsertPurchase(ctx context.Context, p *Purchase) error {
if p.PaymentMethod == "" {
p.PaymentMethod = PayLightning
}
_, err := s.exec(ctx, `INSERT INTO purchases (`+purchaseCols+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.ID, p.UserID, p.WalletID, p.Product, p.AmountSats, p.Status, p.PaymentHash, p.Bolt11, p.ChatID,
p.MessageID, p.MessageIsPhoto, p.Lang, p.RequestID, p.Profile, p.DeliveryID, p.Fulfilled,
p.CreatedAt, p.ExpiresAt, p.PaidAt)
p.CreatedAt, p.ExpiresAt, p.PaidAt, p.PaymentMethod, p.StarsAmount, p.ChargeID, p.RefundedAt)
return err
}
@@ -322,7 +330,8 @@ func (s *Store) SetPurchaseMessage(ctx context.Context, id string, chatID, messa
// arrive in the moment an invoice expires or is cancelled.
func (s *Store) UnsettledPurchases(ctx context.Context, closedAfter int64, limit int) ([]*Purchase, error) {
return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases
WHERE status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?)
WHERE payment_method = 'lightning'
AND (status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?))
ORDER BY created_at LIMIT ?`, closedAfter, limit))
}
@@ -333,13 +342,18 @@ func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Pur
WHERE status = 'paid' AND fulfilled = ? ORDER BY paid_at LIMIT ?`, false, limit))
}
// CountPaidPurchases counts the paid purchases of a user, donations aside.
// CountReferralPurchases counts the settled purchases of a user that our
// referral program looks at: everything but donations, paid in sats.
// referral program looks at: everything but donations, paid over
// Lightning.
func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) {
return s.CountPaidPurchases(ctx, userID)
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status IN ('paid', 'refunded')
AND product <> 'donation' AND payment_method = 'lightning'`, userID).Scan(&n)
return n, err
}
// CountPaidPurchases counts the paid purchases of a user, donations aside.
func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid'
@@ -431,3 +445,83 @@ func (s *Store) UseGiftCode(ctx context.Context, code string, userID, now int64)
}
return err == nil, err
}
// SetPurchaseCharge records Telegram's charge ID of a Stars payment. The
// unique index makes a second purchase with the same charge fail with
// ErrDuplicate.
func (s *Store) SetPurchaseCharge(ctx context.Context, id, chargeID string) error {
_, err := s.exec(ctx, `UPDATE purchases SET tg_charge_id = ? WHERE id = ? AND tg_charge_id = ''`, chargeID, id)
if isUniqueViolation(err) {
return ErrDuplicate
}
return err
}
// GetPurchaseByCharge finds a Stars purchase by Telegram's charge ID.
func (s *Store) GetPurchaseByCharge(ctx context.Context, chargeID string) (*Purchase, error) {
if chargeID == "" {
return nil, ErrNotFound
}
return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE tg_charge_id = ?`, chargeID))
}
// MarkPurchaseRefunded moves a paid Stars purchase to refunded. It
// reports false when it was not paid, so a refund is undone once.
func (s *Store) MarkPurchaseRefunded(ctx context.Context, id string, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE purchases SET status = 'refunded', refunded_at = ?
WHERE id = ? AND status = 'paid' AND payment_method = 'stars'`, now, id)
return n == 1, err
}
// RemovePassesFrom deletes the passes a purchase granted, for a refund,
// and moves later passes of the wallet back by the time they lose.
func (s *Store) RemovePassesFrom(ctx context.Context, walletID, source string) (int64, error) {
var start, end sql.NullInt64
if err := s.row(ctx, `SELECT MIN(starts_at), MAX(expires_at) FROM passes WHERE wallet_id = ? AND source = ?`,
walletID, source).Scan(&start, &end); err != nil || !start.Valid {
return 0, err
}
n, err := s.exec(ctx, `DELETE FROM passes WHERE wallet_id = ? AND source = ?`, walletID, source)
if err != nil || n == 0 {
return n, err
}
// Passes that were stacked after the refunded one start earlier now.
length := end.Int64 - start.Int64
_, err = s.exec(ctx, `UPDATE passes SET starts_at = starts_at - ?, expires_at = expires_at - ?
WHERE wallet_id = ? AND starts_at >= ?`, length, length, walletID, end.Int64)
return n, err
}
// Revenue is what one payment method brought in.
type Revenue struct {
Method string
Purchases int
Sats int64 // Lightning: sats received
Stars int64 // Stars: Stars received, refunds excluded
Refunded int
}
// RevenueByMethod sums settled purchases per payment method since a
// moment (0 for all time). Refunded Stars purchases are counted apart.
func (s *Store) RevenueByMethod(ctx context.Context, since int64) ([]Revenue, error) {
rows, err := s.rows(ctx, `SELECT payment_method,
COALESCE(SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'lightning' THEN amount_sats ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'stars' THEN stars_amount ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END), 0)
FROM purchases WHERE status IN ('paid', 'refunded') AND paid_at >= ?
GROUP BY payment_method ORDER BY payment_method`, since)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Revenue
for rows.Next() {
var r Revenue
if err := rows.Scan(&r.Method, &r.Purchases, &r.Sats, &r.Stars, &r.Refunded); err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}