feat(payments): Telegram Stars payment rail
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 22s
CI / integration (pull_request) Successful in 20s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m57s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 22s
CI / integration (pull_request) Successful in 20s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m57s
Accept real money via Telegram Stars (XTR) — the third intake rail alongside Robokassa (direct) and VK Votes. Only the bot reaches Telegram, so the rail funnels through the reverse mTLS bot-link: - the gateway mints the invoice on a CreateInvoice command (the bot calls createInvoiceLink, XTR; the link goes to WebApp.openInvoice); - the bot gates each pre_checkout_query via a ValidatePreCheckout unary (the order must exist, be still creditable and not already paid — the reusable-invoice double-pay guard; the decline reason is localised to the order account's language); - a completed successful_payment is queued in a durable pure-Go SQLite outbox and forwarded via a ForwardPayment unary, credited once (idempotent on telegram_payment_charge_id, honours an expired order), re-driven on restart and every 30s. The rail is wired by TELEGRAM_STARS_OUTBOX_DIR (default /data) but stays inert until a chip pack carries an XTR price, so seeding a Stars price in the admin is the go-live. Tests: backend integration (order->forward->credit once, duplicate, pre_checkout gate) + bot outbox unit (idempotent, restart re-drive) + executor createInvoice. Docs: PAYMENTS(+ru) §9, ARCHITECTURE, the platform/telegram README, PLAN.
This commit is contained in:
@@ -83,6 +83,34 @@ func (c *Client) ResolveChatEligibility(ctx context.Context, externalID string)
|
||||
return resp.GetEligible(), nil
|
||||
}
|
||||
|
||||
// ValidatePreCheckout asks the gateway whether a Telegram Stars pre_checkout_query for orderID
|
||||
// paying amount in currency may be approved, before the charge. The bot calls it on every
|
||||
// pre_checkout_query over the same mTLS connection and approves only on ok; the reason is a short
|
||||
// decline message (already localised by the backend) to show the payer.
|
||||
func (c *Client) ValidatePreCheckout(ctx context.Context, orderID string, amount int64, currency string) (ok bool, reason string, err error) {
|
||||
resp, err := c.client.ValidatePreCheckout(ctx, &botlinkv1.PreCheckoutRequest{OrderId: orderID, Amount: amount, Currency: currency})
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
return resp.GetOk(), resp.GetReason(), nil
|
||||
}
|
||||
|
||||
// ForwardPayment delivers a completed Stars payment to the gateway for crediting. The bot calls it
|
||||
// from the outbox drain; it reports whether the order was credited (or already had been). A non-nil
|
||||
// error is a transient failure the bot retries.
|
||||
func (c *Client) ForwardPayment(ctx context.Context, orderID, chargeID string, amount, telegramUserID int64) (credited bool, err error) {
|
||||
resp, err := c.client.ForwardPayment(ctx, &botlinkv1.ForwardPaymentRequest{
|
||||
OrderId: orderID,
|
||||
TelegramPaymentChargeId: chargeID,
|
||||
Amount: amount,
|
||||
TelegramUserId: telegramUserID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return resp.GetCredited(), nil
|
||||
}
|
||||
|
||||
// Run keeps the bot-link command stream open, re-opening it after each break, until
|
||||
// ctx is cancelled. The gRPC connection auto-reconnects the transport underneath.
|
||||
func (c *Client) Run(ctx context.Context) error {
|
||||
@@ -121,8 +149,8 @@ func (c *Client) serve(ctx context.Context, client botlinkv1.BotLinkClient) erro
|
||||
if cmd == nil {
|
||||
continue
|
||||
}
|
||||
delivered, herr := c.exec.Handle(ctx, cmd)
|
||||
ack := &botlinkv1.Ack{CommandId: cmd.GetCommandId(), Delivered: delivered}
|
||||
delivered, result, herr := c.exec.Handle(ctx, cmd)
|
||||
ack := &botlinkv1.Ack{CommandId: cmd.GetCommandId(), Delivered: delivered, Result: result}
|
||||
if herr != nil {
|
||||
ack.Error = herr.Error()
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ type Sender interface {
|
||||
// chat, but only when they are currently in it; it reports whether a restriction
|
||||
// was applied.
|
||||
ApplyChatGate(ctx context.Context, userID int64, allow bool) (bool, error)
|
||||
// CreateInvoiceLink mints a Telegram Stars invoice link (XTR) for amountStars, tagged
|
||||
// with payload (the order id, echoed back in pre_checkout and successful_payment), and
|
||||
// returns the link.
|
||||
CreateInvoiceLink(ctx context.Context, title, description, payload string, amountStars int64) (string, error)
|
||||
}
|
||||
|
||||
// Executor turns a bot-link Command into a Bot API send. The delivered flag mirrors
|
||||
@@ -48,22 +52,42 @@ func NewExecutor(sender Sender, channelID int64, log *zap.Logger) *Executor {
|
||||
return &Executor{sender: sender, channelID: channelID, log: log}
|
||||
}
|
||||
|
||||
// Handle dispatches one command to the matching Bot API send.
|
||||
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, error) {
|
||||
// Handle dispatches one command to the matching Bot API call. It returns whether the command was
|
||||
// delivered, an optional result string (the created invoice link for a create_invoice command; empty
|
||||
// otherwise), and an error for an unexpected or malformed failure.
|
||||
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, string, error) {
|
||||
switch p := cmd.GetPayload().(type) {
|
||||
case *botlinkv1.Command_Notify:
|
||||
return e.notify(ctx, p.Notify)
|
||||
d, err := e.notify(ctx, p.Notify)
|
||||
return d, "", err
|
||||
case *botlinkv1.Command_SendToUser:
|
||||
return e.sendToUser(ctx, p.SendToUser)
|
||||
d, err := e.sendToUser(ctx, p.SendToUser)
|
||||
return d, "", err
|
||||
case *botlinkv1.Command_SendToChannel:
|
||||
return e.sendToChannel(ctx, p.SendToChannel)
|
||||
d, err := e.sendToChannel(ctx, p.SendToChannel)
|
||||
return d, "", err
|
||||
case *botlinkv1.Command_ChatGate:
|
||||
return e.chatGate(ctx, p.ChatGate)
|
||||
d, err := e.chatGate(ctx, p.ChatGate)
|
||||
return d, "", err
|
||||
case *botlinkv1.Command_CreateInvoice:
|
||||
return e.createInvoice(ctx, p.CreateInvoice)
|
||||
default:
|
||||
return false, fmt.Errorf("botlink: empty command")
|
||||
return false, "", fmt.Errorf("botlink: empty command")
|
||||
}
|
||||
}
|
||||
|
||||
// createInvoice mints a Telegram Stars invoice link for the order and returns it in the Ack result.
|
||||
// A Bot API failure is a hard error carried back in the Ack, so the gateway's synchronous mint fails
|
||||
// (rather than returning an empty link).
|
||||
func (e *Executor) createInvoice(ctx context.Context, req *botlinkv1.CreateInvoiceCommand) (bool, string, error) {
|
||||
link, err := e.sender.CreateInvoiceLink(ctx, req.GetTitle(), req.GetDescription(), req.GetPayload(), req.GetAmount())
|
||||
if err != nil {
|
||||
e.log.Warn("create invoice link failed", zap.String("order", req.GetPayload()), zap.Error(err))
|
||||
return false, "", err
|
||||
}
|
||||
return true, link, nil
|
||||
}
|
||||
|
||||
// chatGate applies a chat-gate command: it parses the target Telegram user id and
|
||||
// sets their write access in the moderated chat (a no-op when they are not in it). A
|
||||
// Bot API failure is logged and reported as not-delivered, not a hard error.
|
||||
|
||||
@@ -13,11 +13,13 @@ import (
|
||||
|
||||
// fakeSender records the delivery calls the executor makes.
|
||||
type fakeSender struct {
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
gate []gateCall
|
||||
applied bool // ApplyChatGate's reported result
|
||||
err error
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
gate []gateCall
|
||||
invoice []invoiceCall
|
||||
invoiceLink string // CreateInvoiceLink's returned link
|
||||
applied bool // ApplyChatGate's reported result
|
||||
err error
|
||||
}
|
||||
|
||||
type notifyCall struct {
|
||||
@@ -32,6 +34,10 @@ type gateCall struct {
|
||||
userID int64
|
||||
allow bool
|
||||
}
|
||||
type invoiceCall struct {
|
||||
title, description, payload string
|
||||
amount int64
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
|
||||
@@ -48,6 +54,11 @@ func (f *fakeSender) ApplyChatGate(_ context.Context, userID int64, allow bool)
|
||||
return f.applied, f.err
|
||||
}
|
||||
|
||||
func (f *fakeSender) CreateInvoiceLink(_ context.Context, title, description, payload string, amountStars int64) (string, error) {
|
||||
f.invoice = append(f.invoice, invoiceCall{title, description, payload, amountStars})
|
||||
return f.invoiceLink, f.err
|
||||
}
|
||||
|
||||
func yourTurnPayload(gameID string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
gid := b.CreateString(gameID)
|
||||
@@ -67,7 +78,7 @@ func TestExecutorNotifyDelivers(t *testing.T) {
|
||||
const gameID = "7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "your_turn", yourTurnPayload(gameID), "en"))
|
||||
delivered, _, err := exec.Handle(context.Background(), notifyCmd("12345", "your_turn", yourTurnPayload(gameID), "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
@@ -85,7 +96,7 @@ func TestExecutorNotifyDelivers(t *testing.T) {
|
||||
func TestExecutorNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "opponent_moved", nil, "en"))
|
||||
delivered, _, err := exec.Handle(context.Background(), notifyCmd("12345", "opponent_moved", nil, "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
@@ -99,7 +110,7 @@ func TestExecutorNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
|
||||
func TestExecutorNotifyInvalidExternalID(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), notifyCmd("not-a-number", "your_turn", yourTurnPayload("g"), "en")); err == nil {
|
||||
if _, _, err := exec.Handle(context.Background(), notifyCmd("not-a-number", "your_turn", yourTurnPayload("g"), "en")); err == nil {
|
||||
t.Error("expected an error for a non-numeric external_id")
|
||||
}
|
||||
}
|
||||
@@ -108,7 +119,7 @@ func TestExecutorSendToUser(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToUser{SendToUser: &telegramv1.SendToUserRequest{ExternalId: "999", Text: "hi"}}}
|
||||
delivered, err := exec.Handle(context.Background(), cmd)
|
||||
delivered, _, err := exec.Handle(context.Background(), cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
@@ -126,7 +137,7 @@ func chatGateCmd(externalID string, allow bool) *botlinkv1.Command {
|
||||
func TestExecutorChatGateApplied(t *testing.T) {
|
||||
sender := &fakeSender{applied: true}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), chatGateCmd("777", true))
|
||||
delivered, _, err := exec.Handle(context.Background(), chatGateCmd("777", true))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
@@ -138,7 +149,7 @@ func TestExecutorChatGateApplied(t *testing.T) {
|
||||
func TestExecutorChatGateNotInChat(t *testing.T) {
|
||||
sender := &fakeSender{applied: false} // user not in the chat
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), chatGateCmd("888", false))
|
||||
delivered, _, err := exec.Handle(context.Background(), chatGateCmd("888", false))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
@@ -152,24 +163,53 @@ func TestExecutorChatGateNotInChat(t *testing.T) {
|
||||
|
||||
func TestExecutorChatGateInvalidExternalID(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), chatGateCmd("not-a-number", true)); err == nil {
|
||||
if _, _, err := exec.Handle(context.Background(), chatGateCmd("not-a-number", true)); err == nil {
|
||||
t.Error("expected an error for a non-numeric external_id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorCreateInvoice(t *testing.T) {
|
||||
sender := &fakeSender{invoiceLink: "https://t.me/$abc"}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_CreateInvoice{CreateInvoice: &botlinkv1.CreateInvoiceCommand{
|
||||
Title: "50 chips", Description: "50 chips", Payload: "order-1", Amount: 40,
|
||||
}}}
|
||||
delivered, result, err := exec.Handle(context.Background(), cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered || result != "https://t.me/$abc" {
|
||||
t.Errorf("create invoice = %v / %q, want true / the link", delivered, result)
|
||||
}
|
||||
if len(sender.invoice) != 1 || sender.invoice[0].payload != "order-1" || sender.invoice[0].amount != 40 {
|
||||
t.Errorf("invoice calls = %+v", sender.invoice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorCreateInvoiceError(t *testing.T) {
|
||||
sender := &fakeSender{err: context.DeadlineExceeded}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_CreateInvoice{CreateInvoice: &botlinkv1.CreateInvoiceCommand{
|
||||
Title: "x", Description: "x", Payload: "order-2", Amount: 10,
|
||||
}}}
|
||||
if _, _, err := exec.Handle(context.Background(), cmd); err == nil {
|
||||
t.Error("expected an error when minting the invoice fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorSendToChannel(t *testing.T) {
|
||||
channelCmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToChannel{SendToChannel: &telegramv1.SendToGameChannelRequest{Text: "news"}}}
|
||||
|
||||
t.Run("unconfigured", func(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), channelCmd); err == nil {
|
||||
if _, _, err := exec.Handle(context.Background(), channelCmd); err == nil {
|
||||
t.Error("expected an error when no channel is configured")
|
||||
}
|
||||
})
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 555, nil)
|
||||
delivered, err := exec.Handle(context.Background(), channelCmd)
|
||||
delivered, _, err := exec.Handle(context.Background(), channelCmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user