tgkit

package
v0.4.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

tgkit

tgkit is the Telegram package for ServeKit. It combines the complete go-telegram/bot client with focused, validated helpers for:

  • long-polling and webhook bots that implement servekit.Listener;
  • channel posts, metadata, membership, join requests, invite links, and paid subscription links;
  • Mini App keyboard, inline, menu, inline-query, and direct-link launch points;
  • server-side Mini App initData validation with either the bot token or Telegram's public Ed25519 keys;
  • one-time provider or Telegram Stars invoices;
  • recurring Telegram Stars invoices, renewal cancellation/resumption, refunds, and payment-event extraction.

Telegram provisioning boundary

Telegram does not expose bot-account or channel-chat creation through the Bot API. Create bots and configure their Mini Apps with @BotFather, create channels in Telegram, and then add the bot as an administrator with the rights needed by the operations below. tgkit handles the application runtime and Bot API operations after that provisioning step.

Bot runtime

Long polling is the default. The bot can be registered directly with a ServeKit server because it implements Serve(context.Context) error.

bot, err := tgkit.New(
    os.Getenv("TELEGRAM_BOT_TOKEN"),
    tgkit.WithDefaultHandler(handleUpdate),
    tgkit.WithErrorHandler(reportTelegramError),
    tgkit.WithWorkers(4),
)
if err != nil {
    return err
}

server.RegisterListener("telegram", bot)

For webhooks, select webhook mode, mount the handler on an HTTPS endpoint, and register that URL with Telegram using the embedded client.

bot, err := tgkit.New(
    os.Getenv("TELEGRAM_BOT_TOKEN"),
    tgkit.WithWebhook(os.Getenv("TELEGRAM_WEBHOOK_SECRET")),
    tgkit.WithDefaultHandler(handleUpdate),
)
if err != nil {
    return err
}

router.Handle("/webhooks/telegram", bot.WebhookHandler())

_, err = bot.SetWebhook(ctx, &telegram.SetWebhookParams{
    URL:         "https://api.example.com/webhooks/telegram",
    SecretToken: os.Getenv("TELEGRAM_WEBHOOK_SECRET"),
})

WithWebhook rejects empty or malformed secrets. Use the same 1-256 character token, containing only ASCII letters, digits, _, or -, when registering the webhook with Telegram.

The embedded *bot.Bot exposes handler registration and the complete Bot API, so new or uncommon Telegram methods remain available without waiting for a tgkit wrapper.

Channels

Create a channel-scoped helper with a numeric chat ID or @username.

channel, err := bot.Channel("@product_updates")
if err != nil {
    return err
}

_, err = channel.Send(ctx, telegram.SendMessageParams{
    Text: "Version 2.0 is live.",
})
if err != nil {
    return err
}

paidLink, err := channel.CreateSubscriptionInviteLink(ctx, tgkit.ChannelSubscription{
    Name:       "Members",
    PriceStars: 250,
})

Regular invite links, join approvals, channel metadata, administrators, member lookups, pinning, and revocation are also channel-scoped methods.

Mini Apps

Launch controls require an absolute HTTPS URL.

app, err := bot.MiniApp("https://app.example.com")
if err != nil {
    return err
}

button, err := app.InlineButton("Open app")
if err != nil {
    return err
}

_, err = channel.Send(ctx, telegram.SendMessageParams{
    Text: "Open the app:",
    ReplyMarkup: models.InlineKeyboardMarkup{
        InlineKeyboard: [][]models.InlineKeyboardButton{{button}},
    },
})

Never trust Telegram.WebApp.initDataUnsafe. Send the raw Telegram.WebApp.initData query string to the backend and authenticate it. The built-in middleware reads it from X-Telegram-Init-Data and adds parsed data to the request context.

validator, err := tgkit.NewMiniAppValidator(
    os.Getenv("TELEGRAM_BOT_TOKEN"),
    tgkit.DefaultMiniAppInitDataMaxAge,
)
if err != nil {
    return err
}

router.With(validator.Middleware).Get("/mini-app/me", func(w http.ResponseWriter, r *http.Request) {
    initData, ok := tgkit.MiniAppInitDataFromContext(r.Context())
    if !ok {
        http.Error(w, "unauthorized", http.StatusUnauthorized)
        return
    }

    // initData.User and the other fields are authenticated here.
})

