- 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>
215 lines
8.6 KiB
Go
215 lines
8.6 KiB
Go
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)
|
|
}
|
|
}
|