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
+32 -6
View File
@@ -491,13 +491,26 @@ func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) {
if up := m.Cfg.MaxUploadBytes(); up > 0 && up < size {
size = up
}
stars := func(product string, amount int64) int64 {
n, _ := m.Billing.StarsPrice(product, amount)
return n
}
starsPacks := []map[string]int64{}
for _, a := range p.CreditPacks {
if n := stars(billing.ProductCredits, a); n > 0 {
starsPacks = append(starsPacks, map[string]int64{"amount": a, "stars": n})
}
}
m.ok(w, map[string]any{
"enabled": m.Billing.Enabled(),
"enabled": m.Billing.Selling(),
"lightning": m.Billing.Enabled(),
"stars": m.Billing.StarsEnabled(),
"passes": []map[string]any{
{"product": billing.ProductPassDay, "price": p.PassDay},
{"product": billing.ProductPassWeek, "price": p.PassWeek},
{"product": billing.ProductPassMonth, "price": p.PassMonth},
{"product": billing.ProductPassDay, "price": p.PassDay, "stars": stars(billing.ProductPassDay, 0)},
{"product": billing.ProductPassWeek, "price": p.PassWeek, "stars": stars(billing.ProductPassWeek, 0)},
{"product": billing.ProductPassMonth, "price": p.PassMonth, "stars": stars(billing.ProductPassMonth, 0)},
},
"stars_packs": starsPacks,
"credit_packs": p.CreditPacks,
"credit_per_download": p.CreditPerDownload,
"paid": tierJSON{MaxSize: size, MaxDuration: int64(paid.MaxDuration.D().Seconds()), ActiveJobs: paid.ActiveJobs, DailyDownloads: paid.DailyDownloads, DailyBytes: paid.DailyMB << 20},
@@ -510,9 +523,9 @@ func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) {
func (m *MiniApp) purchaseJSON(p *db.Purchase, withInvoice bool) map[string]any {
out := map[string]any{
"id": p.ID, "product": p.Product, "amount": p.AmountSats, "status": p.Status,
"expires_at": p.ExpiresAt, "paid_at": p.PaidAt,
"expires_at": p.ExpiresAt, "paid_at": p.PaidAt, "method": p.PaymentMethod, "stars": p.StarsAmount,
}
if withInvoice && p.Status == db.PurchasePending {
if withInvoice && p.Status == db.PurchasePending && p.PaymentMethod != db.PayStars {
out["bolt11"] = p.Bolt11
if png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512); err == nil {
out["qr"] = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
@@ -526,6 +539,8 @@ func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) {
Target string `json:"target"` // "me" or a group chat ID
Product string `json:"product"`
Amount int64 `json:"amount"`
// Method is "lightning" (the default) or "stars".
Method string `json:"method"`
}
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
@@ -548,6 +563,17 @@ func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) {
}
groupID = id
}
if in.Method == db.PayStars {
p, link, err := m.Bot.AppStarsPurchase(r.Context(), s.user, s.lang, groupID, in.Product, in.Amount)
if err != nil {
m.explain(w, s, err)
return
}
out := m.purchaseJSON(p, true)
out["invoice_link"] = link
m.ok(w, out)
return
}
p, err := m.Bot.AppPurchase(r.Context(), s.user, s.lang, groupID, in.Product, in.Amount, "")
if err != nil {
m.explain(w, s, err)
+1 -1
View File
@@ -371,7 +371,7 @@ func New(ctx context.Context, opts Options) (*App, error) {
}
// allowedUpdates is the list of update types the bot asks Telegram for.
var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query"}
var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query"}
// Run starts every loop and blocks until ctx ends. Shutdown is ordered:
// updates stop first, then the worker hands back its jobs, then the
+8 -1
View File
@@ -223,6 +223,13 @@ func tour(t *testing.T, h *moneyHarness, user int64, lang string) {
buy := h.wait(seq, "sendMessage", inChat)
seq = pressOn(buy, "by:pass_day")
h.wait(seq, "sendPhoto", inChat)
// The same in Stars, and its invoice.
seq = pressOn(buy, "sm")
stars := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID })
seq = pressOn(stars, "sb:pass_day")
h.wait(seq, "sendInvoice", inChat)
seq = pressOn(stars, "lm")
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID })
}
// Links of the tour with scripted outcomes.
@@ -263,7 +270,7 @@ func TestEveryScreenInSpanishAndDutch(t *testing.T) {
t.Run(lang, func(t *testing.T) {
// A missing message or a fallback to English is logged as a bug,
// which fails the test (see guardHandler).
h := startApp(t, tourFake(), nil)
h := startApp(t, tourFake(), withStars)
const user = int64(501)
tour(t, h, user, lang)
if out != "" {
+214
View File
@@ -0,0 +1,214 @@
package app_test
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
func withStars(c *config.Config) { c.StarsEnabled = true }
// invoiceOf reads the essentials of a sendInvoice or createInvoiceLink call.
func invoiceOf(t *testing.T, c fakeserver.Call) (payload string, total int) {
t.Helper()
var prices []struct {
Label string `json:"label"`
Amount int `json:"amount"`
}
if err := json.Unmarshal([]byte(c.Params["prices"]), &prices); err != nil || len(prices) != 1 {
t.Fatalf("a Stars invoice needs exactly one price: %s (%v)", c.Params["prices"], err)
}
if c.Params["currency"] != "XTR" || c.Params["provider_token"] != "" {
t.Fatalf("currency %q, provider token %q: want XTR and none", c.Params["currency"], c.Params["provider_token"])
}
if n := len([]rune(c.Params["title"])); n < 1 || n > 32 {
t.Fatalf("title %q is %d characters", c.Params["title"], n)
}
return c.Params["payload"], prices[0].Amount
}
// precheck sends a pre-checkout query and returns the bot's answer.
func (h *harness) precheck(user int64, payload, currency string, total int) fakeserver.Call {
h.t.Helper()
seq := h.srv.Seq()
id := h.srv.PushPreCheckout(user, payload, currency, total)
return h.wait(seq, "answerPreCheckoutQuery", func(c fakeserver.Call) bool { return c.Params["pre_checkout_query_id"] == id })
}
func TestStarsPurchaseInTheChat(t *testing.T) {
const owner = int64(900)
h := startMoney(t, nil, func(c *config.Config) {
withStars(c)
c.Owners = []int64{owner}
})
ctx := context.Background()
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
buy := h.wait(seq, "sendMessage", textHas("Passes and credits"))
// Lightning first, Stars one tap away.
if got := labels(buy); !strings.HasPrefix(got, "Day pass · 700 sats") || !strings.HasSuffix(got, "⭐ Pay with Stars") {
t.Fatalf("buy buttons = %q", got)
}
seq = h.press(alice, alice, buy, "sm")
menu := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID })
if got := labels(menu); got != "Day pass · ⭐ 50 | Week pass · ⭐ 200 | Month pass · ⭐ 600 | 1,000 sats · ⭐ 70 | 5,000 sats · ⭐ 330 | 20,000 sats · ⭐ 1,300 | ⚡ Pay with Lightning" {
t.Fatalf("stars buttons = %q", got)
}
seq = h.press(alice, alice, menu, "sb:pass_week")
inv := h.wait(seq, "sendInvoice", nil)
payload, total := invoiceOf(t, inv)
if total != 200 || !strings.HasPrefix(payload, "dlp:") || inv.ChatID() != alice {
t.Fatalf("invoice: payload %q, total %d, chat %d", payload, total, inv.ChatID())
}
if n, _ := h.ln.Calls(); n != 0 {
t.Fatal("a Stars invoice created a Lightning invoice")
}
// Pre-checkout: only the exact order passes.
if a := h.precheck(alice, payload, "XTR", 199); a.Params["ok"] != "false" || a.Params["error_message"] == "" {
t.Fatalf("wrong amount answered %+v", a.Params)
}
if a := h.precheck(bob, payload, "XTR", 200); a.Params["ok"] != "false" {
t.Fatalf("another payer answered %+v", a.Params)
}
if a := h.precheck(alice, payload, "XTR", 200); a.Params["ok"] != "true" {
t.Fatalf("the right order answered %+v", a.Params)
}
// The payment, then the same event again: one pass, one confirmation.
seq = h.srv.Seq()
h.srv.PushSuccessfulPayment(alice, payload, "XTR", 200, "tg-charge-1")
h.wait(seq, "sendMessage", textHas("Paid."))
st, _ := h.app.Billing.State(ctx, db.OwnerUser, alice)
if st.PassUntil == 0 {
t.Fatal("no pass after the Stars payment")
}
seq = h.srv.Seq()
h.srv.PushSuccessfulPayment(alice, payload, "XTR", 200, "tg-charge-1")
h.never(seq, "sendMessage", textHas("Paid."))
if again, _ := h.app.Billing.State(ctx, db.OwnerUser, alice); again.PassUntil != st.PassUntil {
t.Fatal("a repeated payment event extended the pass")
}
// Revenue by method for the owner.
seq = h.srv.Seq()
h.srv.PushMessage(owner, owner, "/stats")
stats := h.wait(seq, "sendMessage", textHas("Revenue"))
if !strings.Contains(stats.Text(), "Stars: 200 Stars from 1 purchase, 0 refunded") {
t.Fatalf("stats = %q", stats.Text())
}
// The owner refunds it: Telegram returns the Stars, the pass goes.
p, err := h.app.Store.GetPurchaseByCharge(ctx, "tg-charge-1")
if err != nil {
t.Fatal(err)
}
seq = h.srv.Seq()
h.srv.PushMessage(owner, owner, "/refund "+p.ID)
refund := h.wait(seq, "refundStarPayment", nil)
if refund.Params["user_id"] != "42" || refund.Params["telegram_payment_charge_id"] != "tg-charge-1" {
t.Fatalf("refundStarPayment = %+v", refund.Params)
}
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "refunded") })
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner && strings.Contains(c.Text(), "Refunded 200 Stars") })
if st, _ := h.app.Billing.State(ctx, db.OwnerUser, alice); st.PassUntil != 0 {
t.Fatal("the refunded pass is still active")
}
// Telegram's own refund message for it changes nothing more.
seq = h.srv.Seq()
h.srv.PushRefundedPayment(alice, payload, 200, "tg-charge-1")
h.never(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice })
// A refunded purchase is not refunded twice.
seq = h.srv.Seq()
h.srv.PushMessage(owner, owner, "/refund tg-charge-1")
h.wait(seq, "sendMessage", textHas("cannot be refunded"))
if n := len(h.srv.Calls("refundStarPayment")); n != 1 {
t.Fatalf("refundStarPayment called %d times", n)
}
// The old /refund still gives sats back.
seq = h.srv.Seq()
h.srv.PushMessage(owner, owner, "/refund 42 300")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner })
if got := h.balance(alice); got != 300 {
t.Fatalf("balance after a sats refund = %d", got)
}
h.booksBalance()
}
func TestStarsPassForAnOverLimitDownload(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{FileSize: 4096}, withStars)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
// Lightning first; Stars below it.
if got := labels(offer); !strings.HasPrefix(got, "Day pass · 700 sats") || !strings.Contains(got, "⭐ Pay with Stars") {
t.Fatalf("offer buttons = %q", got)
}
seq = h.press(alice, alice, offer, "so:")
stars := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("sv:"); return ok })
seq = h.press(alice, alice, stars, "sv:pass_day")
payload, total := invoiceOf(t, h.wait(seq, "sendInvoice", nil))
if total != 50 {
t.Fatalf("day pass costs %d Stars", total)
}
if n := len(h.fake.Downloads()); n != 0 {
t.Fatal("downloaded before payment")
}
h.precheck(alice, payload, "XTR", 50)
seq = h.srv.Seq()
h.srv.PushSuccessfulPayment(alice, payload, "XTR", 50, "tg-charge-9")
// The download it was for starts, like after a Lightning payment.
h.finished(seq, alice)
sent := h.waitSent(alice, 1)
if sent[0].Source != "own_pass" {
t.Fatalf("delivery source = %q, want own_pass", sent[0].Source)
}
}
func TestMiniAppStarsPurchase(t *testing.T) {
h := startApp(t, nil, withStars)
products := h.must(alice, "GET", "products", nil)
if products.Body["stars"] != true || products.Body["lightning"] != true {
t.Fatalf("products = %s", products.Raw)
}
if packs := products.list("stars_packs"); len(packs) != 3 || packs[0]["stars"] != float64(70) {
t.Fatalf("stars packs = %v", packs)
}
seq := h.srv.Seq()
p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 5000, "method": "stars"})
if p.str("method") != "stars" || p.num("stars") != 330 || p.str("status") != "pending" ||
!strings.HasPrefix(p.str("invoice_link"), "https://t.me/$fake_invoice") || p.str("bolt11") != "" {
t.Fatalf("purchase = %s", p.Raw)
}
link := h.wait(seq, "createInvoiceLink", nil)
payload, total := invoiceOf(t, link)
if total != 330 {
t.Fatalf("invoice link total = %d", total)
}
// A pack without a Stars price is not sold for Stars.
h.refused(h.call(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 1234, "method": "stars"}), 422, "bad_amount")
// The payment arrives as a Telegram update; the app sees it on its next poll.
h.precheck(alice, payload, "XTR", 330)
h.srv.PushSuccessfulPayment(alice, payload, "XTR", 330, "tg-charge-app")
id := p.str("id")
for i := 0; ; i++ {
if st := h.must(alice, "GET", "purchase/"+id, nil); st.str("status") == "paid" {
break
}
if i > 200 {
t.Fatal("the purchase never showed as paid")
}
time.Sleep(20 * time.Millisecond)
}
if got := h.balance(alice); got != 5000 {
t.Fatalf("balance = %d", got)
}
}
+30 -13
View File
@@ -196,26 +196,26 @@ func (b *Billing) State(ctx context.Context, ownerType string, ownerID int64) (e
// Credit adds sats to a wallet. The dedupe key makes it idempotent.
func (b *Billing) Credit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor)
return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor, "")
}
// Debit takes sats from a wallet, or fails with db.ErrInsufficient.
func (b *Billing) Debit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor)
return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor, "")
}
// Refund gives sats back to a wallet.
func (b *Billing) Refund(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor)
return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor, "")
}
func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64, method string) (bool, error) {
var applied bool
err := b.store.InTx(ctx, func(tx *db.Store) error {
var err error
applied, err = tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: walletID, Kind: kind, Amount: sats, Reason: reason, Ref: ref,
DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(),
DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(), PaymentMethod: method,
})
return err
})
@@ -390,7 +390,9 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*
if p.UserID != userID {
return nil, ErrNotOwner
}
if p.Status != db.PurchasePaid {
if p.Status != db.PurchasePaid && p.PaymentMethod != db.PayStars {
// A Stars payment arrives as a Telegram update; there is nothing
// to ask LNbits about.
if _, err := b.checkOne(ctx, p); err != nil {
return nil, err
}
@@ -400,7 +402,7 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*
// checkOne confirms a purchase with LNbits and settles or expires it.
func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, err error) {
if p.Status == db.PurchasePaid {
if p.Status == db.PurchasePaid || p.PaymentMethod == db.PayStars {
return false, nil
}
if b.ln == nil {
@@ -442,6 +444,13 @@ func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, e
// transaction. It is idempotent: the second and later calls return false
// and change nothing. Callers must have confirmed the payment.
func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
settled, _, err := b.settle(ctx, purchaseID, nil)
return settled, err
}
// settle is Settle with a step of its own inside the transaction, run once
// the purchase is marked paid: a Stars payment records its charge ID there.
func (b *Billing) settle(ctx context.Context, purchaseID string, inTx func(tx *db.Store) error) (bool, *db.Purchase, error) {
var (
settled bool
p *db.Purchase
@@ -452,6 +461,11 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
if err != nil || !won {
return err
}
if inTx != nil {
if err := inTx(tx); err != nil {
return err
}
}
if p, err = tx.GetPurchase(ctx, purchaseID); err != nil {
return err
}
@@ -460,6 +474,7 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: p.WalletID, Kind: db.LedgerCredit, Amount: p.AmountSats,
Reason: "purchase", Ref: p.ID, DedupeKey: "purchase:" + p.ID, ActorID: p.UserID, CreatedAt: now,
PaymentMethod: p.PaymentMethod,
}); err != nil {
return err
}
@@ -483,18 +498,18 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
return nil
})
if errors.Is(err, db.ErrDuplicate) {
return false, nil // another connection settled it first
return false, nil, nil // another connection settled it first
}
if err != nil || !settled {
return false, err
return false, nil, err
}
b.mu.Lock()
b.stats.InvoicesSettled++
b.mu.Unlock()
b.log.Info("invoice settled", "purchase_id", p.ID, "product", p.Product, "sats", p.AmountSats,
"user_id", p.UserID, "wallet_id", p.WalletID)
"stars", p.StarsAmount, "method", p.PaymentMethod, "user_id", p.UserID, "wallet_id", p.WalletID)
b.emit(EventPaid, p)
return true, nil
return true, p, nil
}
// rewardReferrer pays the inviter of a user who settled their first
@@ -544,7 +559,9 @@ func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purcha
// countsForReferral reports whether a purchase was paid in a way our
// referral program rewards: Lightning.
func countsForReferral(p *db.Purchase) bool { return true }
func countsForReferral(p *db.Purchase) bool {
return p.PaymentMethod == db.PayLightning || p.PaymentMethod == ""
}
// underCap reports whether an inviter may be paid amount more today.
func (b *Billing) underCap(ctx context.Context, tx *db.Store, referrer int64, day int, amount int64) (bool, error) {
@@ -642,7 +659,7 @@ func (b *Billing) ConvertToCredits(ctx context.Context, p *db.Purchase) (bool, e
if err != nil {
return false, err
}
return b.Credit(ctx, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID)
return b.move(ctx, db.LedgerCredit, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID, p.PaymentMethod)
}
// --- reconciliation --------------------------------------------------------
+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
}
+208
View File
@@ -0,0 +1,208 @@
package billing_test
import (
"context"
"errors"
"testing"
"time"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/db"
)
const bob = int64(43)
func starsRig(t *testing.T) *rig {
t.Helper()
r := newRig(t)
r.cfg.StarsEnabled = true
r.b = r.newBilling()
return r
}
func (r *rig) buyStars(user int64, product string, amount int64) *db.Purchase {
r.t.Helper()
p, err := r.b.CreateStarsPurchase(context.Background(), billing.NewPurchase{
UserID: user, WalletID: r.wallet(user).ID, Product: product, Amount: amount, Lang: "en",
})
if err != nil {
r.t.Fatalf("CreateStarsPurchase: %v", err)
}
return p
}
func TestStarsPricesAreTheirOwn(t *testing.T) {
r := starsRig(t)
ctx := context.Background()
p := r.buyStars(alice, billing.ProductCredits, 5000)
if p.PaymentMethod != db.PayStars || p.StarsAmount != 330 || p.AmountSats != 5000 || p.Bolt11 != "" {
t.Fatalf("purchase = %+v", p)
}
// Only passes and credit packs with a configured price are sold.
for _, c := range []struct {
product string
amount int64
}{{billing.ProductOneOff, 1000}, {billing.ProductDonation, 500}, {billing.ProductCredits, 1234}, {billing.ProductSkipQueue, 0}} {
_, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: c.product, Amount: c.amount})
if !errors.Is(err, billing.ErrNotForStars) {
t.Errorf("%s %d: %v, want ErrNotForStars", c.product, c.amount, err)
}
}
// Off means off.
r.cfg.StarsEnabled = false
r.b = r.newBilling()
if _, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductPassDay}); !errors.Is(err, billing.ErrStarsOff) {
t.Fatalf("stars off: %v", err)
}
if creates, statuses := r.ln.Calls(); creates != 0 || statuses != 0 {
t.Fatalf("a Stars purchase talked to LNbits: %d creates, %d statuses", creates, statuses)
}
}
func TestStarsPreCheckout(t *testing.T) {
r := starsRig(t)
ctx := context.Background()
p := r.buyStars(alice, billing.ProductPassDay, 0)
payload := billing.StarsPayload(p)
cases := []struct {
name string
payload string
user int64
currency string
total int64
want error
}{
{"matches", payload, alice, "XTR", 50, nil},
{"other amount", payload, alice, "XTR", 49, billing.ErrStarsMismatch},
{"other currency", payload, alice, "USD", 50, billing.ErrStarsMismatch},
{"other payer", payload, bob, "XTR", 50, billing.ErrUnknownCharge},
{"unknown payload", "dlp:nope", alice, "XTR", 50, billing.ErrUnknownCharge},
{"foreign payload", "something else", alice, "XTR", 50, billing.ErrUnknownCharge},
}
for _, c := range cases {
if err := r.b.PreCheckStars(ctx, c.payload, c.user, c.currency, c.total); !errors.Is(err, c.want) {
t.Errorf("%s: %v, want %v", c.name, err, c.want)
}
}
// A cancelled invoice is not paid any more.
if _, err := r.b.Cancel(ctx, p.ID, alice); err != nil {
t.Fatal(err)
}
if err := r.b.PreCheckStars(ctx, payload, alice, "XTR", 50); !errors.Is(err, billing.ErrInvoiceClosed) {
t.Fatalf("cancelled: %v", err)
}
}
func TestStarsPaymentGrantsTheSameAsLightningOnce(t *testing.T) {
r := starsRig(t)
ctx := context.Background()
// The same pass, once over Lightning (bob) and once in Stars (alice).
_ = r.ln.Pay(r.buy(bob, billing.ProductPassWeek, 0).PaymentHash)
p := r.buyStars(alice, billing.ProductPassWeek, 0)
settled, paid, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200)
if err != nil || !settled || paid.Status != db.PurchasePaid || paid.ChargeID != "charge-1" {
t.Fatalf("SettleStars = %v, %+v, %v", settled, paid, err)
}
stA, _ := r.b.State(ctx, db.OwnerUser, alice)
stB, _ := r.b.State(ctx, db.OwnerUser, bob)
if stA.PassUntil == 0 || stA.PassUntil != stB.PassUntil {
t.Fatalf("pass until: stars %d, lightning %d", stA.PassUntil, stB.PassUntil)
}
// The same payment event again, and again with the poll: nothing new.
for i := 0; i < 3; i++ {
again, cur, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200)
if err != nil || again || cur.ID != p.ID {
t.Fatalf("repeat %d: %v %+v %v", i, again, cur, err)
}
}
if n := r.count(billing.EventPaid); n != 2 {
t.Fatalf("%d paid events, want 2 (one per purchase)", n)
}
if _, err := r.b.Reconcile(ctx, time.Hour); err != nil {
t.Fatal(err)
}
if st, _ := r.b.State(ctx, db.OwnerUser, alice); st.PassUntil != stA.PassUntil {
t.Fatal("the pass was extended twice")
}
// Credits: the pack's sats arrive in the wallet, marked as paid in Stars.
c := r.buyStars(alice, billing.ProductCredits, 1000)
if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(c), "charge-2", alice, "XTR", 70); err != nil {
t.Fatal(err)
}
if got := r.balance(alice); got != 1000 {
t.Fatalf("balance = %d", got)
}
if l := r.ledger(alice); len(l) == 0 || l[0].PaymentMethod != db.PayStars {
t.Fatalf("ledger = %+v", l)
}
// A payment that does not match its invoice is not settled.
m := r.buyStars(alice, billing.ProductCredits, 5000)
if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(m), "charge-3", alice, "XTR", 1); !errors.Is(err, billing.ErrStarsMismatch) {
t.Fatalf("mismatch: %v", err)
}
r.booksBalance()
}
func TestStarsRefundUndoesThePurchase(t *testing.T) {
r := starsRig(t)
ctx := context.Background()
c := r.buyStars(alice, billing.ProductCredits, 1000)
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(c), "c1", alice, "XTR", 70)
pass := r.buyStars(alice, billing.ProductPassDay, 0)
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(pass), "c2", alice, "XTR", 50)
week := r.buyStars(alice, billing.ProductPassWeek, 0)
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(week), "c3", alice, "XTR", 200)
before, _ := r.b.State(ctx, db.OwnerUser, alice)
// The day pass goes; the week pass stacked after it moves up a day.
if ok, err := r.b.UndoStarsPurchase(ctx, pass.ID); err != nil || !ok {
t.Fatalf("undo pass: %v %v", ok, err)
}
after, _ := r.b.State(ctx, db.OwnerUser, alice)
if got := before.PassUntil - after.PassUntil; got != (24 * time.Hour).Milliseconds() {
t.Fatalf("pass shortened by %d ms, want one day", got)
}
// Credits are taken back as far as they are left.
if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); !ok || r.balance(alice) != 0 {
t.Fatalf("balance after refund = %d", r.balance(alice))
}
// Once only, and never for a Lightning purchase.
if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); ok {
t.Fatal("refunded twice")
}
ln := r.buy(bob, billing.ProductCredits, 1000)
_ = r.ln.Pay(ln.PaymentHash)
if ok, _ := r.b.UndoStarsPurchase(ctx, ln.ID); ok || r.balance(bob) != 1000 {
t.Fatal("a Lightning purchase was undone as a Stars refund")
}
if p := r.purchase(pass.ID); p.Status != db.PurchaseRefunded || p.RefundedAt == 0 {
t.Fatalf("purchase = %+v", p)
}
r.booksBalance()
}
func TestStarsPurchasesEarnNoSatsReferral(t *testing.T) {
r := starsRig(t)
ctx := context.Background()
const inviter, invited = int64(700), int64(701)
for _, id := range []int64{inviter, invited} {
if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
t.Fatal(err)
}
}
if _, err := r.store.SetReferrer(ctx, invited, inviter); err != nil {
t.Fatal(err)
}
// Telegram's affiliate program covers Stars; our sats reward does not.
p := r.buyStars(invited, billing.ProductPassDay, 0)
_, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(p), "c1", invited, "XTR", 50)
if r.balance(inviter) != 0 {
t.Fatal("a Stars purchase paid a sats referral reward")
}
// The first Lightning purchase after it does.
_ = r.ln.Pay(r.buy(invited, billing.ProductCredits, 1000).PaymentHash)
if r.balance(inviter) != 200 {
t.Fatalf("inviter balance = %d, want 200", r.balance(inviter))
}
}
+38 -1
View File
@@ -226,6 +226,42 @@ func (b *Bot) AppPurchase(ctx context.Context, user *db.User, lang string, group
})
}
// AppStarsPurchase creates a Stars purchase from the Mini App and an
// invoice link for WebApp.openInvoice. Payments made inside the Mini App
// are the ones Telegram's affiliate program counts.
func (b *Bot) AppStarsPurchase(ctx context.Context, user *db.User, lang string, groupID int64, product string, amount int64) (*db.Purchase, string, error) {
if !billing.ValidProduct(product) {
return nil, "", billing.ErrBadProduct
}
if !b.rate.allow("ap:"+itoa(user.ID), 10, time.Minute) {
return nil, "", ErrRateLimited
}
ownerType, ownerID := db.OwnerUser, user.ID
if groupID != 0 {
g, err := b.store.GetGroup(ctx, groupID)
if err != nil || !g.Present() {
return nil, "", db.ErrNotFound
}
ownerType, ownerID = db.OwnerGroup, groupID
}
w, err := b.bill.Wallet(ctx, ownerType, ownerID)
if err != nil {
return nil, "", err
}
p, err := b.bill.CreateStarsPurchase(ctx, billing.NewPurchase{
UserID: user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang,
})
if err != nil {
return nil, "", err
}
link, err := b.StarsInvoiceLink(ctx, p)
if err != nil {
_, _ = b.bill.Cancel(context.WithoutCancel(ctx), p.ID, user.ID)
return nil, "", err
}
return p, link, nil
}
// Explain turns an error from the operations above into a stable code and
// a message in the user's language.
func (b *Bot) Explain(lang string, err error) (code, message string, upgradable bool) {
@@ -248,7 +284,8 @@ func (b *Bot) Explain(lang string, err error) (code, message string, upgradable
return "payments_off", b.tr.T(lang, "buy.unavailable", nil), false
case errors.Is(err, billing.ErrLightningDown):
return "payments_down", b.tr.T(lang, "buy.backend_down_short", nil), false
case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct):
case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct),
errors.Is(err, billing.ErrNotForStars), errors.Is(err, billing.ErrStarsOff):
return "bad_amount", b.tr.T(lang, "buy.bad_amount", nil), false
}
b.log.Error("mini app operation failed", "err", err)
+8
View File
@@ -302,6 +302,8 @@ func updateChatID(u telego.Update) int64 {
return u.CallbackQuery.From.ID
case u.MyChatMember != nil:
return u.MyChatMember.Chat.ID
case u.PreCheckoutQuery != nil:
return u.PreCheckoutQuery.From.ID
case u.WidgetQuery != nil:
if u.WidgetQuery.Chat != nil {
return u.WidgetQuery.Chat.ID
@@ -332,6 +334,8 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
b.handleMyChatMember(ctx, u.MyChatMember)
case u.WidgetQuery != nil:
b.handleWidgetQuery(ctx, u.WidgetQuery)
case u.PreCheckoutQuery != nil:
b.handlePreCheckout(ctx, u.PreCheckoutQuery)
}
}
@@ -347,6 +351,8 @@ func updateUser(u telego.Update) (*telego.User, *telego.Chat) {
return &u.CallbackQuery.From, &chat
}
return &u.CallbackQuery.From, nil
case u.PreCheckoutQuery != nil:
return &u.PreCheckoutQuery.From, nil
}
return nil, nil
}
@@ -361,6 +367,8 @@ func updateType(u telego.Update) string {
return "my_chat_member"
case u.WidgetQuery != nil:
return "widget_query"
case u.PreCheckoutQuery != nil:
return "pre_checkout_query"
}
return "other"
}
+21 -1
View File
@@ -19,7 +19,19 @@ import (
func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
act, ok := actorFrom(ctx)
if !ok || act.user.Banned {
if !ok {
return
}
// Payments are settled whoever pays: the Stars were already taken.
switch {
case m.SuccessfulPayment != nil:
b.handleSuccessfulPayment(ctx, m, act)
return
case m.RefundedPayment != nil:
b.handleRefundedPayment(ctx, m, act)
return
}
if act.user.Banned {
return
}
private := isPrivate(m.Chat.Type)
@@ -524,6 +536,14 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
b.cbShowUpgrade(ctx, q, act)
case cbReferralQR:
b.cbSendReferralQR(ctx, q, act)
case cbStarsMenu, cbLightningMenu:
b.cbSwitchPayment(ctx, q, act, action == cbStarsMenu)
case cbStarsBuy:
b.cbStarsProduct(ctx, q, act, id, arg)
case cbStarsOffer:
b.cbStarsForOffer(ctx, q, act, id, arg)
case cbStarsOfferBuy:
b.cbStarsOfferProduct(ctx, q, act, id, arg)
case cbPersonal:
b.cbPersonalSetting(ctx, q, act, id, arg)
case cbSkipQueue:
+53 -15
View File
@@ -77,19 +77,30 @@ func (b *Bot) cmdBuy(ctx context.Context, m *telego.Message, act actor) {
}
func (b *Bot) showBuy(ctx context.Context, chat int64, act actor) {
if !b.bill.Enabled() {
if !b.bill.Selling() {
_, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil)
return
}
text, kb := b.buyView(act.lang)
_, _ = b.send(ctx, chat, 0, text, kb)
}
// buyView is the buy screen: Lightning prices first, and a button to the
// Stars prices when Stars are on. Without Lightning it is the Stars prices.
func (b *Bot) buyView(lang string) (string, *telego.InlineKeyboardMarkup) {
paid := b.cfg.Limits.Paid
rows := b.passButtons(act.lang, func(product string) string { return cbData(cbBuy, product) })
rows = append(rows, b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks))
text := b.tr.HTML(act.lang, "buy.intro", i18n.Args{
"MaxSize": b.tr.Size(act.lang, min64(paid.MaxSizeMB<<20, b.cfg.MaxUploadBytes())),
"MaxDuration": b.tr.Span(act.lang, paid.MaxDuration.D()),
"PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload),
text := b.tr.HTML(lang, "buy.intro", i18n.Args{
"MaxSize": b.tr.Size(lang, min64(paid.MaxSizeMB<<20, b.cfg.MaxUploadBytes())),
"MaxDuration": b.tr.Span(lang, paid.MaxDuration.D()),
"PerDownload": b.tr.Sats(lang, b.cfg.Prices.CreditPerDownload),
})
_, _ = b.send(ctx, chat, 0, text, keyboard(rows...))
if !b.bill.Enabled() {
stars, kb := b.starsMenu(lang)
return text + "\n\n" + stars, kb
}
rows := b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })
rows = append(rows, b.amountButtons(lang, billing.ProductCredits, b.cfg.Prices.CreditPacks), b.starsMenuButton(lang))
return text, keyboard(rows...)
}
func min64(a, b int64) int64 {
@@ -113,8 +124,12 @@ func (b *Bot) cmdCredits(ctx context.Context, m *telego.Message, act actor) {
"PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload),
})
var kb *telego.InlineKeyboardMarkup
if b.bill.Enabled() {
kb = keyboard(b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks))
if b.bill.Selling() {
var packs []telego.InlineKeyboardButton
if b.bill.Enabled() {
packs = b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks)
}
kb = keyboard(packs, b.starsMenuButton(act.lang))
}
_, _ = b.send(ctx, m.Chat.ID, 0, text, kb)
}
@@ -173,8 +188,12 @@ func (b *Bot) cmdAccount(ctx context.Context, m *telego.Message, act actor) {
"Used": b.tr.Size(lang, usage.Bytes), "Max": b.capSize(lang, dec.Limits.DailyBytes),
}))
var kb *telego.InlineKeyboardMarkup
if b.bill.Enabled() {
kb = keyboard(b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })...)
if b.bill.Selling() {
var rows [][]telego.InlineKeyboardButton
if b.bill.Enabled() {
rows = b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })
}
kb = keyboard(append(rows, b.starsMenuButton(lang))...)
}
_, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), kb)
}
@@ -656,7 +675,14 @@ func (b *Bot) handlePayEvent(ctx context.Context, ev billing.Event) {
}
b.showPurchaseState(ctx, p)
if ev.Type == billing.EventPaid {
if p.MessageID == 0 {
switch {
case p.MessageID == 0 && p.PaymentMethod == db.PayStars:
// Telegram's invoice message cannot be edited into "paid", and
// the payment arrived as a message: confirm it right away.
if msg, err := b.send(ctx, p.UserID, 0, b.paidText(ctx, p), nil); err == nil {
_ = b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, p.UserID, int64(msg.MessageID), false)
}
case p.MessageID == 0:
b.goBG("confirm-payment", func() { b.confirmWithoutInvoice(ctx, p.ID) })
}
b.fulfil(ctx, p)
@@ -686,9 +712,13 @@ func (b *Bot) confirmWithoutInvoice(ctx context.Context, purchaseID string) {
// paidText is what the invoice message becomes once it is settled.
func (b *Bot) paidText(ctx context.Context, p *db.Purchase) string {
lang := p.Lang
amount := b.tr.Sats(lang, p.AmountSats)
if p.PaymentMethod == db.PayStars {
amount = b.starsAmount(lang, p.StarsAmount)
}
text := b.tr.HTML(lang, "invoice.paid", i18n.Args{
"Title": b.productTitle(lang, p.Product),
"Amount": b.tr.Sats(lang, p.AmountSats),
"Amount": amount,
})
w, err := b.store.GetWallet(ctx, p.WalletID)
if err != nil {
@@ -860,7 +890,15 @@ func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string
rows = b.passButtons(lang, func(product string) string {
return cbData(cbOfferBuy, product, req.ID, string(profile))
})
if le.Code == service.LimitTooLarge || le.Code == service.LimitTooLong {
if !b.bill.Enabled() {
rows = nil // Stars only: the passes come with the Stars button
}
if b.bill.StarsEnabled() {
rows = append(rows, []telego.InlineKeyboardButton{
button(b.tr.T(lang, "btn.pay_stars", nil), cbData(cbStarsOffer, req.ID, string(profile))),
})
}
if b.bill.Enabled() && (le.Code == service.LimitTooLarge || le.Code == service.LimitTooLong) {
price := b.cfg.Prices.OneOffPrice(le.Size)
rows = append(rows, []telego.InlineKeyboardButton{
button(b.priced(lang, b.tr.T(lang, "btn.this_file", nil), price),
+28 -1
View File
@@ -52,6 +52,12 @@ func (b *Bot) ownerCommand(ctx context.Context, m *telego.Message, act actor, cm
case "credit":
b.cmdCredit(ctx, m, act, false)
case "refund":
// /refund <purchase or charge ID> returns a Stars payment;
// /refund <user> <sats> gives sats back, as before.
if f := strings.Fields(commandArgs(m)); len(f) == 1 && !isDigits(f[0]) {
b.refundStars(ctx, m, act, f[0])
return true
}
b.cmdCredit(ctx, m, act, true)
case "blocklist":
b.cmdBlocklist(ctx, m, act)
@@ -97,7 +103,7 @@ func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) {
}
}
maint, _ := b.store.GetKV(ctx, "maintenance")
b.ownerReply(ctx, m, act, "owner.stats", i18n.Args{
text := b.tr.HTML(lang, "owner.stats", i18n.Args{
"Users": b.tr.Number(lang, users),
"Done": b.tr.Number(lang, jobs[db.JobDone]),
"Failed": b.tr.Number(lang, jobs[db.JobFailed]),
@@ -109,6 +115,27 @@ func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) {
"Created": bst.InvoicesCreated, "Settled": bst.InvoicesSettled,
"Lightning": ln, "Books": books, "Maint": b.onOff(lang, maint == "1"),
})
// Revenue by payment method, all time.
if revenue, err := b.store.RevenueByMethod(ctx, 0); err == nil && len(revenue) > 0 {
text += "\n\n" + b.tr.HTML(lang, "owner.revenue_title", nil)
for _, r := range revenue {
key, amount := "owner.revenue_lightning", b.tr.Sats(lang, r.Sats)
if r.Method == db.PayStars {
key, amount = "owner.revenue_stars", b.starsAmount(lang, r.Stars)
}
text += "\n" + b.tr.HTML(lang, key, i18n.Args{"Amount": amount, "Count": r.Purchases, "Refunded": r.Refunded})
}
}
_, _ = b.send(ctx, m.Chat.ID, 0, text, nil)
}
func isDigits(s string) bool {
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return s != ""
}
// cmdQueueAll is /queue all for owners: every queued and running job.
+1 -1
View File
@@ -415,7 +415,7 @@ func (b *Bot) errorKeyboard(lang string, req *db.Request, profile media.Profile,
// upgradeButton is "Upgrade", when there is something to buy.
func (b *Bot) upgradeButton(lang string, private bool) []telego.InlineKeyboardButton {
if !b.bill.Enabled() {
if !b.bill.Selling() {
return nil
}
if !private {
+313
View File
@@ -0,0 +1,313 @@
package bot
import (
"context"
"errors"
"strconv"
"strings"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
// This file is the chat side of Telegram Stars payments: the Stars price
// buttons next to the Lightning ones, the invoice, the pre-checkout
// answer, the successful and refunded payment messages, and the owner's
// refund. Lightning stays the first option everywhere.
const (
cbStarsMenu = "sm" // sm: the Stars prices, in place of the Lightning ones
cbLightningMenu = "lm" // lm: back to the Lightning prices
cbStarsBuy = "sb" // sb:<product>[:<amount>]
cbStarsOffer = "so" // so:<request id>:<profile>, Stars for an over-limit offer
cbStarsOfferBuy = "sv" // sv:<product>:<request id>:<profile>
)
// starsLabel is a price in Stars for a button, such as "Day pass · ⭐ 50".
func (b *Bot) starsLabel(lang, label string, stars int64) string {
return b.tr.T(lang, "btn.with_stars", i18n.Args{"Label": label, "Stars": b.tr.Number(lang, stars)})
}
// starsAmount is a price in Stars for a sentence.
func (b *Bot) starsAmount(lang string, stars int64) string {
return b.tr.T(lang, "unit.stars", i18n.Args{"Count": stars, "N": b.tr.Number(lang, stars)})
}
// starsPassButtons are the passes that have a Stars price.
func (b *Bot) starsPassButtons(lang string, data func(product string) string) [][]telego.InlineKeyboardButton {
var row []telego.InlineKeyboardButton
for _, product := range []string{billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth} {
if stars, ok := b.bill.StarsPrice(product, 0); ok {
row = append(row, button(b.starsLabel(lang, b.productTitle(lang, product), stars), data(product)))
}
}
if len(row) == 3 {
return [][]telego.InlineKeyboardButton{row[:2], row[2:]}
}
return [][]telego.InlineKeyboardButton{row}
}
// starsMenu is the Stars counterpart of the buy screen.
func (b *Bot) starsMenu(lang string) (string, *telego.InlineKeyboardMarkup) {
rows := b.starsPassButtons(lang, func(product string) string { return cbData(cbStarsBuy, product) })
var packs []telego.InlineKeyboardButton
for _, a := range b.cfg.Prices.CreditPacks {
if stars, ok := b.bill.StarsPrice(billing.ProductCredits, a); ok {
packs = append(packs, button(b.starsLabel(lang, b.tr.Sats(lang, a), stars),
cbData(cbStarsBuy, billing.ProductCredits, strconv.FormatInt(a, 10))))
}
}
rows = append(rows, packs)
if b.bill.Enabled() {
rows = append(rows, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.pay_lightning", nil), cbLightningMenu)})
}
return b.tr.HTML(lang, "stars.intro", nil), keyboard(rows...)
}
// starsMenuButton opens the Stars prices, when Stars are on.
func (b *Bot) starsMenuButton(lang string) []telego.InlineKeyboardButton {
if !b.bill.StarsEnabled() {
return nil
}
return []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.pay_stars", nil), cbStarsMenu)}
}
// cbSwitchPayment turns a buy screen into the Stars prices or back.
func (b *Bot) cbSwitchPayment(ctx context.Context, q *telego.CallbackQuery, act actor, stars bool) {
if q.Message == nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
chat, msgID := q.Message.GetChat().ID, int64(q.Message.GetMessageID())
if stars {
text, kb := b.starsMenu(act.lang)
_ = b.edit(ctx, chat, msgID, false, text, kb)
return
}
text, kb := b.buyView(act.lang)
_ = b.edit(ctx, chat, msgID, false, text, kb)
}
// cbStarsProduct handles a Stars price button of the buy screen.
func (b *Bot) cbStarsProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, amountArg string) {
b.answer(ctx, q, "", false)
amount, _ := strconv.ParseInt(amountArg, 10, 64)
b.startStarsPurchase(ctx, act, product, amount, purchaseContext{})
}
// cbStarsForOffer shows the Stars passes for an over-limit offer, as a
// message of its own under the Lightning offer.
func (b *Bot) cbStarsForOffer(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) {
req, err := b.store.GetRequest(ctx, requestID)
if err != nil || req.UserID != act.user.ID || req.Status != db.RequestReady {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
rows := b.starsPassButtons(act.lang, func(product string) string {
return cbData(cbStarsOfferBuy, product, req.ID, profileArg)
})
_, _ = b.send(ctx, act.user.ID, 0, b.tr.HTML(act.lang, "stars.offer", nil), keyboard(rows...))
}
// cbStarsOfferProduct buys a pass in Stars for an over-limit offer; the
// download starts once it is paid, as with Lightning.
func (b *Bot) cbStarsOfferProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) {
requestID, profileArg, _ := strings.Cut(rest, ":")
req, err := b.store.GetRequest(ctx, requestID)
_, perr := media.Parse(profileArg)
if err != nil || perr != nil || req.UserID != act.user.ID || req.Status != db.RequestReady {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
if _, err := service.ParseCardInfo(req.Info); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
b.startStarsPurchase(ctx, act, product, 0, purchaseContext{requestID: req.ID, profile: profileArg})
}
// startStarsPurchase records a Stars purchase and sends its invoice to the
// payer's private chat.
func (b *Bot) startStarsPurchase(ctx context.Context, act actor, product string, amount int64, pc purchaseContext) {
lang := act.lang
chat := act.user.ID
if !billing.ValidProduct(product) {
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil)
return
}
ownerType, ownerID := db.OwnerUser, act.user.ID
if pc.groupID != 0 {
ownerType, ownerID = db.OwnerGroup, pc.groupID
}
w, err := b.bill.Wallet(ctx, ownerType, ownerID)
if err != nil {
b.internalError(ctx, chat, act, err)
return
}
p, err := b.bill.CreateStarsPurchase(ctx, billing.NewPurchase{
UserID: act.user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang,
RequestID: pc.requestID, Profile: pc.profile, DeliveryID: pc.deliveryID,
})
switch {
case errors.Is(err, billing.ErrStarsOff), errors.Is(err, billing.ErrNotForStars),
errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct):
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil)
return
case err != nil:
b.internalError(ctx, chat, act, err)
return
}
if _, err := b.api.SendInvoice(ctx, b.starsInvoice(p, chat)); err != nil {
b.log.Error("send stars invoice", "purchase_id", p.ID, "err", err)
_, _ = b.bill.Cancel(context.WithoutCancel(ctx), p.ID, p.UserID)
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "error.internal", nil), nil)
}
}
// starsInvoice is the sendInvoice call for a Stars purchase: currency XTR,
// no provider token, exactly one price.
func (b *Bot) starsInvoice(p *db.Purchase, chat int64) *telego.SendInvoiceParams {
title, desc := b.starsInvoiceTexts(p)
return &telego.SendInvoiceParams{
ChatID: chatID(chat), Title: title, Description: desc, Payload: billing.StarsPayload(p),
Currency: "XTR", Prices: []telego.LabeledPrice{{Label: title, Amount: int(p.StarsAmount)}},
}
}
// starsInvoiceTexts are the title (1 to 32 characters) and description
// (1 to 255) of a Stars invoice.
func (b *Bot) starsInvoiceTexts(p *db.Purchase) (title, desc string) {
lang := p.Lang
title = b.productTitle(lang, p.Product)
if p.Product == billing.ProductCredits {
title = b.tr.T(lang, "stars.credits_title", i18n.Args{"Amount": b.tr.Sats(lang, p.AmountSats)})
}
title = shorten(title, 32)
desc = b.tr.T(lang, "stars.invoice_description", i18n.Args{"Title": title})
if g := b.groupTitle(p); g != "" {
desc = b.tr.T(lang, "invoice.for_group", i18n.Args{"Group": g}) + "\n" + desc
}
return title, shorten(plainText(desc), 255)
}
// StarsInvoiceLink makes an invoice link for a Stars purchase, for the
// Mini App to open with WebApp.openInvoice.
func (b *Bot) StarsInvoiceLink(ctx context.Context, p *db.Purchase) (string, error) {
title, desc := b.starsInvoiceTexts(p)
link, err := b.api.CreateInvoiceLink(ctx, &telego.CreateInvoiceLinkParams{
Title: title, Description: desc, Payload: billing.StarsPayload(p),
Currency: "XTR", Prices: []telego.LabeledPrice{{Label: title, Amount: int(p.StarsAmount)}},
})
if err != nil {
return "", err
}
return *link, nil
}
// handlePreCheckout answers Telegram's last question before it takes the
// Stars. It has ten seconds; the check is a database read.
func (b *Bot) handlePreCheckout(ctx context.Context, q *telego.PreCheckoutQuery) {
lang := b.tr.Resolve(q.From.LanguageCode)
if act, ok := actorFrom(ctx); ok {
lang = act.lang
}
err := b.bill.PreCheckStars(ctx, q.InvoicePayload, q.From.ID, q.Currency, int64(q.TotalAmount))
params := &telego.AnswerPreCheckoutQueryParams{PreCheckoutQueryID: q.ID, Ok: err == nil}
if err != nil {
key := "stars.precheck_failed"
if errors.Is(err, billing.ErrInvoiceClosed) {
key = "stars.precheck_closed"
}
params.ErrorMessage = b.tr.T(lang, key, nil)
b.log.Info("pre-checkout refused", "user_id", q.From.ID, "err", err)
}
if err := b.api.AnswerPreCheckoutQuery(ctx, params); err != nil {
b.log.Warn("answerPreCheckoutQuery failed", "err", err)
}
}
// handleSuccessfulPayment settles the purchase a Stars payment was for.
// The paid event that follows confirms it in the chat and starts what was
// paid for. The same payment twice settles once.
func (b *Bot) handleSuccessfulPayment(ctx context.Context, m *telego.Message, act actor) {
sp := m.SuccessfulPayment
_, p, err := b.bill.SettleStars(context.WithoutCancel(ctx), sp.InvoicePayload, sp.TelegramPaymentChargeID,
m.From.ID, sp.Currency, int64(sp.TotalAmount))
if err != nil {
// The Stars were taken but cannot be matched to an order. The owner
// can return them with /refund and the charge ID from this log line.
b.log.Error("stars payment not settled", "user_id", m.From.ID, "charge_id", sp.TelegramPaymentChargeID,
"payload", sp.InvoicePayload, "total", sp.TotalAmount, "err", err)
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "stars.payment_problem", nil), nil)
return
}
b.log.Info("stars payment received", "purchase_id", p.ID, "user_id", m.From.ID, "stars", sp.TotalAmount)
}
// handleRefundedPayment takes back what a refunded Stars purchase granted.
// It runs for refunds made through /refund as well as any other, and does
// nothing the second time.
func (b *Bot) handleRefundedPayment(ctx context.Context, m *telego.Message, act actor) {
rp := m.RefundedPayment
p, err := b.store.GetPurchaseByCharge(ctx, rp.TelegramPaymentChargeID)
if err != nil {
b.log.Warn("refund of an unknown stars payment", "charge_id", rp.TelegramPaymentChargeID)
return
}
undone, err := b.bill.UndoStarsPurchase(context.WithoutCancel(ctx), p.ID)
if err != nil {
b.log.Error("undo refunded stars purchase", "purchase_id", p.ID, "err", err)
return
}
if undone {
_, _ = b.send(ctx, p.UserID, 0, b.tr.HTML(p.Lang, "stars.refunded", i18n.Args{
"Title": b.productTitle(p.Lang, p.Product), "Amount": b.starsAmount(p.Lang, p.StarsAmount),
}), nil)
}
}
// refundStars is the owner's /refund for a Stars payment: by purchase ID
// or by Telegram's charge ID. Telegram returns the Stars; the purchase's
// credits or pass are taken back.
func (b *Bot) refundStars(ctx context.Context, m *telego.Message, act actor, ref string) {
p, err := b.store.GetPurchase(ctx, ref)
if err != nil {
p, err = b.store.GetPurchaseByCharge(ctx, ref)
}
if err != nil || p.PaymentMethod != db.PayStars {
b.ownerReply(ctx, m, act, "owner.not_found", nil)
return
}
if p.Status != db.PurchasePaid || p.ChargeID == "" {
b.ownerReply(ctx, m, act, "owner.stars_not_refundable", i18n.Args{"Status": p.Status})
return
}
if err := b.api.RefundStarPayment(ctx, &telego.RefundStarPaymentParams{
UserID: p.UserID, TelegramPaymentChargeID: p.ChargeID,
}); err != nil {
b.log.Warn("refundStarPayment failed", "purchase_id", p.ID, "err", err)
b.ownerReply(ctx, m, act, "owner.stars_refund_failed", i18n.Args{"Reason": err.Error()})
return
}
undone, err := b.bill.UndoStarsPurchase(context.WithoutCancel(ctx), p.ID)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if undone {
_, _ = b.send(ctx, p.UserID, 0, b.tr.HTML(p.Lang, "stars.refunded", i18n.Args{
"Title": b.productTitle(p.Lang, p.Product), "Amount": b.starsAmount(p.Lang, p.StarsAmount),
}), nil)
}
b.ownerReply(ctx, m, act, "owner.stars_refunded", i18n.Args{
"ID": p.ID, "Amount": b.starsAmount(act.lang, p.StarsAmount), "User": strconv.FormatInt(p.UserID, 10),
})
}
+63
View File
@@ -113,6 +113,45 @@ type Config struct {
// day (UTC), in sats. Rewards above it wait and are paid on a later
// day. 0 means no cap.
ReferralDailyCap int64 `toml:"referral_daily_cap" env:"REFERRAL_DAILY_CAP"`
// StarsEnabled offers Telegram Stars as a second way to pay for passes
// and credits, next to Lightning. It needs no setup beyond the bot.
StarsEnabled bool `toml:"stars_enabled" env:"STARS_ENABLED"`
// StarsPrices is the price in Stars of each product sold for Stars:
// pass_day, pass_week, pass_month and credits_<sats> for a credit pack
// (credits_1000 = 70). These are set on their own, never converted from
// sats. A product without a price is not offered for Stars. In the
// environment: STARS_PRICES="pass_day=50,credits_1000=70".
StarsPrices map[string]int64 `toml:"stars_prices"`
}
// StarsPrice returns the price in Stars of a product, or false when it
// is not sold for Stars. amount names the credit pack.
func (c Config) StarsPrice(product string, amount int64) (int64, bool) {
key := product
if product == "credits" {
key = "credits_" + strconv.FormatInt(amount, 10)
}
n, ok := c.StarsPrices[key]
return n, ok && n > 0
}
// ParseStarsPrices reads STARS_PRICES: "pass_day=50,credits_1000=70".
func ParseStarsPrices(raw string) (map[string]int64, error) {
out := map[string]int64{}
for _, part := range strings.Split(raw, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
k, v, ok := strings.Cut(part, "=")
n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
if !ok || err != nil {
return nil, fmt.Errorf("STARS_PRICES: bad entry %q, want product=stars", part)
}
out[strings.TrimSpace(k)] = n
}
return out, nil
}
// Telegram holds the Bot API settings.
@@ -387,6 +426,10 @@ func Default() Config {
CaptionAttribution: true,
ReferralRewardSats: -1,
ReferralDailyCap: 2000,
StarsPrices: map[string]int64{
"pass_day": 50, "pass_week": 200, "pass_month": 600,
"credits_1000": 70, "credits_5000": 330, "credits_20000": 1300,
},
}
}
@@ -424,6 +467,13 @@ func Load(path string) (Config, error) {
if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil {
return cfg, err
}
if raw, ok := os.LookupEnv("STARS_PRICES"); ok && raw != "" {
m, err := ParseStarsPrices(raw)
if err != nil {
return cfg, err
}
cfg.StarsPrices = m
}
if raw, ok := os.LookupEnv("SITE_TAGS"); ok && raw != "" {
m, err := ParseSiteTags(raw)
if err != nil {
@@ -467,6 +517,19 @@ func (c Config) Validate() error {
if c.QueueNoticeThresholdSeconds < 0 {
errs = append(errs, "QUEUE_NOTICE_THRESHOLD_SECONDS must not be negative")
}
for k, n := range c.StarsPrices {
known := k == "pass_day" || k == "pass_week" || k == "pass_month"
if amount, ok := strings.CutPrefix(k, "credits_"); ok {
v, err := strconv.ParseInt(amount, 10, 64)
known = err == nil && v > 0
}
if !known {
errs = append(errs, fmt.Sprintf("stars_prices: unknown product %q (pass_day, pass_week, pass_month, credits_<sats>)", k))
}
if n < 1 || n > 100000 {
errs = append(errs, fmt.Sprintf("stars_prices: %s must be between 1 and 100000 Stars", k))
}
}
if c.ReferralDailyCap < 0 {
errs = append(errs, "REFERRAL_DAILY_CAP must not be negative")
}
+32
View File
@@ -393,3 +393,35 @@ func TestReferralRewardNames(t *testing.T) {
t.Fatal("a negative cap was accepted")
}
}
func TestStarsPrices(t *testing.T) {
cfg := Default()
if n, ok := cfg.StarsPrice("pass_week", 0); !ok || n != 200 {
t.Fatalf("default pass_week = %d %v", n, ok)
}
if n, ok := cfg.StarsPrice("credits", 5000); !ok || n != 330 {
t.Fatalf("default 5000 credits = %d %v", n, ok)
}
if _, ok := cfg.StarsPrice("credits", 1234); ok {
t.Fatal("a pack without a Stars price is sold for Stars")
}
if _, ok := cfg.StarsPrice("one_off", 0); ok {
t.Fatal("one-off payments are not sold for Stars")
}
m, err := ParseStarsPrices(" pass_day=25, credits_1000=60 ")
if err != nil || m["pass_day"] != 25 || m["credits_1000"] != 60 || len(m) != 2 {
t.Fatalf("ParseStarsPrices = %v, %v", m, err)
}
if _, err := ParseStarsPrices("pass_day=lots"); err == nil {
t.Fatal("a bad price was accepted")
}
cfg.Telegram.Token = "x"
cfg.StarsPrices = map[string]int64{"pass_year": 5}
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "pass_year") {
t.Fatalf("unknown product: %v", err)
}
cfg.StarsPrices = map[string]int64{"pass_day": 0}
if err := cfg.Validate(); err == nil {
t.Fatal("a price of 0 Stars was accepted")
}
}
+2 -2
View File
@@ -300,9 +300,9 @@ func (s *Store) ActiveJobs(ctx context.Context, limit int) ([]*Job, error) {
ORDER BY CASE status WHEN 'running' THEN 0 ELSE 1 END, `+queueOrder+` LIMIT ?`, limit))
}
// SatsReceived sums paid purchases.
// SatsReceived sums purchases paid over Lightning.
func (s *Store) SatsReceived(ctx context.Context) (int64, error) {
var n sql.NullInt64
err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid'`).Scan(&n)
err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid' AND payment_method = 'lightning'`).Scan(&n)
return n.Int64, err
}
+24
View File
@@ -0,0 +1,24 @@
-- +goose Up
-- Telegram Stars as a second payment method. Every purchase and every
-- ledger entry says how it was paid; everything before this was Lightning.
ALTER TABLE purchases ADD COLUMN payment_method TEXT NOT NULL DEFAULT 'lightning';
-- What a Stars purchase cost in Stars. amount_sats keeps the sats value of
-- what it bought (the credit pack, or the pass price) for the wallet.
ALTER TABLE purchases ADD COLUMN stars_amount BIGINT NOT NULL DEFAULT 0;
-- Telegram's identifier of a Stars payment. Unique, so the same payment
-- event can never settle twice.
ALTER TABLE purchases ADD COLUMN tg_charge_id TEXT NOT NULL DEFAULT '';
ALTER TABLE purchases ADD COLUMN refunded_at BIGINT NOT NULL DEFAULT 0;
CREATE UNIQUE INDEX purchases_charge_idx ON purchases (tg_charge_id) WHERE tg_charge_id <> '';
CREATE INDEX purchases_method_idx ON purchases (payment_method, status);
ALTER TABLE ledger ADD COLUMN payment_method TEXT NOT NULL DEFAULT 'lightning';
-- +goose Down
ALTER TABLE ledger DROP COLUMN payment_method;
DROP INDEX purchases_method_idx;
DROP INDEX purchases_charge_idx;
ALTER TABLE purchases DROP COLUMN refunded_at;
ALTER TABLE purchases DROP COLUMN tg_charge_id;
ALTER TABLE purchases DROP COLUMN stars_amount;
ALTER TABLE purchases DROP COLUMN payment_method;
+19
View File
@@ -255,6 +255,9 @@ type LedgerEntry struct {
DedupeKey string
ActorID int64
CreatedAt int64
// PaymentMethod is how the money behind the entry was paid: lightning
// or stars. Empty means lightning.
PaymentMethod string
}
// Pass is a time window of paid limits on a wallet.
@@ -291,8 +294,24 @@ type Purchase struct {
CreatedAt int64
ExpiresAt int64
PaidAt int64
// PaymentMethod is lightning or stars.
PaymentMethod string
// StarsAmount is the price in Stars of a Stars purchase.
StarsAmount int64
// ChargeID is Telegram's telegram_payment_charge_id of a Stars payment.
ChargeID string
RefundedAt int64
}
// Payment methods.
const (
PayLightning = "lightning"
PayStars = "stars"
)
// PurchaseRefunded is the status of a Stars purchase that was refunded.
const PurchaseRefunded = "refunded"
// Usage is what a user consumed on one UTC day.
type Usage struct {
Downloads int
+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()
}
+1 -1
View File
@@ -507,7 +507,7 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me
func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError {
le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]}
if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || strings.HasPrefix(code, "group_") ||
code == LimitMaintenance || dec.Source.Paid() || !s.billing.Enabled() {
code == LimitMaintenance || dec.Source.Paid() || !s.billing.Selling() {
return le
}
// Would the paid tier accept it? Only then is it worth offering.
+4
View File
@@ -37,6 +37,10 @@ type API interface {
AnswerWidgetQuery(ctx context.Context, params *telego.AnswerWidgetQueryParams) error
GetChatMember(ctx context.Context, params *telego.GetChatMemberParams) (telego.ChatMember, error)
SetChatMenuButton(ctx context.Context, params *telego.SetChatMenuButtonParams) error
SendInvoice(ctx context.Context, params *telego.SendInvoiceParams) (*telego.Message, error)
CreateInvoiceLink(ctx context.Context, params *telego.CreateInvoiceLinkParams) (*string, error)
AnswerPreCheckoutQuery(ctx context.Context, params *telego.AnswerPreCheckoutQueryParams) error
RefundStarPayment(ctx context.Context, params *telego.RefundStarPaymentParams) error
}
var _ API = (*telego.Bot)(nil)
+61 -1
View File
@@ -353,6 +353,52 @@ func (s *Server) PushWidgetQuery(chatID, userID int64, messageID int, data strin
return id
}
// PushPreCheckout queues the query Telegram sends before it takes a
// payment, and returns its ID.
func (s *Server) PushPreCheckout(userID int64, payload, currency string, total int) string {
s.mu.Lock()
defer s.mu.Unlock()
id := fmt.Sprintf("pcq%d", s.updateID+1)
s.pushLocked(map[string]any{"pre_checkout_query": map[string]any{
"id": id,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"currency": currency,
"total_amount": total,
"invoice_payload": payload,
}})
return id
}
// PushSuccessfulPayment queues the service message of a completed payment
// in the payer's private chat.
func (s *Server) PushSuccessfulPayment(userID int64, payload, currency string, total int, chargeID string) {
s.pushPaymentLocked(userID, "successful_payment", map[string]any{
"currency": currency, "total_amount": total, "invoice_payload": payload,
"telegram_payment_charge_id": chargeID, "provider_payment_charge_id": "",
})
}
// PushRefundedPayment queues the service message of a refunded payment.
func (s *Server) PushRefundedPayment(userID int64, payload string, total int, chargeID string) {
s.pushPaymentLocked(userID, "refunded_payment", map[string]any{
"currency": "XTR", "total_amount": total, "invoice_payload": payload,
"telegram_payment_charge_id": chargeID,
})
}
func (s *Server) pushPaymentLocked(userID int64, field string, body map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
s.msgID++
s.pushLocked(map[string]any{"message": map[string]any{
"message_id": s.msgID,
"date": time.Now().Unix(),
"chat": chatObject(userID),
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
field: body,
}})
}
// PushRaw queues an arbitrary update body, for example my_chat_member.
func (s *Server) PushRaw(update map[string]any) {
s.mu.Lock()
@@ -479,7 +525,10 @@ func (s *Server) resultLocked(c *Call) any {
}
uid, _ := strconv.ParseInt(c.Params["user_id"], 10, 64)
return map[string]any{"status": status, "user": map[string]any{"id": uid, "is_bot": false, "first_name": "User"}}
case "sendMessage", "sendPhoto", "sendVideo", "sendAudio", "sendDocument", "sendAnimation", "sendWidget":
case "createInvoiceLink":
s.fileSeq++
return fmt.Sprintf("https://t.me/$fake_invoice_%d", s.fileSeq)
case "sendMessage", "sendPhoto", "sendVideo", "sendAudio", "sendDocument", "sendAnimation", "sendWidget", "sendInvoice":
s.msgID++
c.MessageID = s.msgID
msg := s.messageLocked(c)
@@ -540,6 +589,17 @@ func (s *Server) messageLocked(c *Call) map[string]any {
msg["animation"] = a
case "sendWidget":
msg["widget"] = map[string]any{"html": c.Params["html"], "chat_data": c.Params["chat_data"], "public_data": c.Params["public_data"]}
case "sendInvoice":
var prices []struct {
Amount int `json:"amount"`
}
_ = json.Unmarshal([]byte(c.Params["prices"]), &prices)
total := 0
for _, p := range prices {
total += p.Amount
}
msg["invoice"] = map[string]any{"title": c.Params["title"], "description": c.Params["description"],
"start_parameter": "", "currency": c.Params["currency"], "total_amount": total}
}
return msg
}