Third parties that must not receive the bot token can use NewMiniAppSignatureValidator with Telegram's production or test public key.

Payments and subscriptions

Provider-backed fiat payments require the provider token configured through BotFather. Telegram Stars payments use XTR, an empty provider token, and one price component.

payments := bot.Payments()

_, err := payments.SendInvoice(ctx, tgkit.SendInvoiceParams{
    ChatID:      userID,
    Title:       "100 credits",
    Description: "Account credit pack",
    Payload:     orderID,
    Currency:    tgkit.StarsCurrency,
    Prices: []tgkit.LabeledPrice{
        {Label: "Credits", Amount: 100},
    },
})

Recurring bot subscriptions currently use a 30-day Telegram Stars invoice link. CreateSubscriptionLink sets that period and validates Telegram's current price and currency rules.

invoiceURL, err := payments.CreateSubscriptionLink(ctx, tgkit.CreateInvoiceLinkParams{
    Title:       "Pro plan",
    Description: "30 days of Pro access",
    Payload:     subscriptionID,
    Currency:    tgkit.StarsCurrency,
    Prices: []tgkit.LabeledPrice{
        {Label: "Pro", Amount: 500},
    },
})

Every checkout must be answered within Telegram's deadline using ApprovePreCheckout or RejectPreCheckout. Grant entitlements only after PaymentFromUpdate returns a successful payment. Persist PaymentEvent.IdempotencyKey() before granting access so webhook retries cannot apply a charge twice. Subscription events distinguish the first charge from renewals and expose the paid expiration time.

Stars payments can be refunded with RefundStars. Recurring renewal can be disabled or re-enabled with CancelSubscription and ResumeSubscription; a cancellation leaves the already-paid period active.

Documentation

Overview

Package tgkit provides reusable Telegram bot, channel, Mini App, and payment building blocks.

Bot wraps the complete Telegram Bot API client and implements servekit's Listener contract for long polling and webhook workers. Channel adds channel-scoped helpers, MiniApp handles launch controls and authenticated initialization data, and Payments covers one-time invoices, Telegram Stars subscriptions, refunds, and renewal management.

Telegram bots and channels must still be provisioned in Telegram. The Bot API can operate a bot and administer channels to which it has been added, but it does not provision bot accounts or create channel chats.

Example
package main

import (
	"context"
	"fmt"

	telegram "github.com/go-telegram/bot"
	"github.com/go-telegram/bot/models"
	"github.com/marsolab/servekit/tgkit"
)

func main() {
	handler := func(ctx context.Context, bot *telegram.Bot, update *models.Update) {
		if update.Message == nil {
			return
		}

		_, _ = bot.SendMessage(ctx, &telegram.SendMessageParams{
			ChatID: update.Message.Chat.ID,
			Text:   "Hello from ServeKit.",
		})
	}

	bot, err := tgkit.New(
		"123456:development-token",
		tgkit.WithSkipIdentityCheck(),
		tgkit.WithDefaultHandler(handler),
	)
	if err != nil {
		panic(err)
	}

	fmt.Println(bot.Mode())
}
Output:
0

Index

Examples

Constants

View Source
const (

	// MonthlySubscriptionPeriod is Telegram's currently supported recurring
	// billing period for bot and channel subscriptions.
	MonthlySubscriptionPeriod = 30 * 24 * time.Hour

	// MaxStarsSubscriptionPrice is Telegram's maximum monthly subscription
	// price in Stars.
	MaxStarsSubscriptionPrice = 10000
)
View Source
const (

	// MiniAppInitDataHeader is the default HTTP header read by Mini App
	// authentication middleware.
	MiniAppInitDataHeader = "X-Telegram-Init-Data"

	// DefaultMiniAppInitDataMaxAge is the recommended default validity window
	// for authenticated Mini App initialization data.
	DefaultMiniAppInitDataMaxAge = 5 * time.Minute
)
View Source
const (

	// StarsCurrency is Telegram's ISO-like currency code for Telegram Stars.
	StarsCurrency = "XTR"
)

Variables

