Phase 5: Telegram affiliate program

- docs/AFFILIATE.md: the owner's setup in Telegram (profile editor or
  BotFather's Mini App), commission and duration rules (raise only, end
  with commission 0, about 24 hours), who counts as referred, the link
  formats, and the no-double-rewards rule. Checked against Telegram's
  current pages.
- Affiliate purchases go through Stars invoices inside the Mini App
  (createInvoiceLink and WebApp.openInvoice, from Phase 4).
- /start accepts any payload; only our own rf_ (and old ref_) links set
  an inviter. A test sends payloads of every shape, Telegram's affiliate
  prefix included.
- Mini App Me page: an Earn section explaining both programs, with how
  to join Telegram's from the bot's profile, behind AFFILIATE_ENABLED.
  No affiliate numbers are computed or shown.
- /referral notes that Stars purchases earn through Telegram's program.
- The optional MTProto CLI is left out, with the reason in the docs.
- The Mini App browser test checks the Earn section in en, es and nl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 21:31:06 +00:00
co-authored by Claude Opus 5.5
parent 2b5625e9d4
commit d64db03f21
20 changed files with 341 additions and 9 deletions
+8 -4
View File
@@ -255,7 +255,7 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) {
MaxSize: dec.Limits.MaxSize, MaxDuration: dec.Limits.MaxDuration, ActiveJobs: dec.Limits.ActiveJobs,
DailyDownloads: dec.Limits.DailyDownloads, DailyBytes: dec.Limits.DailyBytes,
},
"payments": m.Billing.Enabled(),
"payments": m.Billing.Enabled(),
"referral_link": refLink,
"referral_count": refStats.Invited,
"referral_converted": refStats.Converted,
@@ -264,9 +264,13 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) {
"referral_qr": refQR,
"referral_reward": m.Cfg.Prices.ReferralReward,
"referral_daily_cap": m.Cfg.ReferralDailyCap,
"support": support,
"start_param": s.init.StartParam,
"bot": m.Bot.Username(),
// Telegram's affiliate program is set up and paid by Telegram; the
// app only explains it, and shows no numbers of its own.
"affiliate_enabled": m.Cfg.AffiliateEnabled,
"stars_enabled": m.Billing.StarsEnabled(),
"support": support,
"start_param": s.init.StartParam,
"bot": m.Bot.Username(),
})
}
+61
View File
@@ -605,3 +605,64 @@ func TestMenuButtonOpensTheAppInTheUsersLanguage(t *testing.T) {
t.Fatalf("menu button after switching = %s", btn.Params["menu_button"])
}
}
// --- /start payloads of every shape ------------------------------------------
func TestStartPayloadsOfEveryShape(t *testing.T) {
h := startApp(t, nil, func(c *config.Config) { c.AffiliateEnabled = true })
h.askEveryTime(alice)
code, err := h.app.Store.RefCode(context.Background(), alice)
if err != nil {
t.Fatal(err)
}
payloads := []string{
"",
// Telegram's affiliate links: a prefix from Telegram's client
// configuration (starref_start_param_prefixes), then the referrer.
"_tgr_AbCdEf123", "_tgr_", "_tgr_" + strings.Repeat("x", 58),
// Our own links, the old ones, and broken ones.
"rf_" + code, "rf_", "rf_zzzzzzzz", "rf_" + code + "extra", "ref_", "ref_42", "ref_-5", "ref_99999999999999999999",
// Other deep links of the bot, valid and not.
"buy", "buy_", "buy_nope_best", "buy_nope_x--y", "skip_", "skip_nope", "gw_", "gw_abc", "gs_-100", "gw_-100123",
// What a person can type by hand.
"hello world", "<b>hi</b>", "💥", strings.Repeat("A", 300), "_", "-", "ref", "rf", "start",
}
for i, p := range payloads {
user := int64(5000 + i)
seq := h.srv.Seq()
h.srv.PushMessage(user, user, strings.TrimSpace("/start "+p))
reply := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == user })
if strings.Contains(reply.Text(), "went wrong") {
t.Errorf("payload %q: %q", p, reply.Text())
}
u, err := h.app.Store.GetUser(context.Background(), user)
if err != nil {
t.Fatalf("payload %q: %v", p, err)
}
// Only our own links set a referrer; Telegram's never do.
want := int64(0)
if p == "rf_"+code || p == "ref_42" {
want = alice
}
if u.ReferredBy != want {
t.Errorf("payload %q: referred by %d, want %d", p, u.ReferredBy, want)
}
}
// In a group /start with a payload is fine too.
h.meetGroup(alice)
seq := h.srv.Seq()
h.srv.PushMessage(group, alice, "/start@"+fakeserver.BotUsername+" _tgr_abc")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group })
// /referral says which purchases count where.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/referral")
ref := h.wait(seq, "sendMessage", textHas("Invite friends"))
if !strings.Contains(ref.Text(), "Telegram Stars do not count here") {
t.Fatalf("referral text = %q", ref.Text())
}
// The Mini App knows whether to explain Telegram's program.
if me := h.must(alice, "GET", "me", nil); me.Body["affiliate_enabled"] != true {
t.Fatalf("me = %s", me.Raw)
}
}
+2
View File
@@ -28,6 +28,8 @@ func TestMiniAppStage(t *testing.T) {
}
h := startApp(t, &ytdlptest.Fake{FileSize: 3000, Delay: 5 * time.Second}, func(c *config.Config) {
c.Worker.Concurrency = 1
c.StarsEnabled = true
c.AffiliateEnabled = true
})
h.meetGroup(alice, bob)
h.fetch(bob, link) // something for the history page
+3 -1
View File
@@ -117,7 +117,9 @@ func TestStarsPurchaseInTheChat(t *testing.T) {
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") })
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")
}
+5
View File
@@ -305,6 +305,11 @@ func (b *Bot) referralView(ctx context.Context, act actor, back bool) (string, *
if c := b.cfg.ReferralDailyCap; c > 0 {
text += "\n\n" + b.tr.HTML(lang, "referral.cap", i18n.Args{"Cap": b.tr.Sats(lang, c)})
}
if b.cfg.AffiliateEnabled {
// Stars purchases are rewarded by Telegram's affiliate program,
// never by ours: one purchase, one reward.
text += "\n\n" + b.tr.HTML(lang, "referral.affiliate_note", i18n.Args{"Bot": b.username})
}
rows := [][]telego.InlineKeyboardButton{
{
urlButton(b.tr.T(lang, "btn.share", nil), shareURL(link, b.tr.T(lang, "referral.share_text", nil))),
+5
View File
@@ -123,6 +123,11 @@ type Config struct {
// 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"`
// AffiliateEnabled shows the Earn section's part about Telegram's
// affiliate program (a share of Stars spent in the Mini App, paid by
// Telegram). Turn it on once the program is set up for the bot, see
// docs/AFFILIATE.md.
AffiliateEnabled bool `toml:"affiliate_enabled" env:"AFFILIATE_ENABLED"`
}
// StarsPrice returns the price in Stars of a product, or false when it