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
+206
View File
@@ -0,0 +1,206 @@
package billing
import (
"context"
"errors"
"strings"
"time"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/ids"
)
// Telegram Stars are the second way to pay, next to Lightning, for passes
// and credit packs. Their prices are set on their own (StarsPrices), never
// converted from sats. A Stars purchase grants exactly what the same
// Lightning purchase grants, through the same settlement, so entitlement
// does not care how something was paid.
//
// The flow is Telegram's: the bot sends an invoice in XTR (or makes an
// invoice link for the Mini App), Telegram asks the bot to confirm with a
// pre-checkout query, takes the Stars, and sends a message with a
// successful_payment. Its telegram_payment_charge_id is stored with the
// purchase under a unique index, so a repeated event settles nothing twice.
// Errors of Stars payments.
var (
ErrStarsOff = errors.New("billing: stars payments are off")
ErrNotForStars = errors.New("billing: this is not sold for stars")
ErrStarsMismatch = errors.New("billing: the payment does not match the invoice")
ErrInvoiceClosed = errors.New("billing: the invoice is closed")
ErrUnknownCharge = errors.New("billing: unknown payment")
)
// StarsPayloadPrefix starts the invoice payload of a Stars purchase.
const StarsPayloadPrefix = "dlp:"
// starsInvoiceLife is how long a Stars purchase is shown as open. Telegram
// invoices do not expire, so a payment that comes later still settles.
const starsInvoiceLife = 24 * time.Hour
// StarsEnabled reports whether Stars are offered.
func (b *Billing) StarsEnabled() bool { return b.cfg.StarsEnabled }
// Selling reports whether anything can be bought, by either method.
func (b *Billing) Selling() bool { return b.Enabled() || b.StarsEnabled() }
// StarsPrice returns the price in Stars of a product, or false when it is
// not sold for Stars.
func (b *Billing) StarsPrice(product string, amount int64) (int64, bool) {
if !b.StarsEnabled() {
return 0, false
}
switch {
case passKind(product) != "":
return b.cfg.StarsPrice(product, 0)
case product == ProductCredits:
return b.cfg.StarsPrice(product, amount)
}
return 0, false
}
// StarsPayload is the invoice payload of a Stars purchase.
func StarsPayload(p *db.Purchase) string { return StarsPayloadPrefix + p.ID }
// CreateStarsPurchase records a purchase to be paid in Stars. The caller
// sends the invoice. amount_sats keeps the sats value of what is bought:
// the credit pack, or the pass's Lightning price, for the books.
func (b *Billing) CreateStarsPurchase(ctx context.Context, np NewPurchase) (*db.Purchase, error) {
if !b.StarsEnabled() {
return nil, ErrStarsOff
}
stars, ok := b.StarsPrice(np.Product, np.Amount)
if !ok {
return nil, ErrNotForStars
}
sats, err := b.Price(np.Product, np.Amount)
if err != nil {
return nil, err
}
now := b.nowMilli()
id := ids.New()
p := &db.Purchase{
ID: id, UserID: np.UserID, WalletID: np.WalletID, Product: np.Product, AmountSats: sats,
Status: db.PurchasePending, PaymentHash: "stars:" + id, Lang: np.Lang,
RequestID: np.RequestID, Profile: np.Profile, DeliveryID: np.DeliveryID,
CreatedAt: now, ExpiresAt: now + starsInvoiceLife.Milliseconds(),
PaymentMethod: db.PayStars, StarsAmount: stars,
}
if err := b.store.InsertPurchase(ctx, p); err != nil {
return nil, err
}
b.log.Info("stars invoice created", "purchase_id", p.ID, "product", p.Product, "stars", stars, "user_id", np.UserID)
return p, nil
}
// starsPurchase finds the purchase an invoice payload names, for its payer.
func (b *Billing) starsPurchase(ctx context.Context, payload string, userID int64) (*db.Purchase, error) {
id, ok := strings.CutPrefix(payload, StarsPayloadPrefix)
if !ok {
return nil, ErrUnknownCharge
}
p, err := b.store.GetPurchase(ctx, id)
if errors.Is(err, db.ErrNotFound) {
return nil, ErrUnknownCharge
}
if err != nil {
return nil, err
}
if p.PaymentMethod != db.PayStars || p.UserID != userID {
return nil, ErrUnknownCharge
}
return p, nil
}
// PreCheckStars decides a pre-checkout query: Telegram is about to take
// the Stars and asks whether the order still stands.
func (b *Billing) PreCheckStars(ctx context.Context, payload string, userID int64, currency string, total int64) error {
p, err := b.starsPurchase(ctx, payload, userID)
if err != nil {
return err
}
if currency != "XTR" || total != p.StarsAmount {
return ErrStarsMismatch
}
if p.Status != db.PurchasePending {
return ErrInvoiceClosed
}
return nil
}
// SettleStars settles a purchase from a successful_payment. The same
// payment arriving again changes nothing: settled is then false and the
// purchase is returned as it is.
func (b *Billing) SettleStars(ctx context.Context, payload, chargeID string, userID int64, currency string, total int64) (bool, *db.Purchase, error) {
if chargeID == "" {
return false, nil, ErrUnknownCharge
}
if p, err := b.store.GetPurchaseByCharge(ctx, chargeID); err == nil {
return false, p, nil // seen before
}
p, err := b.starsPurchase(ctx, payload, userID)
if err != nil {
return false, nil, err
}
if currency != "XTR" || total != p.StarsAmount {
b.log.Error("stars payment does not match its invoice", "purchase_id", p.ID, "currency", currency,
"total", total, "want", p.StarsAmount)
return false, p, ErrStarsMismatch
}
settled, paid, err := b.settle(ctx, p.ID, func(tx *db.Store) error {
return tx.SetPurchaseCharge(ctx, p.ID, chargeID)
})
if err != nil {
return false, p, err
}
if !settled {
cur, err := b.store.GetPurchase(ctx, p.ID)
return false, cur, err
}
return true, paid, nil
}
// UndoStarsPurchase takes back what a refunded Stars purchase granted:
// the credits (as far as they are left) or the pass. It is safe to call
// more than once; only the first call changes anything. The Stars
// themselves are returned by Telegram (refundStarPayment).
func (b *Billing) UndoStarsPurchase(ctx context.Context, purchaseID string) (bool, error) {
var undone bool
err := b.store.InTx(ctx, func(tx *db.Store) error {
now := b.nowMilli()
won, err := tx.MarkPurchaseRefunded(ctx, purchaseID, now)
if err != nil || !won {
return err
}
p, err := tx.GetPurchase(ctx, purchaseID)
if err != nil {
return err
}
switch {
case p.Product == ProductCredits:
w, err := tx.GetWallet(ctx, p.WalletID)
if err != nil {
return err
}
take := min(w.Balance, p.AmountSats)
if take > 0 {
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: p.WalletID, Kind: db.LedgerDebit, Amount: take, Reason: "stars_refund",
Ref: p.ID, DedupeKey: "stars-refund:" + p.ID, CreatedAt: now, PaymentMethod: db.PayStars,
}); err != nil {
return err
}
}
case passKind(p.Product) != "":
if _, err := tx.RemovePassesFrom(ctx, p.WalletID, p.ID); err != nil {
return err
}
}
undone = true
return nil
})
if err == nil && undone {
b.log.Info("stars purchase refunded", "purchase_id", purchaseID)
}
return undone, err
}