View Source
var (
	// ErrInvalidMode is returned when a bot has an unsupported update mode.
	ErrInvalidMode = errors.New("invalid telegram update mode")

	// ErrInvalidBotConfig is returned when a bot option would produce an invalid
	// runtime configuration.
	ErrInvalidBotConfig = errors.New("invalid telegram bot configuration")
)
View Source
var (
	// ErrInvalidChatID is returned when a channel chat ID is empty or unsupported.
	ErrInvalidChatID = errors.New("invalid telegram chat id")

	// ErrInvalidInviteLink is returned when invite-link settings violate the
	// Telegram Bot API constraints.
	ErrInvalidInviteLink = errors.New("invalid telegram invite link")

	// ErrInvalidSubscription is returned when subscription settings violate the
	// Telegram Bot API constraints.
	ErrInvalidSubscription = errors.New("invalid telegram subscription")

	// ErrRequestRejected is returned when Telegram responds with a false result
	// without a more specific API error.
	ErrRequestRejected = errors.New("telegram request rejected")
)
View Source
var (
	// ErrInvalidMiniApp is returned when a Mini App URL, button, or direct link
	// is invalid.
	ErrInvalidMiniApp = errors.New("invalid telegram mini app")

	// ErrMiniAppNotBound is returned when an API operation is attempted on a
	// standalone MiniApp that is not associated with a Bot.
	ErrMiniAppNotBound = errors.New("telegram mini app is not bound to a bot")
)
View Source
var (
	// ErrInvalidMiniAppInitData is returned for malformed, incomplete, or
	// unauthenticated Mini App initialization data.
	ErrInvalidMiniAppInitData = errors.New("invalid telegram mini app init data")

	// ErrExpiredMiniAppInitData is returned when authenticated initialization
	// data is older than the configured validity window.
	ErrExpiredMiniAppInitData = errors.New("expired telegram mini app init data")

	// ErrFutureMiniAppInitData is returned when initialization data has an
	// auth_date unreasonably far in the future.
	ErrFutureMiniAppInitData = errors.New("future telegram mini app init data")
)
View Source
var ErrInvalidInvoice = errors.New("invalid telegram invoice")

ErrInvalidInvoice is returned when invoice settings violate Telegram's payment constraints.

Functions

func MiniAppLink(
	botUsername string,
	shortName string,
	startParameter string,
	mode MiniAppMode,
) (string, error)

MiniAppLink builds a t.me direct link for a main or named Mini App. The bot username must contain 5-32 ASCII letters, digits, or underscores and end in "bot". Leave shortName empty to link to the bot's main Mini App.

Types

type Bot

type Bot struct {
	*telegram.Bot
	// contains filtered or unexported fields
}

Bot is a ServeKit-compatible Telegram bot.

The embedded Telegram client exposes the complete Bot API, including handler registration and methods not covered by tgkit's higher-level helpers.

func New

func New(token string, options ...Option) (*Bot, error)

New creates a Telegram bot. Long polling is used unless ModeWebhook is selected.

func (*Bot) Channel

func (b *Bot) Channel(chatID any) (*Channel, error)

Channel creates a helper scoped to a channel ID or @username.

func (*Bot) MiniApp

func (b *Bot) MiniApp(appURL string) (*MiniApp, error)

MiniApp creates Mini App launch controls bound to this bot.

func (*Bot) Mode

func (b *Bot) Mode() Mode

Mode reports how the bot receives updates.

func (*Bot) Payments

func (b *Bot) Payments() *Payments

Payments creates a payment helper for the bot.

func (*Bot) Serve

func (b *Bot) Serve(ctx context.Context) error

Serve receives and dispatches Telegram updates until the context is canceled. In webhook mode callers must mount WebhookHandler on an HTTP listener.

func (*Bot) Telegram

func (b *Bot) Telegram() *telegram.Bot

Telegram returns the underlying complete Telegram Bot API client.

type Channel

type Channel struct {
	// contains filtered or unexported fields
}

Channel provides channel-scoped Telegram Bot API operations.

The bot must be a member or administrator with the rights required by each operation. Telegram's Bot API does not create the channel chat itself.

func (*Channel) Administrators

func (c *Channel) Administrators(ctx context.Context, includeBots bool) ([]models.ChatMember, error)

