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
+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),
})
}