Bonus: Building a Telegram Bot, and How Best to Pair It with a Mini App
番外:Telegram 機器人怎麼做,搭配 Mini App 怎樣比較好
Using the shop as the example: what a bot is good at and what a Mini App is good at, and when to use only one of them. Then, step by step: create the bot with BotFather, set commands and the menu button, choose between long polling and webhooks, write commands, inline buttons and order notifications in Go with plain net/http, build a shopping Mini App in SvelteKit, validate initData on the backend, and finish with deployment and the payment rules.
In this article
- What this article solves
- Step 1: What bots and Mini Apps are each good at
- Step 2: Create the bot with BotFather and get the token
- Step 3: Set the commands and the menu button
- Step 4: A Bot API client with net/http
- Step 5: Receiving updates: long polling or a webhook
- Step 6: Commands, inline keyboards and callback queries
- Step 7: Order-status notifications and rate limits
- Step 8: A shopping Mini App with SvelteKit
- Step 9: Validating initData on the backend
- Step 10: Deployment: HTTPS, domains and secrets
- Step 11: Payments: physical goods and Telegram Stars
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Bonus: SvelteKit Basics: Project Structure, Working with AI Skills and Automatic Deployment”, built the shop's back office in SvelteKit and deployed it automatically on every push to GitHub. This one goes a step further out. Some of the shop's customers keep Telegram open all day, and they would rather check orders and receive notifications in their messaging app than open a website. Telegram offers two things for reaching them: bots and Mini Apps. This article starts with the concepts, what each is good at and how to combine them, then writes the bot backend in Go and the Mini App in SvelteKit, and connects both to the existing order service.
What this article solves
The operations team's request is concrete: after ordering, customers want “paid” and “shipped” notifications in Telegram; they want to type /orders and see their recent orders; ideally they could also browse products and order inside Telegram without switching to a browser. The team got stuck on a few questions straight away:
- How do a bot and a Mini App differ? Is a bot alone enough, or do we need a Mini App?
- How is a bot created, and where does its token live? How are the command list and the button next to the input field configured?
- How do messages come in? Long polling or a webhook? If Telegram delivers the same update twice, do we process it twice?
- When the Mini App places an order, how does the backend know who the user is? Can we trust a user ID sent by the front end?
- Will notifications be blocked if we send too fast? How do we retry if they are?
- Can we take payment inside Telegram?
This article works through it step by step:
- How the bot and the Mini App divide the work, and when to use only one of them.
- Creating the bot with BotFather, getting the token, setting commands and the menu button.
- A small Bot API client with
net/http, including errors and retrying on 429. - Long polling versus webhooks, and de-duplicating on
update_id. - Commands, inline keyboards and callback queries, plus order-status notifications.
- A shopping Mini App in SvelteKit, and why not
sendData. - Validating
initDataon the backend, with tests. - Deployment, secrets and Telegram's payment rules.
Step 1: What bots and Mini Apps are each good at
A bot is a Telegram account controlled by your program. When users type or tap buttons in the chat, Telegram wraps those actions into updates and hands them to your program; your program calls the Bot API to reply. Its interface is the chat itself: text, buttons and images.
A Mini App is a web page opened inside Telegram. It is ordinary HTML, CSS and JavaScript running in the WebView built into the Telegram app, plus a script, telegram-web-app.js, that lets the page read the user's details and use Telegram's theme colours and bottom buttons.
Figure: The bot reaches and reminds users in the chat; the Mini App lets them do real work. Both connect to the same Go backend and use the same Telegram user identity.
The biggest differences are who speaks first and how rich the interface can be:
| Aspect | Bot | Mini App |
|---|---|---|
| Interface | Text, inline buttons, reply keyboards | A full web page with any layout |
| Reaching out | Can message users first (the shop only messages those who sent /start) | No, it exists only while the user has it open |
| Suited operations | One or two steps: check status, confirm, cancel | Multi-step, comparing or forms: browse, cart, checkout |
| Development cost | Backend only | Backend plus a front-end project |
| State | Each update must recover its context from a database | The page itself holds the state of the task |
So each of the three combinations has its place:
| Approach | Fits | Why | When not to use it |
|---|---|---|---|
| Bot only | Shipping alerts, order lookups, on-call alerts, simple confirmations or polls | Quickest to build; notifications are what chat does best | Viewing images, comparing products or filling many fields with buttons becomes painful |
| Mini App only | Something that is an app in itself: a small game, a tool, a campaign page | A full interface, opened from a link or the bot's profile | When you need to notify users later, there is no channel to reach them without a bot |
| Both | Shops, bookings, memberships: browse, order, and be notified afterwards | The bot is the entry point and notifier; the Mini App is the working screen | If all you need is notifications, an extra front end only adds maintenance |
Figure: First ask whether users need to browse, compare or fill in forms; if not, use a bot only. If they do, ask whether you also need chat notifications or commands; if so, combine both.
The shop is a textbook case for “both”: browsing and the cart need a screen, and shipping needs notifications. With the division settled, the rest of the design is clear: the bot does not run the shopping flow, and the Mini App does not send notifications; both share one backend service, shop-telegram.
Step 2: Create the bot with BotFather and get the token
A bot must first be registered inside Telegram. Telegram provides an official bot, @BotFather, for creating and managing bots.
Figure: Illustration; the actual wording is whatever Telegram shows. (1) Send /newbot; (2) enter a display name; (3) enter a username ending in bot; (4) BotFather replies with the token.
According to the official documentation:
- The name is shown in contact details and elsewhere, and can be changed later.
- The username is used in search, mentions and
t.melinks. It is 5 to 32 characters long, may only contain Latin letters, digits and underscores, must end inbot(for exampleexample_shop_bot), and cannot be changed afterwards. - The token looks like
110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw(the example in the docs). You need it to call the Bot API, and anyone who has it can control the bot. If it leaks or is lost, use/tokenin BotFather to generate a new one.
Treat the token like a database password: keep it in a secret store (a Kubernetes Secret, a cloud Secret Manager and so on), pass it to the program as an environment variable, and never put it in code, in Git or in logs. In practice, create one bot for testing and another for production, with separate tokens; the test environment points its webhook at a test URL and cannot message real customers by accident.
Step 3: Set the commands and the menu button
Once the bot exists, users need to know what it does. Two things to configure: the command list and the menu button.
The command list decides the suggestions users see when they type / in the chat. The official docs ask every bot to support /start (begin the interaction) and /help; commands must start with / and be at most 32 characters.
Figure: Illustration. (1) Send /setcommands to BotFather; (2) choose the bot; (3) send the command list as prompted; (4) from then on, typing / in the chat with the bot shows the commands and their descriptions.
The menu button sits to the left of the input field. By default it opens the command list; since Bot API 6.0 it can launch a Mini App instead. The docs list two ways to configure it: for all users, BotFather's /setmenubutton or Menu Button under Bot Settings; per user (for example to change the label by language), the Bot API method setChatMenuButton.
Figure: Illustration. (1) Send /mybots and pick the bot; (2) open Bot Settings; (3) choose Menu Button and enter the label and the Mini App's HTTPS URL; (4) a “Shop” button appears next to the user's input field. The other entry, Configure Mini App, enables the Main Mini App: the bot's profile gains a launch button, and https://t.me/<username>?startapp links open it.
Clicking through BotFather is intuitive, but those clicks leave no record and must be repeated for every environment. For a real project, configure it from code: call setMyCommands, setChatMenuButton and setWebhook once during deployment, so the configuration lives in version control and the test and production environments match. In BotCommand, command is 1 to 32 characters of lowercase English letters, digits and underscores; description is 1 to 256 characters.
package telegram
import "context"
// Setup runs once per deployment: it sets the command list, the menu button and the webhook.
// Same effect as configuring BotFather by hand, but versioned and run once per environment.
func (b *Bot) Setup(ctx context.Context, webhookURL, secret string) error {
if err := b.API.Call(ctx, "setMyCommands", map[string]any{
"commands": []BotCommand{
{Command: "start", Description: "Get started and open the shop"},
{Command: "orders", Description: "Show recent orders"},
},
}, nil); err != nil {
return err
}
if err := b.API.Call(ctx, "setChatMenuButton", map[string]any{
"menu_button": map[string]any{
"type": "web_app",
"text": "Shop",
"web_app": WebAppInfo{URL: b.MiniAppURL},
},
}, nil); err != nil {
return err
}
return b.API.Call(ctx, "setWebhook", map[string]any{
"url": webhookURL, // e.g. https://shop.example.com/telegram/webhook
"secret_token": secret, // 1-256 characters, only A-Z a-z 0-9 _ -
"allowed_updates": []string{"message", "callback_query"},
}, nil)
}The Client, Bot and types used in Setup appear over the next few steps. BotFather remains the only way to create the bot and get its token; everything else can be left to code.
Step 4: A Bot API client with net/http
The Bot API is a very plain HTTP interface: each method is https://api.telegram.org/bot<token>/<method name>, parameters can be sent as JSON, and the response is always a JSON object with a Boolean field ok. On success the result is in result; on failure there is a description, plus an error_code whose contents, the docs say, may change in the future. Some errors also carry parameters, whose retry_after is the number of seconds to wait before the request can be repeated after hitting flood control.
Go has several third-party Telegram packages. This article uses net/http directly for three reasons: the shop needs only a handful of methods; all behaviour is visible and testable; and the Bot API adds fields often, so declaring only the fields you use means you never wait for a package to catch up. If you need many methods (all kinds of media, group administration), a maintained package will save effort.
package telegram
// Only the fields this shop uses; encoding/json skips the rest.
type Update struct {
UpdateID int64 `json:"update_id"`
Message *Message `json:"message,omitempty"`
CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
}
type Message struct {
MessageID int64 `json:"message_id"`
From *User `json:"from,omitempty"`
Chat Chat `json:"chat"`
Text string `json:"text,omitempty"`
}
type Chat struct {
ID int64 `json:"id"`
Type string `json:"type"`
}
type User struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
LanguageCode string `json:"language_code,omitempty"`
}
type CallbackQuery struct {
ID string `json:"id"`
From User `json:"from"`
Message *Message `json:"message,omitempty"`
Data string `json:"data,omitempty"`
}
type InlineKeyboardMarkup struct {
InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
}
type InlineKeyboardButton struct {
Text string `json:"text"`
CallbackData string `json:"callback_data,omitempty"` // 1-64 bytes
WebApp *WebAppInfo `json:"web_app,omitempty"`
}
type WebAppInfo struct {
URL string `json:"url"` // must be HTTPS
}
type BotCommand struct {
Command string `json:"command"`
Description string `json:"description"`
}package telegram
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"time"
)
// Client calls the Bot API with net/http directly, with no third-party library.
type Client struct {
BaseURL string // https://api.telegram.org in production, an httptest URL in tests
Token string
HTTP *http.Client // Timeout must exceed the getUpdates timeout
MaxRetries int // how many extra attempts after a 429
sleep func(context.Context, time.Duration) error // replaced in tests so they do not really wait
}
// APIError is returned when the Bot API answers ok=false.
type APIError struct {
Method string
Code int
Description string
RetryAfter int // seconds; set only when flood control was hit
}
func (e *APIError) Error() string {
return fmt.Sprintf("telegram %s: %d %s", e.Method, e.Code, e.Description)
}
type apiResponse struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result"`
Description string `json:"description"`
ErrorCode int `json:"error_code"`
Parameters *struct {
RetryAfter int `json:"retry_after"`
} `json:"parameters"`
}
// Call invokes a Bot API method; params are sent as JSON and result is decoded into out (may be nil).
func (c *Client) Call(ctx context.Context, method string, params, out any) error {
body, err := json.Marshal(params)
if err != nil {
return err
}
for attempt := 0; ; attempt++ {
err := c.do(ctx, method, body, out)
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.RetryAfter == 0 || attempt >= c.MaxRetries {
return err
}
// retry only when Telegram says how long to wait, and wait exactly retry_after
if err := c.wait(ctx, time.Duration(apiErr.RetryAfter)*time.Second); err != nil {
return err
}
}
}
func (c *Client) do(ctx context.Context, method string, body []byte, out any) error {
endpoint := c.BaseURL + "/bot" + c.Token + "/" + method
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("telegram %s: build request failed", method) // never put the URL in an error: it contains the token
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTP.Do(req)
if err != nil {
var ue *url.Error
if errors.As(err, &ue) {
err = ue.Err // url.Error would log the full URL including the token; keep only the cause
}
return fmt.Errorf("telegram %s: %w", method, err)
}
defer resp.Body.Close()
var r apiResponse
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return fmt.Errorf("telegram %s: decode response (HTTP %d): %w", method, resp.StatusCode, err)
}
if !r.OK {
e := &APIError{Method: method, Code: r.ErrorCode, Description: r.Description}
if r.Parameters != nil {
e.RetryAfter = r.Parameters.RetryAfter
}
return e
}
if out == nil {
return nil
}
return json.Unmarshal(r.Result, out)
}
func (c *Client) wait(ctx context.Context, d time.Duration) error {
if c.sleep != nil {
return c.sleep(ctx, d)
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}The design points:
- No URL in errors. The token is part of the URL, and the
*url.Errorreturned bynet/httpputs the full URL in its message; once logged, the token has leaked.dounwraps*url.Errorand keeps only the underlying cause. - Retry only on
retry_after. The docs say plainly thatretry_afteris the number of seconds to wait before repeating, so we wait exactly that long and retry, with a cap ofMaxRetries. Other errors (bad parameters, say) will not succeed on retry, so they are returned. - No automatic retry on network errors. If the connection drops after
sendMessagewas sent, you cannot know whether Telegram received it; retrying automatically might give the user the same notification twice. Such errors are left to the caller; in Step 7 the message queue redelivers, accepting the occasional duplicate notification. The general rules for retries are in “Timeouts, Retries and Circuit Breakers”. sleepis replaceable, so tests do not really wait seven seconds.
Step 5: Receiving updates: long polling or a webhook
Each user action (a message, a button tap) becomes an update. The Bot API offers two mutually exclusive ways to receive them: long polling with getUpdates, or setWebhook so Telegram sends them to you. Either way, updates not yet collected are kept for at most 24 hours.
Figure: With long polling your service keeps asking and Telegram answers when updates arrive; with a webhook Telegram POSTs to your URL over HTTPS with a secret header, and retries when the response is not 2xx.
| Aspect | Long polling (getUpdates) | Webhook (setWebhook) |
|---|---|---|
| Needs a public URL | No, the service connects outwards | Yes, an HTTPS URL on port 443, 80, 88 or 8443 |
| Confirmation | The next call's offset exceeds the update_id | A 2xx response; any other status is retried |
| Several replicas | Only one process may poll at a time | Any replica can take requests; max_connections 1–100, default 40 |
| Verifying the source | Not needed, you are asking Telegram | secret_token, checked in X-Telegram-Bot-Api-Secret-Token |
| Fits | Local development, internal networks, single-replica tools | Production, several replicas, an existing HTTPS entry point |
They are mutually exclusive: while a webhook is set, getUpdates does not work; to go back to long polling, call deleteWebhook first.
For long polling, offset is what matters. In the docs' words, offset must be one greater than the highest update_id received so far, and an update counts as confirmed as soon as getUpdates is called with an offset higher than its update_id. timeout is the long-polling time in seconds; the default 0 is ordinary short polling, which the docs say should be used only for testing. limit accepts 1–100 and defaults to 100.
For webhooks, what matters is verifying the source and handling retries. setWebhook accepts a secret_token (1–256 characters, only A-Z, a-z, 0-9, _ and -); from then on every webhook request carries an X-Telegram-Bot-Api-Secret-Token header with that value. Without this check, anyone who knows the URL can forge updates. When Telegram gets a non-2xx response it repeats the request and gives up after a reasonable number of attempts.
Retries mean the same update may arrive twice. The update_id in Update is exactly what you need: the docs say identifiers start from some positive number and increase sequentially, which makes them especially handy for ignoring repeated updates when using webhooks. (The docs also note that if there are no new updates for at least a week, the next identifier is chosen at random, so do not treat it as a sequence that is always contiguous.)
Figure: Check the secret, decode the JSON, then de-duplicate on update_id; only a first-seen update is handled.
package telegram
import (
"context"
"crypto/subtle"
"database/sql"
"encoding/json"
"log/slog"
"net/http"
"time"
)
// Dedup answers whether an update_id is seen for the first time.
type Dedup interface {
FirstTime(ctx context.Context, updateID int64) (bool, error)
}
// PGDedup de-duplicates with a PostgreSQL primary key shared by all replicas.
//
// CREATE TABLE telegram_updates (
// update_id bigint PRIMARY KEY,
// received_at timestamptz NOT NULL DEFAULT now()
// );
type PGDedup struct{ DB *sql.DB }
func (d PGDedup) FirstTime(ctx context.Context, updateID int64) (bool, error) {
res, err := d.DB.ExecContext(ctx,
`INSERT INTO telegram_updates (update_id) VALUES ($1) ON CONFLICT DO NOTHING`, updateID)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n == 1, err
}
const secretHeader = "X-Telegram-Bot-Api-Secret-Token"
// WebhookHandler receives updates that Telegram POSTs over HTTPS.
func (b *Bot) WebhookHandler(secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
got := r.Header.Get(secretHeader)
if subtle.ConstantTimeCompare([]byte(got), []byte(secret)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var u Update
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&u); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
first, err := b.Dedup.FirstTime(r.Context(), u.UpdateID)
if err != nil {
// nothing recorded yet: answer 5xx so Telegram retries
http.Error(w, "try again", http.StatusInternalServerError)
return
}
if first {
if err := b.Handle(r.Context(), u); err != nil {
// the update_id is recorded and a retry would be skipped, so log and still answer 200
slog.ErrorContext(r.Context(), "telegram update failed", "update_id", u.UpdateID, "err", err)
}
}
w.WriteHeader(http.StatusOK)
})
}
// Poll long-polls getUpdates, for local development or environments without a public HTTPS URL.
func (b *Bot) Poll(ctx context.Context) error {
var offset int64
for {
var updates []Update
err := b.API.Call(ctx, "getUpdates", map[string]any{
"offset": offset,
"timeout": 30, // seconds; Client.HTTP.Timeout must be longer
"allowed_updates": []string{"message", "callback_query"},
}, &updates)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
slog.ErrorContext(ctx, "getUpdates failed", "err", err)
if err := b.API.wait(ctx, 3*time.Second); err != nil {
return err
}
continue
}
for _, u := range updates {
if err := b.Handle(ctx, u); err != nil {
slog.ErrorContext(ctx, "telegram update failed", "update_id", u.UpdateID, "err", err)
}
offset = u.UpdateID + 1 // passing this offset next time confirms the earlier updates
}
}
}There is a trade-off to think through here: record the update_id first, then process. If processing fails halfway, the update is already recorded, the retry is skipped, and the user effectively gets no reply. The other order, process then record, means that when processing succeeds but recording fails, the retry processes it again. For bot replies, an occasional missing reply is fine, since the user just taps again; running something twice can cause a duplicate action. So this handler chooses “at most once”: a processing error is logged and the response is still 200.
Actions that really change data (placing or cancelling an order) do not rely on this table; they rely on the order service's idempotency key, as described in “Idempotency and Distributed Locks”. The telegram_updates table only filters retries, and rows older than a few days can be deleted periodically.
Poll lets the same Bot.Handle run in both modes: long polling for local development, without exposing your machine to the internet, and a webhook in production. Note that Client.HTTP's Timeout must exceed the getUpdates timeout, or your own HTTP client will cut every long poll short.
Step 6: Commands, inline keyboards and callback queries
Once an update arrives, the shop's own logic takes over. Everything the bot needs is in the existing order service; the bot calls it only through the Orders interface and stores no orders itself.
An inline keyboard is a set of buttons attached under a particular message. The official docs explain that pressing an inline button does not send a message to the chat, and that buttons can be callback buttons, URL buttons and others. Besides text, exactly one other field of InlineKeyboardButton decides the button's type; the shop uses two:
callback_data: sent back to the bot when pressed, 1–64 bytes.web_app: opens the Mini App when pressed;WebAppInfo.urlmust be HTTPS. The docs note this button is available only in private chats between a user and the bot.
When a user presses a callback button, the bot receives a callback query. The docs stress that after the user presses the button, the Telegram client shows a progress bar until the bot calls answerCallbackQuery, so call it even if no notification needs to be shown.
Figure: After the tap, the bot first answers the callback query so the button stops loading, then asks the order service, and finally updates the message in place with editMessageText, so no new message appears in the chat.
package telegram
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
// Order is the order summary returned by the order service; amounts are integer minor units.
type Order struct {
ID string `json:"id"`
Status string `json:"status"`
Amount int64 `json:"amount"`
Currency string `json:"currency"`
CreatedAt time.Time `json:"created_at"`
}
type PlaceOrderRequest struct {
TelegramUserID int64
IdempotencyKey string
Items []OrderItem
}
type OrderItem struct {
ProductID string `json:"product_id"`
Quantity int `json:"quantity"`
}
var ErrNotFound = errors.New("not found")
// Orders wraps calls to the existing order service; the bot stores no orders itself.
type Orders interface {
ListByTelegramUser(ctx context.Context, userID int64, limit int) ([]Order, error)
GetForTelegramUser(ctx context.Context, userID int64, orderID string) (Order, error)
Place(ctx context.Context, req PlaceOrderRequest) (Order, error)
}
// Chats remembers which user sent /start in which chat; notifications go only to those chats.
type Chats interface {
Save(ctx context.Context, userID, chatID int64) error
ChatFor(ctx context.Context, userID int64) (chatID int64, ok bool, err error)
}
type Bot struct {
API *Client
Orders Orders
Chats Chats
Dedup Dedup
MiniAppURL string // e.g. https://shop.example.com/tg/
}
// Handle processes one update; the returned error is only logged.
func (b *Bot) Handle(ctx context.Context, u Update) error {
switch {
case u.Message != nil && u.Message.From != nil:
return b.onMessage(ctx, u.Message)
case u.CallbackQuery != nil:
return b.onCallback(ctx, u.CallbackQuery)
}
return nil // ignore update types we did not subscribe to
}
func (b *Bot) onMessage(ctx context.Context, m *Message) error {
switch command(m.Text) {
case "/start":
if m.Chat.Type == "private" {
if err := b.Chats.Save(ctx, m.From.ID, m.Chat.ID); err != nil {
return err
}
}
return b.send(ctx, m.Chat.ID, "Welcome. Tap Open shop to browse, or use /orders to see your orders.", &InlineKeyboardMarkup{
InlineKeyboard: [][]InlineKeyboardButton{
{{Text: "Open shop", WebApp: &WebAppInfo{URL: b.MiniAppURL}}},
{{Text: "My orders", CallbackData: "orders"}},
},
})
case "/orders":
return b.sendOrderList(ctx, m.Chat.ID, m.From.ID)
default:
return b.send(ctx, m.Chat.ID, "Commands: /start, /orders", nil)
}
}
// command returns the first word without the @botname suffix used in groups.
func command(text string) string {
first, _, _ := strings.Cut(text, " ")
name, _, _ := strings.Cut(first, "@")
return strings.ToLower(name)
}
func (b *Bot) sendOrderList(ctx context.Context, chatID, userID int64) error {
orders, err := b.Orders.ListByTelegramUser(ctx, userID, 5)
if err != nil {
return err
}
if len(orders) == 0 {
return b.send(ctx, chatID, "You have no orders yet.", nil)
}
kb := &InlineKeyboardMarkup{}
for _, o := range orders {
label := fmt.Sprintf("%s · %s · %s", o.CreatedAt.Format("01/02"), statusText(o.Status), money(o.Amount, o.Currency))
kb.InlineKeyboard = append(kb.InlineKeyboard, []InlineKeyboardButton{
{Text: label, CallbackData: "order:" + o.ID}, // UUID plus prefix is 42 bytes, within the 64-byte limit
})
}
return b.send(ctx, chatID, "Recent orders:", kb)
}
func (b *Bot) onCallback(ctx context.Context, q *CallbackQuery) error {
// answer first so the button stops loading; call it even with nothing to show
if err := b.API.Call(ctx, "answerCallbackQuery", map[string]any{"callback_query_id": q.ID}, nil); err != nil {
return err
}
if q.Message == nil {
return nil
}
chatID := q.Message.Chat.ID
switch {
case q.Data == "orders":
return b.sendOrderList(ctx, chatID, q.From.ID)
case strings.HasPrefix(q.Data, "order:"):
// callback_data comes from the client: it only says which order to show; re-check access with q.From.ID
o, err := b.Orders.GetForTelegramUser(ctx, q.From.ID, strings.TrimPrefix(q.Data, "order:"))
if errors.Is(err, ErrNotFound) {
return b.send(ctx, chatID, "Order not found.", nil)
}
if err != nil {
return err
}
return b.API.Call(ctx, "editMessageText", map[string]any{
"chat_id": chatID,
"message_id": q.Message.MessageID,
"text": orderText(o),
"reply_markup": InlineKeyboardMarkup{InlineKeyboard: [][]InlineKeyboardButton{
{{Text: "Refresh", CallbackData: "order:" + o.ID}, {Text: "All orders", CallbackData: "orders"}},
}},
}, nil)
}
return nil
}
func (b *Bot) send(ctx context.Context, chatID int64, text string, kb *InlineKeyboardMarkup) error {
params := map[string]any{"chat_id": chatID, "text": text}
if kb != nil {
params["reply_markup"] = kb
}
return b.API.Call(ctx, "sendMessage", params, nil)
}
func orderText(o Order) string {
return fmt.Sprintf("Order %s\nStatus: %s\nAmount: %s\nCreated: %s",
o.ID, statusText(o.Status), money(o.Amount, o.Currency), o.CreatedAt.Format("2006-01-02 15:04"))
}
func statusText(s string) string {
switch s {
case "pending":
return "awaiting payment"
case "paid":
return "paid"
case "shipped":
return "shipped"
case "cancelled":
return "cancelled"
}
return s
}
// shortcut: assumes two decimal places; look up a currency table once zero-decimal currencies such as JPY are needed.
func money(minor int64, currency string) string {
return fmt.Sprintf("%s %d.%02d", currency, minor/100, minor%100)
}Points worth noticing:
callback_datais data from the client. Telegram returns it as is, but does not promise it came from a button you sent (the docs also warn that the originating message may contain no button with that data). Soorder:o-1only means “the user wants to see o-1”; whether they may is re-decided by theorderservice usingq.From.ID.GetForTelegramUserreturnsErrNotFoundboth when the order does not exist and when it belongs to someone else, revealing nothing.- The 64-byte limit: a UUID is 36 characters, plus
order:makes 42 bytes, which fits. If a button needs to carry more, store it in the database and put only a short ID on the button. - Update the original message with
editMessageText, so the chat is not flooded with order-status messages; the Refresh button uses the same flow. - Save the chat ID on
/start, in private chats only. The next step's notifications go only to saved chats. - Amounts are
int64minor units, converted to decimals only for display; see “Handling Money in Go: Minor Units, Decimals, Currencies, Rounding and Allocation”.
The telegram_chats table is simple:
CREATE TABLE telegram_chats (
telegram_user_id bigint PRIMARY KEY,
chat_id bigint NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);Telegram user IDs may exceed 32 bits (the docs say at most 52 significant bits), so use int64 in Go and bigint in PostgreSQL, never int or integer.
Step 7: Order-status notifications and rate limits
Notifications are where a bot earns its keep. The order service already publishes order.paid and order.shipped to NATS JetStream on payment and shipment (see “Message Queues and Event-Driven Design”); shop-telegram simply subscribes to those two events, and the order service does not need to know Telegram exists.
Figure: When an event arrives, look up the user's chat ID, throttle, then call sendMessage; on 429, wait retry_after seconds and retry.
package telegram
import (
"context"
"fmt"
)
// NotifyOrderStatus tells the user an order changed status; the order-event consumer calls it.
func (b *Bot) NotifyOrderStatus(ctx context.Context, userID int64, o Order) error {
chatID, ok, err := b.Chats.ChatFor(ctx, userID)
if err != nil {
return err
}
if !ok {
return nil // users who never sent /start are not notified
}
text := fmt.Sprintf("Order status update: %s\n%s", statusText(o.Status), orderText(o))
return b.send(ctx, chatID, text, &InlineKeyboardMarkup{InlineKeyboard: [][]InlineKeyboardButton{
{{Text: "View order", CallbackData: "order:" + o.ID}},
}})
}The consumer side does two things: skip orders that did not come from Telegram, and throttle. Subscribing is covered in “Event-Driven Go with Watermill: What It Is, What It Solves, and Wiring It to an Outbox”; here is just the handler:
// fragment: handler for order events
throttle := time.NewTicker(time.Second / 25) // below the FAQ's ~30 per second
defer throttle.Stop()
handle := func(ctx context.Context, ev OrderStatusChanged) error {
if ev.TelegramUserID == 0 {
return nil // not an order placed through Telegram
}
select {
case <-throttle.C:
case <-ctx.Done():
return ctx.Err()
}
return bot.NotifyOrderStatus(ctx, ev.TelegramUserID, ev.Order)
}The official FAQ describes the limits like this (free tier):
- A single chat: avoid more than one message per second. Short bursts may be allowed, but eventually you will get 429 errors.
- A group: no more than 20 messages per minute.
- Bulk notifications: about 30 messages per second; beyond that, 429 errors. Paid broadcasts can be enabled in BotFather, up to 1000 messages per second, at 0.1 Telegram Stars per message above the free amount; enabling it requires at least 100,000 Stars on the bot's balance and at least 100,000 monthly active users.
The shop's notification volume is far below these limits, but a big sale that ships thousands of orders at once could hit 30 per second. So the global throttle is set to 25 per second, leaving some headroom; one user's order rarely changes status twice within a second, so there is no separate per-chat throttle. If a 429 still arrives, Client waits retry_after and resends.
When NotifyOrderStatus returns an error, the message queue redelivers later, which may send a notification twice. For “shipped”, an occasional duplicate is acceptable; if it is not, de-duplicate on “order ID plus status” before sending. Also, once a user blocks the bot, sends keep failing; the docs explain that in private chats the bot receives a my_chat_member update when it is blocked or unblocked, which you can use to mark the telegram_chats row inactive and stop trying.
Step 8: A shopping Mini App with SvelteKit
A Mini App is a web page, so we build it with SvelteKit from the previous article. The shop's Mini App has just two screens: the product list and the cart.
Figure: Illustration. (1) Tap the “Shop” menu button in the chat to open the Mini App; (2) the product list; (3) the MainButton at the bottom shows the cart count; (4) the BackButton appears at the top of the cart page; (5) the MainButton becomes “Place order” and shows a progress indicator while sending.
Load telegram-web-app.js. The official docs require the script in <head>, before any other scripts. SvelteKit's src/app.html is exactly that place:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://telegram.org/js/telegram-web-app.js?65"></script>
%sveltekit.head%
</head>
<body>
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>Once loaded, window.Telegram.WebApp exists. It exists only in the browser, so the whole Mini App turns off server-side rendering and is output as a single-page app with adapter-static, served under /tg/:
// svelte.config.js
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({ fallback: 'index.html' }),
paths: { base: '/tg' }
}
};// src/routes/+layout.ts
export const ssr = false; // Telegram.WebApp exists only in the browser// src/app.d.ts (simplified: only what we use)
declare global {
interface Window {
Telegram: { WebApp: any };
}
}
export {};Then the page itself, written with Svelte 5 runes:
<script lang="ts">
import { onMount } from 'svelte';
type Product = { id: string; name: string; price: number; currency: string }; // price is in minor units
const tg = window.Telegram.WebApp; // ssr = false, so this only runs in the browser
let products = $state<Product[]>([]);
let cart = $state<Record<string, number>>({});
let view = $state<'list' | 'cart'>('list');
let notice = $state('');
let idempotencyKey = crypto.randomUUID(); // one key per intent to submit
const count = $derived(Object.values(cart).reduce((a, n) => a + n, 0));
const total = $derived(products.reduce((s, p) => s + p.price * (cart[p.id] ?? 0), 0));
const money = (minor: number) => (minor / 100).toFixed(2);
onMount(async () => {
tg.ready(); // hide Telegram's loading placeholder
tg.expand(); // expand to the maximum height
products = await (await fetch('/api/telegram/products')).json();
});
// MainButton: "View cart" on the list, "Place order" on the cart
$effect(() => {
const mb = tg.MainButton;
if (count === 0) {
mb.hide();
return;
}
mb.setText(view === 'list' ? `View cart (${count})` : `Place order ${money(total)}`);
mb.show();
const onClick = view === 'list' ? () => (view = 'cart') : placeOrder;
mb.onClick(onClick);
return () => mb.offClick(onClick); // remove the old handler on page change so it does not fire twice
});
// BackButton: only on the cart page
$effect(() => {
const bb = tg.BackButton;
if (view !== 'cart') {
bb.hide();
return;
}
bb.show();
const back = () => (view = 'list');
bb.onClick(back);
return () => bb.offClick(back);
});
async function placeOrder() {
tg.MainButton.showProgress();
try {
const res = await fetch('/api/telegram/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Telegram-Init-Data': tg.initData, // the raw string, for the backend to verify
'Idempotency-Key': idempotencyKey
},
// products and quantities only, never prices
body: JSON.stringify({
items: Object.entries(cart).map(([product_id, quantity]) => ({ product_id, quantity }))
})
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
cart = {};
view = 'list';
idempotencyKey = crypto.randomUUID();
notice = 'Order placed. The bot will tell you about status changes.';
} catch {
notice = 'Sending failed. Tap again (it will not order twice).';
} finally {
tg.MainButton.hideProgress();
}
}
function add(id: string) {
cart[id] = (cart[id] ?? 0) + 1;
}
function remove(id: string) {
if (--cart[id] <= 0) delete cart[id];
}
</script>
{#if notice}<p class="notice">{notice}</p>{/if}
{#if view === 'list'}
<ul>
{#each products as p (p.id)}
<li>
<span>{p.name}</span>
<span class="hint">{p.currency} {money(p.price)}</span>
<button onclick={() => add(p.id)}>Add</button>
</li>
{/each}
</ul>
{:else}
<ul>
{#each products.filter((p) => cart[p.id]) as p (p.id)}
<li>
<span>{p.name} × {cart[p.id]}</span>
<button onclick={() => remove(p.id)} aria-label="Remove one {p.name}">−</button>
</li>
{/each}
</ul>
{/if}
<style>
/* telegram-web-app.js exposes theme colours as CSS variables; the second value is a fallback for a plain browser */
:global(body) {
background: var(--tg-theme-bg-color, #fff);
color: var(--tg-theme-text-color, #222);
}
.hint {
color: var(--tg-theme-hint-color, #888);
}
button {
background: var(--tg-theme-button-color, #2481cc);
color: var(--tg-theme-button-text-color, #fff);
border: 0;
border-radius: 6px;
padding: 0.4rem 0.8rem;
}
li {
display: flex;
gap: 0.5rem;
align-items: center;
justify-content: space-between;
padding: 0.5rem 0;
}
</style>The Mini App APIs this code uses:
| API | Purpose |
|---|---|
ready() | Tells Telegram the interface can be shown and hides the loading placeholder; the docs recommend calling it as early as possible |
expand() | Expands the Mini App to the maximum available height |
MainButton | The main button at the bottom: setText, show, hide, onClick, offClick, showProgress, hideProgress |
BackButton | The back button in the header: show, hide, onClick, offClick |
initData | The raw query string, passed to the backend for validation |
CSS variables such as --tg-theme-bg-color | Telegram's current theme colours, which follow the user into dark mode |
Theme colours: each themeParams field (bg_color, text_color, hint_color, button_color, button_text_color and so on) has a matching CSS variable named --tg-theme- plus the field name with underscores turned into hyphens. Use these variables directly in CSS and the Mini App matches the user's Telegram colours; the fallback values are for opening the page in a normal browser during development.
MainButton and $effect: a handler registered with onClick is not replaced automatically, so on a page change you must remove the old one with offClick, or a single tap fires two handlers. Registering inside $effect and calling offClick in its cleanup function lets Svelte clean up and re-register whenever the state it depends on changes.
Why not sendData? The Mini App API has a tempting Telegram.WebApp.sendData(data) that sends data straight to the bot. But the docs are clear: it is only available for Mini Apps launched from a keyboard button, the data is at most 4096 bytes and reaches the bot as a service message, and the Mini App closes once it is called.
Figure: sendData suits one-off input such as “pick a date and close”; to place an order and learn whether it worked, call your own backend with fetch and initData.
The shop's Mini App is opened from the menu button and inline buttons, where sendData is not available at all; and placing an order needs a result (success, sold out, network error), which there is no chance to show once the Mini App has closed. The docs also state that initData is empty when the Mini App is launched from a keyboard button or from inline mode. So the shop calls the Go backend directly with fetch, sending an Idempotency-Key: if the user taps Send, the network times out and they tap again, the order service sees the same key and creates only one order.
One domain: the Mini App lives at https://shop.example.com/tg/ and the API at /api/telegram/ on the same domain, so the browser treats them as same-origin and there is no CORS to handle. If the site has a Content Security Policy, remember to allow scripts from https://telegram.org.
Step 9: Validating initData on the backend
When the Mini App opens, Telegram.WebApp offers the user data twice: initDataUnsafe is a parsed object and initData is the raw string. The docs put a warning next to initDataUnsafe: data from this field should not be trusted; the server should use only initData, and only after validating it. The reason is simple: the Mini App is a web page running on the user's device, and anyone can open the developer tools and change user.id to someone else's.
Validation uses HMAC-SHA256. The docs describe it as follows:
initDatais a query string. Take all received fields, sort them alphabetically by key, write each askey=<value>, and join them with a line feed (0x0A) to get the data-check-string.hashitself is what you compare against, so it is not included.- The secret_key is the HMAC-SHA256 of the bot token, with the constant string
WebAppDataas the key. - Compute HMAC-SHA256 of the data-check-string with secret_key as the key, hex-encode it, and compare with the received
hash; if they match, the data came from Telegram. - To prevent outdated data being reused, you can additionally check
auth_date(the Unix time at which the Mini App received the data).
Figure: Split the fields, sort them and build the data-check-string; derive secret_key from WebAppData and the token; compute the HMAC and compare in constant time; finally check auth_date, and only then trust user.id.
package telegram
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
var (
ErrInitDataInvalid = errors.New("init data: invalid")
ErrInitDataExpired = errors.New("init data: expired")
)
type WebAppUser struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
Username string `json:"username,omitempty"`
LanguageCode string `json:"language_code,omitempty"`
}
type InitData struct {
User WebAppUser
AuthDate time.Time
QueryID string
}
// ValidateInitData checks the raw Telegram.WebApp.initData string sent by the Mini App.
func ValidateInitData(raw, botToken string, maxAge time.Duration, now time.Time) (InitData, error) {
vals, err := url.ParseQuery(raw)
if err != nil {
return InitData{}, ErrInitDataInvalid
}
hash := vals.Get("hash")
if hash == "" {
return InitData{}, ErrInitDataInvalid
}
// data-check-string: every field except hash, sorted by key, key=value lines joined by \n
keys := make([]string, 0, len(vals))
for k, v := range vals {
if len(v) != 1 {
return InitData{}, ErrInitDataInvalid // a repeated key: do not guess which one counts
}
if k != "hash" {
keys = append(keys, k)
}
}
sort.Strings(keys)
lines := make([]string, len(keys))
for i, k := range keys {
lines[i] = k + "=" + vals.Get(k)
}
dataCheck := strings.Join(lines, "\n")
// secret_key = HMAC_SHA256(key="WebAppData", message=bot_token)
secret := hmacSHA256([]byte("WebAppData"), []byte(botToken))
want := hmacSHA256(secret, []byte(dataCheck))
got, err := hex.DecodeString(hash)
if err != nil || !hmac.Equal(got, want) { // hmac.Equal compares in constant time
return InitData{}, ErrInitDataInvalid
}
// only after the signature matches do we check time and parse content
sec, err := strconv.ParseInt(vals.Get("auth_date"), 10, 64)
if err != nil {
return InitData{}, ErrInitDataInvalid
}
authAt := time.Unix(sec, 0)
if now.Sub(authAt) > maxAge || authAt.After(now.Add(time.Minute)) {
return InitData{}, ErrInitDataExpired
}
var user WebAppUser
if err := json.Unmarshal([]byte(vals.Get("user")), &user); err != nil || user.ID == 0 {
return InitData{}, fmt.Errorf("%w: missing user", ErrInitDataInvalid)
}
return InitData{User: user, AuthDate: authAt, QueryID: vals.Get("query_id")}, nil
}
func hmacSHA256(key, msg []byte) []byte {
m := hmac.New(sha256.New, key)
m.Write(msg)
return m.Sum(nil)
}Implementation details:
- Compare with
hmac.Equal, a constant-time comparison that does not return early when the first few bytes match, so the correct value cannot be guessed byte by byte. - Reject a key that appears twice.
url.Values.Gettakes only the first value; an attacker could append a seconduserso that verification and parsing see different values. Rejecting outright is safest. - Verify the signature before looking at time or content. Data with a bad signature does not even need its JSON parsed.
- The
auth_datewindow is a business decision. The shop uses one hour: a user who browses for too long gets a 401 on submit, and the front end asks them to reopen the Mini App. It also rejects times more than a minute in the future, which is beyond normal clock skew. - The
signaturefield: for first-party validation the docs define the data-check-string as all received fields excepthash, sosignatureis included and the code needs no special case for it.signatureis meant for third parties: give theminitDataand your bot ID, and they can verify it with Telegram's published Ed25519 public key without knowing your token. The docs specify that in that case the data-check-string starts with<bot_id>:WebAppDataand excludes bothhashandsignature. The shop's backend has the token, so HMAC is enough.
The test uses a fake token to build valid initData with the same algorithm, then checks that tampered data, the wrong token, expired data, a missing hash and a repeated key are all rejected:
package telegram
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"net/url"
"sort"
"strconv"
"strings"
"testing"
"time"
)
const testToken = "123456:TEST-token-not-real"
// signInitData builds valid initData with a test token, following the documented algorithm.
func signInitData(token string, fields url.Values) string {
keys := make([]string, 0, len(fields))
for k := range fields {
keys = append(keys, k)
}
sort.Strings(keys)
var lines []string
for _, k := range keys {
lines = append(lines, k+"="+fields.Get(k))
}
secret := hmac.New(sha256.New, []byte("WebAppData"))
secret.Write([]byte(token))
m := hmac.New(sha256.New, secret.Sum(nil))
m.Write([]byte(strings.Join(lines, "\n")))
out := url.Values{}
for k, v := range fields {
out[k] = v
}
out.Set("hash", hex.EncodeToString(m.Sum(nil)))
return out.Encode()
}
func TestValidateInitData(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
fields := url.Values{
"auth_date": {strconv.FormatInt(now.Add(-5*time.Minute).Unix(), 10)},
"query_id": {"AAH-test"},
"user": {`{"id":42,"first_name":"Ann","language_code":"zh-hant"}`},
"signature": {"c2lnbmF0dXJl"},
}
valid := signInitData(testToken, fields)
got, err := ValidateInitData(valid, testToken, time.Hour, now)
if err != nil {
t.Fatalf("valid init data rejected: %v", err)
}
if got.User.ID != 42 || got.QueryID != "AAH-test" {
t.Fatalf("unexpected result %+v", got)
}
tampered := strings.Replace(valid, "%22id%22%3A42", "%22id%22%3A43", 1)
if tampered == valid {
t.Fatal("tamper replacement did not apply")
}
cases := map[string]struct {
raw string
token string
now time.Time
want error
}{
"tampered user": {tampered, testToken, now, ErrInitDataInvalid},
"wrong token": {valid, "999:other", now, ErrInitDataInvalid},
"expired": {valid, testToken, now.Add(2 * time.Hour), ErrInitDataExpired},
"from future": {valid, testToken, now.Add(-time.Hour), ErrInitDataExpired},
"no hash": {"auth_date=1&user=%7B%7D", testToken, now, ErrInitDataInvalid},
"empty": {"", testToken, now, ErrInitDataInvalid},
"duplicate key": {valid + "&user=x", testToken, now, ErrInitDataInvalid},
}
for name, c := range cases {
if _, err := ValidateInitData(c.raw, c.token, time.Hour, c.now); !errors.Is(err, c.want) {
t.Errorf("%s: got %v, want %v", name, err, c.want)
}
}
}With validation in place, the ordering API is simple. The user's identity comes only from validated initData; the front end sends only product IDs and quantities, and prices are always computed by the order service from current product data, so any amount sent by the front end is ignored (the test deliberately sends an extra amount, which is dropped):
package telegram
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"time"
)
// InitDataHeader is this shop's own header name, not one defined by Telegram.
const InitDataHeader = "X-Telegram-Init-Data"
type CheckoutHandler struct {
BotToken string
MaxAge time.Duration // e.g. 1 hour: after that the user reopens the Mini App
Orders Orders
Now func() time.Time
}
type checkoutRequest struct {
Items []OrderItem `json:"items"`
}
// ServeHTTP handles POST /api/telegram/orders.
func (h CheckoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
init, err := ValidateInitData(r.Header.Get(InitDataHeader), h.BotToken, h.MaxAge, h.Now())
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
key := r.Header.Get("Idempotency-Key")
if key == "" {
http.Error(w, "missing Idempotency-Key", http.StatusBadRequest)
return
}
var req checkoutRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil || len(req.Items) == 0 {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
for _, it := range req.Items {
if it.ProductID == "" || it.Quantity < 1 || it.Quantity > 99 {
http.Error(w, "bad item", http.StatusBadRequest)
return
}
}
// only products and quantities; the order service prices them from current data, client amounts are never used
o, err := h.Orders.Place(r.Context(), PlaceOrderRequest{
TelegramUserID: init.User.ID, // identity comes only from validated initData
IdempotencyKey: key,
Items: req.Items,
})
if errors.Is(err, ErrNotFound) {
http.Error(w, "product not found", http.StatusUnprocessableEntity)
return
}
if err != nil {
slog.ErrorContext(r.Context(), "place order failed", "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(o)
}The header name X-Telegram-Init-Data is the shop's own choice; Telegram does not say how initData should reach your backend. A header has the advantage that one middleware can validate every API without changing each request's body format.
The package has more tests that use httptest to stand in for api.telegram.org, covering the webhook's secret check and duplicate updates, the permission check on callbacks, retrying 429 with retry_after, the long-polling offset advancing, and the ordering API. See “Testing in Go: Table-Driven Tests, httptest and Integration Tests” for the techniques. None of it needs a real bot or touches Telegram.
Step 10: Deployment: HTTPS, domains and secrets
Figure: Three paths. Commands and buttons arrive through the webhook; the Mini App calls the API on the same domain with initData; order events arrive from NATS and lead to Bot API calls for notifications. All three reach the same shop-telegram service.
Deployment must meet a few hard requirements from Telegram:
| Item | Requirement |
|---|---|
| Webhook URL | HTTPS; port 443, 80, 88 or 8443 only |
| Certificate | Must be valid; for a self-signed one, upload the public key via setWebhook's certificate parameter |
| Others (FAQ) | Redirects are not supported; wildcard certificates may not be; the CN must exactly match the domain |
| Mini App URL | WebAppInfo.url must be HTTPS |
The shop puts everything on one domain, shop.example.com. The existing HTTPS entry point (nginx or a cloud load balancer) terminates TLS and routes by path: /tg/ serves the Mini App's static files, while /api/telegram/ and /telegram/webhook go to shop-telegram. Reverse-proxy configuration is covered in “Go Behind nginx: Security Settings and API Reverse Proxy Configuration”.
The wiring looks roughly like this:
// fragment: how cmd/shop-telegram/main.go wires things together
token := mustEnv("TELEGRAM_BOT_TOKEN")
secret := mustEnv("TELEGRAM_WEBHOOK_SECRET")
api := &telegram.Client{
BaseURL: "https://api.telegram.org",
Token: token,
HTTP: &http.Client{Timeout: 40 * time.Second}, // longer than the 30 s long poll
MaxRetries: 2,
}
bot := &telegram.Bot{API: api, Orders: orders, Chats: chats,
Dedup: telegram.PGDedup{DB: db}, MiniAppURL: "https://shop.example.com/tg/"}
mux := http.NewServeMux()
mux.Handle("POST /telegram/webhook", bot.WebhookHandler(secret))
mux.Handle("POST /api/telegram/orders", telegram.CheckoutHandler{
BotToken: token, MaxAge: time.Hour, Orders: orders, Now: time.Now})
if os.Getenv("TELEGRAM_MODE") == "polling" { // local development: make sure no webhook is set
go bot.Poll(ctx)
}Setup (Step 3) runs once as the last step of the deployment, or as a separate command. After going live, getWebhookInfo shows the current webhook configuration; a bot using long polling gets a result whose url is empty:
curl -s "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getWebhookInfo"Handling secrets:
TELEGRAM_BOT_TOKENandTELEGRAM_WEBHOOK_SECRETboth live in the secret store and reach the container as environment variables. Make the webhook secret a random string (for example 32 bytes encoded as base64url without=), which satisfies theA-Z a-z 0-9 _ -rule.- Mind the logs: if the reverse proxy or a middleware logs request headers, exclude
X-Telegram-Init-Data, which contains user data. - To rotate the token, generate a new one with
/tokenin BotFather, update the secret and redeploy; while the token is being switched the bot may briefly be unable to call the Bot API, so do it when traffic is low.
For configuration and shutdown in general, follow “Configuration and Graceful Shutdown in Go”: on a shutdown signal, stop accepting new webhook requests and let in-flight ones finish; in long-polling mode, cancel ctx and Poll returns.
Step 11: Payments: physical goods and Telegram Stars
The last question is whether you can take money inside Telegram. You can, but the rules come first; this section covers the concepts only and implements no money flow.
Figure: First decide whether you sell digital or physical goods; digital goods must use Telegram Stars, physical goods may use other currencies and payment providers. Both follow sendInvoice → pre_checkout_query → answerPreCheckoutQuery → successful_payment.
According to the official payments documentation:
- Digital goods and services (e-books, online courses, in-game items and the like) must be paid for exclusively in Telegram Stars, with currency
XTRand an emptyprovider_token. The docs explain this is to comply with the App Store and Google Play rules for digital goods; if you sell digital goods in other currencies or through third-party providers, Telegram cannot show your bot or Mini App to mobile users. Bots selling digital goods must also respond to/paysupport, and Stars refunds userefundStarPayment. - Physical goods and services may use other currencies and payment providers. The provider token is obtained after connecting a provider under
/mybots→ Bot Settings → Payments in BotFather; during development, use the “Stripe TEST MODE” provider mentioned in the docs, which charges nothing. Telegram itself does not collect payment information; card details are stored by the payment provider. - The flow: send an invoice (
sendInvoice; a Mini App can also open an invoice link withopenInvoice) → after the user confirms, the bot receives apre_checkout_query→ it must answer within 10 seconds withanswerPreCheckoutQuery(check that stock and price are still valid) → payment is complete only when thesuccessful_paymentmessage arrives, and only then do you ship.
The shop sells physical goods such as totes and mugs, so the second case applies. There are two practical routes: connect a payment provider supported by Telegram and hand successful_payment to the payment service as the payment-completed event, or keep using the website's existing checkout. Either way, the 10-second limit on answerPreCheckoutQuery means that step can only do quick checks, and payment results still need idempotency and reconciliation, on the same principles as the website's payments.
Common pitfalls
Trusting initDataUnsafe, or a user ID sent by the front end, on the server. Anyone can change data in a web page. User identity may come only from initData whose HMAC has been verified.
Comparing the hash with == when validating initData, or forgetting auth_date. The first leaks timing that can be exploited, so use hmac.Equal; the second makes a captured initData valid forever.
Letting the front end decide prices. The total shown in the Mini App is for people to read; only product IDs and quantities go to the backend, and the order service computes the price.
Not calling answerCallbackQuery. The user keeps seeing the button loading and assumes the bot is broken. Call it even with nothing to show.
Trusting the order ID in callback_data. It comes from the client; always re-check permission with from.id when fetching the order.
No secret_token on the webhook. Anyone who knows the URL can forge updates and issue commands as any user. Set a secret and compare the header in constant time.
Not handling retries. A webhook response other than 2xx is retried, so slow handling or a transient error can bring the same update twice. De-duplicate on update_id, and add idempotency keys to actions that change data.
The token appearing in logs. The token is part of the URL, and *url.Error, reverse-proxy access logs and requests printed while debugging can all carry it. Keep only the underlying cause in errors, and never log full Bot API URLs.
An HTTP client timeout shorter than the long poll. With timeout=30 on getUpdates and a 10-second Timeout on http.Client, every poll fails and starts over.
Two long-polling processes at once, or getUpdates while a webhook is set. Only one process may long-poll, and the two methods are mutually exclusive; call deleteWebhook before switching.
Placing orders with sendData. It only works in Mini Apps launched from a keyboard button, closes the app once sent, and returns no result. Use fetch to call the backend for anything that needs a response.
Notifications without throttling. Sending thousands at once after a big shipment quickly earns 429s. Throttle globally and wait retry_after.
Storing Telegram IDs in int or integer. User IDs may exceed 32 bits; use int64 and bigint.
Selling digital goods through a third-party payment provider. Under Telegram's rules, digital goods and services must use Telegram Stars (XTR) only.
Key takeaways
- Bots are good at reaching users first, commands and one- or two-step actions; Mini Apps are good at browsing, carts, forms and checkout. Shop-like needs usually combine both: the bot is the entry point and notifier, the Mini App the working screen.
- BotFather is where you create the bot and get its token; commands, the menu button and the webhook are best set during deployment with
setMyCommands,setChatMenuButtonandsetWebhook, kept in version control. - The Bot API is plain HTTPS plus JSON, and a small client with
net/httpis enough; retry automatically only on errors withretry_after, and never let the token reach error messages or logs. - Long polling suits local development and a single replica; webhooks suit production and several replicas. A webhook needs
secret_tokenand a check ofX-Telegram-Bot-Api-Secret-Token; de-duplicate onupdate_id. - An inline button's
callback_datais at most 64 bytes and comes from the client; always callanswerCallbackQueryand re-check permission withfrom.id. - Notifications are triggered by order events and throttled below the official FAQ limits (about one per second per chat, about 30 per second for bulk); on 429, wait
retry_after. - The Mini App is SvelteKit with SSR off and
adapter-static; it callsready()andexpand(), uses--tg-theme-*CSS variables for colours and MainButton and BackButton for navigation, and places orders withfetchcarryinginitDataand an idempotency key rather thansendData. - The backend trusts only validated
initData: secret_key is HMAC-SHA256 of the token keyed withWebAppData, then an HMAC of the sorted data-check-string, compared in constant time, plus anauth_datecheck. - Webhooks and Mini Apps both need HTTPS; webhook ports are limited to 443, 80, 88 and 8443. The token and the webhook secret live in a secret store.
- Digital goods must use Telegram Stars (
XTR); physical goods may use other currencies and payment providers; answerpre_checkout_querywithin 10 seconds and ship only aftersuccessful_payment.
References
- Telegram Bot API (official Telegram documentation): methods such as
getUpdates,setWebhook, inline keyboards,answerCallbackQueryandeditMessageText, used in steps 4 to 7. - Telegram Bot Features (official Telegram documentation): BotFather, commands and the menu button in steps 2 and 3.
- Telegram Mini Apps (official Telegram documentation): the Mini App JavaScript interface and validating
initDatawithWebAppData, used in steps 8 and 9. - Bots FAQ (official Telegram documentation): per-chat, per-group and broadcast sending limits and paid broadcasts, used in step 7.
- Bot Payments API (official Telegram documentation): taking payment for physical goods through payment providers, used in step 11.
- Bot Payments API for Digital Goods and Services (official Telegram documentation): digital goods must be paid in Telegram Stars (
XTR), used in step 11. - Static site generation (official SvelteKit documentation):
adapter-staticbuilding the Mini App as static files in step 8.
Next
The shop now has a Telegram entrance: the bot handles notifications and order lookups, the Mini App handles browsing and ordering, and both connect to the existing order service. The next article, “Bonus: An AI Telegram Bot: Answering Support Questions with ChatGPT and RAG”, turns this bot into an AI support agent that answers from the shop’s documents with sources and can look up the user’s own orders through a tool.