Administrators returns the channel's administrators.

func (*Channel) ApproveJoinRequest

func (c *Channel) ApproveJoinRequest(ctx context.Context, userID int64) error

ApproveJoinRequest approves a user's pending request to join the channel.

func (c *Channel) CreateInviteLink(ctx context.Context, invite InviteLink) (*models.ChatInviteLink, error)

CreateInviteLink creates an additional channel invite link.

func (c *Channel) CreateSubscriptionInviteLink(
	ctx context.Context,
	subscription ChannelSubscription,
) (*models.ChatInviteLink, error)

CreateSubscriptionInviteLink creates a paid monthly channel invite link.

func (*Channel) DeclineJoinRequest

func (c *Channel) DeclineJoinRequest(ctx context.Context, userID int64) error

DeclineJoinRequest declines a user's pending request to join the channel.

func (*Channel) DeleteMessage

func (c *Channel) DeleteMessage(ctx context.Context, messageID int) error

DeleteMessage deletes a message from the channel.

func (c *Channel) EditSubscriptionInviteLink(
	ctx context.Context,
	inviteLink string,
	name string,
) (*models.ChatInviteLink, error)

EditSubscriptionInviteLink changes the display name of a paid channel invite link.

func (*Channel) ID

func (c *Channel) ID() any

ID returns the channel's Telegram chat ID or @username.

func (*Channel) Info

func (c *Channel) Info(ctx context.Context) (*models.ChatFullInfo, error)

Info returns full information about the channel.

func (*Channel) Member

func (c *Channel) Member(ctx context.Context, userID int64) (*models.ChatMember, error)

Member returns a channel member by Telegram user ID.

func (*Channel) MemberCount

func (c *Channel) MemberCount(ctx context.Context) (int, error)

MemberCount returns the number of channel members.

func (*Channel) PinMessage

func (c *Channel) PinMessage(ctx context.Context, messageID int, disableNotification bool) error

PinMessage pins a channel message.

func (c *Channel) RevokeInviteLink(ctx context.Context, inviteLink string) (*models.ChatInviteLink, error)

RevokeInviteLink revokes an invite link created by the bot.

func (*Channel) Send

Send sends a message to the channel. The channel ID in params is ignored.

func (*Channel) SetDescription

func (c *Channel) SetDescription(ctx context.Context, description string) error

SetDescription changes the channel description.

func (*Channel) SetTitle

func (c *Channel) SetTitle(ctx context.Context, title string) error

SetTitle changes the channel title.

func (*Channel) UnpinMessage

func (c *Channel) UnpinMessage(ctx context.Context, messageID int) error

UnpinMessage unpins a channel message.

type ChannelSubscription

type ChannelSubscription struct {
	Name       string
	PriceStars int
}

ChannelSubscription configures a paid monthly channel invite link.

type CreateInvoiceLinkParams

type CreateInvoiceLinkParams = telegram.CreateInvoiceLinkParams

CreateInvoiceLinkParams configures a one-time or recurring invoice link.

type HTTPClient

type HTTPClient interface {
	Do(request *http.Request) (*http.Response, error)
}

HTTPClient executes Telegram Bot API requests.

type Handler

type Handler = telegram.HandlerFunc

Handler handles a Telegram update.

type InviteLink struct {
	Name               string
	ExpireAt           time.Time
	MemberLimit        int
	CreatesJoinRequest bool
}

InviteLink configures a regular channel invite link.

type LabeledPrice

type LabeledPrice = models.LabeledPrice

LabeledPrice is one component of an invoice price.

type Middleware

type Middleware = telegram.Middleware

Middleware decorates a Telegram update handler.

type MiniApp

type MiniApp struct {
	// contains filtered or unexported fields
}

MiniApp provides launch controls and Bot API operations for a Telegram Mini App.

func NewMiniApp

func NewMiniApp(appURL string) (*MiniApp, error)

NewMiniApp creates standalone Mini App launch controls for an HTTPS URL.

func (*MiniApp) AnswerQuery

func (a *MiniApp) AnswerQuery(
	ctx context.Context,
	queryID string,
	result models.InlineQueryResult,
) (*models.SentWebAppMessage, error)

