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:
co-authored by
Claude Opus 5.5
parent
f7ceadc462
commit
2b5625e9d4
+38
-1
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user