AnswerQuery sends an inline result on behalf of a Mini App user and closes the Mini App session.

func (*MiniApp) InlineButton

func (a *MiniApp) InlineButton(text string) (models.InlineKeyboardButton, error)

InlineButton creates an inline-keyboard button that launches the Mini App.

func (*MiniApp) InlineQueryButton

func (a *MiniApp) InlineQueryButton(text string) (models.InlineQueryResultsButton, error)

InlineQueryButton creates an inline-mode result button that launches the Mini App.

func (*MiniApp) KeyboardButton

func (a *MiniApp) KeyboardButton(text string) (models.KeyboardButton, error)

KeyboardButton creates a reply-keyboard button that launches the Mini App.

func (*MiniApp) MenuButton

func (a *MiniApp) MenuButton(text string) (models.MenuButtonWebApp, error)

MenuButton creates a bot menu button that launches the Mini App.

func (*MiniApp) SetMenuButton

func (a *MiniApp) SetMenuButton(ctx context.Context, chatID any, text string) error

SetMenuButton configures this Mini App as the bot menu button for a chat. A nil chatID configures the default menu button for all users.

func (*MiniApp) URL

func (a *MiniApp) URL() string

URL returns the Mini App's HTTPS URL.

type MiniAppChat

type MiniAppChat struct {
	ID       int64  `json:"id"`
	Type     string `json:"type"`
	Title    string `json:"title"`
	Username string `json:"username,omitempty"`
	PhotoURL string `json:"photo_url,omitempty"`
}

MiniAppChat contains chat data authenticated from Mini App initData.

type MiniAppEnvironment

type MiniAppEnvironment uint8

MiniAppEnvironment selects Telegram's Ed25519 signature-verification key.

const (
	// MiniAppEnvironmentProduction validates data from Telegram production.
	MiniAppEnvironmentProduction MiniAppEnvironment = iota

	// MiniAppEnvironmentTest validates data from Telegram's test environment.
	MiniAppEnvironmentTest
)

type MiniAppInitData

type MiniAppInitData struct {
	QueryID      string
	User         *MiniAppUser
	Receiver     *MiniAppUser
	Chat         *MiniAppChat
	ChatType     string
	ChatInstance string
	StartParam   string
	CanSendAfter time.Duration
	AuthDate     time.Time
	Hash         string
	Signature    string
	Values       map[string]string
	Raw          string
}

MiniAppInitData is parsed and authenticated Telegram.WebApp.initData.

func MiniAppInitDataFromContext

func MiniAppInitDataFromContext(ctx context.Context) (*MiniAppInitData, bool)

MiniAppInitDataFromContext returns authenticated Mini App data installed by the authentication middleware.

type MiniAppMode

type MiniAppMode string

MiniAppMode controls the initial height of a Mini App opened by direct link.

const (
	// MiniAppModeDefault uses the Mini App's configured opening mode.
	MiniAppModeDefault MiniAppMode = ""

	// MiniAppModeCompact opens the Mini App at half-screen height.
	MiniAppModeCompact MiniAppMode = "compact"
)

type MiniAppSignatureValidator

type MiniAppSignatureValidator struct {
	// contains filtered or unexported fields
}

MiniAppSignatureValidator authenticates Mini App initData for a third party using Telegram's public Ed25519 key and a bot ID.

func NewMiniAppSignatureValidator

func NewMiniAppSignatureValidator(
	botID int64,
	environment MiniAppEnvironment,
	maxAge time.Duration,
) (*MiniAppSignatureValidator, error)

NewMiniAppSignatureValidator creates a third-party Mini App data validator for Telegram's production or test environment.

func (*MiniAppSignatureValidator) Middleware

func (v *MiniAppSignatureValidator) Middleware(next http.Handler) http.Handler

Middleware authenticates third-party Mini App initData from MiniAppInitDataHeader and stores it in the request context. Invalid requests receive HTTP 401.

func (*MiniAppSignatureValidator) Validate

Validate authenticates and parses Mini App initData using Telegram's public signature and the current time.

func (*MiniAppSignatureValidator) ValidateAt

func (v *MiniAppSignatureValidator) ValidateAt(raw string, now time.Time) (*MiniAppInitData, error)

ValidateAt authenticates and parses Mini App initData using Telegram's public signature at a supplied time.

type MiniAppUser

type MiniAppUser struct {
	ID                    int64  `json:"id"`
	IsBot                 bool   `json:"is_bot,omitempty"`
	FirstName             string `json:"first_name"`
	LastName              string `json:"last_name,omitempty"`
	Username              string `json:"username,omitempty"`
	LanguageCode          string `json:"language_code,omitempty"`
	IsPremium             bool   `json:"is_premium,omitempty"`
	AddedToAttachmentMenu bool   `json:"added_to_attachment_menu,omitempty"`
	AllowsWriteToPM       bool   `json:"allows_write_to_pm,omitempty"`
	PhotoURL              string `json:"photo_url,omitempty"`
}

MiniAppUser contains user data authenticated from Mini App initData.

type MiniAppValidator

type MiniAppValidator struct {
	// contains filtered or unexported fields
}

MiniAppValidator authenticates Mini App initData with a private bot token.

func NewMiniAppValidator

func NewMiniAppValidator(botToken string, maxAge time.Duration) (*MiniAppValidator, error)

NewMiniAppValidator creates a bot-token Mini App data validator.

func (*MiniAppValidator) Middleware

func (v *MiniAppValidator) Middleware(next http.Handler) http.Handler

Middleware authenticates Mini App initData from MiniAppInitDataHeader and stores it in the request context. Invalid requests receive HTTP 401.

func (*MiniAppValidator) Validate

func (v *MiniAppValidator) Validate(raw string) (*MiniAppInitData, error)

Validate authenticates and parses Mini App initData using the current time.

func (*MiniAppValidator) ValidateAt

func (v *MiniAppValidator) ValidateAt(raw string, now time.Time) (*MiniAppInitData, error)

ValidateAt authenticates and parses Mini App initData at a supplied time.

type Mode

type Mode uint8

Mode controls how a Bot receives Telegram updates.

const (
	// ModePolling receives updates through Telegram long polling.
	ModePolling Mode = iota

	// ModeWebhook receives updates submitted to Bot.WebhookHandler.
	ModeWebhook
)

type Option

type Option func(*botConfig)

Option configures a Bot.

func WithAllowedUpdates

func WithAllowedUpdates(updates ...string) Option

WithAllowedUpdates restricts the update types Telegram should deliver.

func WithDefaultHandler

func WithDefaultHandler(handler Handler) Option

WithDefaultHandler configures the fallback update handler.

func WithErrorHandler

func WithErrorHandler(handler func(error)) Option

WithErrorHandler configures handling for asynchronous polling, webhook, and update-processing errors.

func WithHTTPClient

func WithHTTPClient(pollTimeout time.Duration, client HTTPClient) Option

WithHTTPClient configures the HTTP client and long-poll timeout.

func WithMiddlewares

func WithMiddlewares(middlewares ...Middleware) Option

WithMiddlewares configures middleware applied to every update handler.

func WithMode

func WithMode(mode Mode) Option

WithMode selects how the bot receives Telegram updates. Webhook mode also requires WithWebhook to configure a validated secret token.

func WithServerURL

func WithServerURL(serverURL string) Option

WithServerURL configures a Telegram Bot API server URL. It supports both the official endpoint and self-hosted Bot API servers.

func WithSkipIdentityCheck

func WithSkipIdentityCheck() Option

WithSkipIdentityCheck skips the getMe request made when the bot is created. It is intended for tests and specialized self-hosted Bot API setups.

func WithTelegramOptions

func WithTelegramOptions(options ...telegram.Option) Option

WithTelegramOptions applies lower-level go-telegram/bot options. Options are applied in call order and provide an escape hatch for new client features.

func WithWebhook

func WithWebhook(secretToken string) Option

WithWebhook selects webhook mode and configures the secret Telegram must include with webhook requests. The token must contain 1-256 ASCII letters, digits, underscores, or hyphens.

func WithWorkers

func WithWorkers(workers int) Option

WithWorkers configures the number of concurrent update workers.

type PaymentEvent

type PaymentEvent struct {
	Kind      PaymentKind
	UserID    int64
	ChatID    int64
	MessageID int
	Payment   *models.SuccessfulPayment
}

PaymentEvent is a successful payment extracted from a Telegram update. Payment.TelegramPaymentChargeID is the stable idempotency key applications should persist before granting an entitlement.

func PaymentFromUpdate

func PaymentFromUpdate(update *models.Update) (PaymentEvent, bool)

PaymentFromUpdate extracts a successful payment and classifies recurring subscription charges.

func (PaymentEvent) IdempotencyKey

func (e PaymentEvent) IdempotencyKey() string

IdempotencyKey returns Telegram's unique charge identifier for this payment.

func (PaymentEvent) SubscriptionExpiresAt

func (e PaymentEvent) SubscriptionExpiresAt() (time.Time, bool)

SubscriptionExpiresAt returns the paid subscription period's expiration.

type PaymentKind

type PaymentKind string

PaymentKind identifies whether a successful payment is one-time, an initial subscription payment, or a subscription renewal.

const (
	// PaymentOneTime identifies a non-recurring payment.
	PaymentOneTime PaymentKind = "one_time"

	// PaymentSubscriptionStarted identifies the first subscription charge.
	PaymentSubscriptionStarted PaymentKind = "subscription_started"

	// PaymentSubscriptionRenewed identifies a later subscription charge.
	PaymentSubscriptionRenewed PaymentKind = "subscription_renewed"
)

type Payments

type Payments struct {
	// contains filtered or unexported fields
}

Payments provides validated Telegram invoice and subscription operations.

func (*Payments) ApprovePreCheckout

func (p *Payments) ApprovePreCheckout(ctx context.Context, queryID string) error

ApprovePreCheckout approves a Telegram pre-checkout query. Telegram requires the answer within ten seconds.

func (*Payments) CancelSubscription

func (p *Payments) CancelSubscription(ctx context.Context, userID int64, chargeID string) error

CancelSubscription prevents a Telegram Stars subscription from renewing. The current paid period remains active.

func (p *Payments) CreateInvoiceLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)

CreateInvoiceLink creates a one-time invoice link after validating Telegram's payment constraints.

func (p *Payments) CreateSubscriptionLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)

CreateSubscriptionLink creates a monthly Telegram Stars subscription invoice link. Telegram currently supports only a 30-day recurring period.

func (*Payments) RefundStars

func (p *Payments) RefundStars(ctx context.Context, userID int64, chargeID string) error

RefundStars refunds a successful Telegram Stars payment.

func (*Payments) RejectPreCheckout

func (p *Payments) RejectPreCheckout(ctx context.Context, queryID, message string) error

RejectPreCheckout rejects a Telegram pre-checkout query with a user-facing explanation.

func (*Payments) ResumeSubscription

func (p *Payments) ResumeSubscription(ctx context.Context, userID int64, chargeID string) error

ResumeSubscription allows a previously canceled Telegram Stars subscription to renew again.

func (*Payments) SendInvoice

func (p *Payments) SendInvoice(ctx context.Context, params SendInvoiceParams) (*models.Message, error)

SendInvoice sends a one-time invoice after validating Telegram's payment constraints.

type PreCheckoutQuery

type PreCheckoutQuery = models.PreCheckoutQuery

PreCheckoutQuery is Telegram's final checkout confirmation request.

type RefundEvent

type RefundEvent struct {
	UserID    int64
	ChatID    int64
	MessageID int
	Refund    *models.RefundedPayment
}

RefundEvent is a refunded Stars payment extracted from a Telegram update.

func RefundFromUpdate

func RefundFromUpdate(update *models.Update) (RefundEvent, bool)

RefundFromUpdate extracts a refunded payment from a Telegram update.

type RefundedPayment

type RefundedPayment = models.RefundedPayment

RefundedPayment is Telegram's refunded payment payload.

type SendInvoiceParams

type SendInvoiceParams = telegram.SendInvoiceParams

SendInvoiceParams configures a one-time invoice sent to a Telegram chat.

type SuccessfulPayment

type SuccessfulPayment = models.SuccessfulPayment

SuccessfulPayment is Telegram's successful payment payload.

type Update

type Update = models.Update

Update is a Telegram Bot API update.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL