Skip to content

Commit 2b968c3

Browse files
committed
chore: add Telegram Stars Payments in GramIO
1 parent 396626b commit 2b968c3

File tree

5 files changed

+299
-24
lines changed

5 files changed

+299
-24
lines changed

docs/.vitepress/config/locales/en.locale.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export const localeEn = {
8181
],
8282
"/": [
8383
{
84-
text: "Guide",
84+
text: "Documentation",
8585
items: [
8686
{ text: "Get started", link: "/get-started" },
8787
{ text: "Bot API", link: "/bot-api" },
@@ -243,6 +243,15 @@ export const localeEn = {
243243
},
244244
],
245245
},
246+
{
247+
text: "Guides",
248+
items: [
249+
{
250+
text: "Telegram Stars",
251+
link: "/guides/telegram-stars",
252+
},
253+
],
254+
},
246255
],
247256
},
248257
},

docs/.vitepress/config/locales/ru.locale.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,15 @@ export const localeRu = {
236236
},
237237
],
238238
},
239+
{
240+
text: "Гайды",
241+
items: [
242+
{
243+
text: "Telegram Stars",
244+
link: "/ru/guides/telegram-stars",
245+
},
246+
],
247+
},
239248
],
240249
},
241250
// Переводы для дефолтных интерфейсов vitepress'а

docs/guides/telegram-stars.md

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
title: Telegram Stars Payments Guide with GramIO - Accept Digital Goods Payments
3+
4+
head:
5+
- - meta
6+
- name: "description"
7+
content: "Complete guide to implementing Telegram Stars payments in your GramIO bot. Learn to handle digital goods transactions, create invoices, process payments, and comply with Telegram's policies."
8+
9+
- - meta
10+
- name: "keywords"
11+
content: "telegram bot, gramio, telegram stars, bot payments, digital goods, telegram payments api, stars payments, gramio payment handling, telegram invoice, pre checkout query, payment disputes, stars refunds"
12+
---
13+
14+
# Telegram Stars Payments in GramIO
15+
16+
> [Official Telegram Documentation](https://core.telegram.org/bots/payments-stars)
17+
18+
Telegram Stars is an in-app virtual currency that allows users to purchase digital goods and services directly in bots. This guide will show you how to implement Stars payments in your GramIO bot.
19+
20+
## Implementation Overview
21+
22+
### 1. Create Payment Handler
23+
24+
```typescript
25+
bot.command("buy", async (context) => {
26+
const invoice = await context.bot.api.sendInvoice({
27+
chat_id: context.chat.id,
28+
title: "Premium Subscription",
29+
description: "1 month of premium features",
30+
payload: "sub_123",
31+
currency: "XTR",
32+
prices: [{ label: "1 Month", amount: 500 }], // 500 Stars = $5
33+
});
34+
35+
return context.send("Invoice created!");
36+
});
37+
```
38+
39+
### 2. Handle Pre-Checkout Queries
40+
41+
```typescript
42+
bot.on("pre_checkout_query", async (context) => {
43+
// Validate inventory/availability here
44+
await context.bot.api.answerPreCheckoutQuery({
45+
pre_checkout_query_id: context.id,
46+
ok: true,
47+
});
48+
});
49+
```
50+
51+
### 3. Process Successful Payments
52+
53+
```typescript
54+
bot.on("successful_payment", async (context) => {
55+
await context.send("Payment received! Delivering goods...");
56+
// Implement your delivery logic here
57+
});
58+
```
59+
60+
## Key Implementation Details
61+
62+
### Creating Invoices
63+
64+
#### Pay Button
65+
66+
```typescript
67+
// Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.
68+
const keyboard = new InlineKeyboard().pay("XTR Buy Now");
69+
70+
context.send("Premium Features", {
71+
reply_markup: keyboard,
72+
// ... other message parameters
73+
});
74+
```
75+
76+
#### Link
77+
78+
```ts
79+
const link = await context.bot.api.createInvoiceLink({
80+
title: "Premium Subscription",
81+
description: "1 month of premium features",
82+
payload: "sub_123",
83+
currency: "XTR",
84+
subscription_period: 2592000,
85+
prices: [{ label: "1 Month", amount: 500 }], // 500 Stars = $5
86+
});
87+
```
88+
89+
### Inline Query Message
90+
91+
```ts
92+
context.anser(
93+
[
94+
InlineQueryResult.article(
95+
"id-1",
96+
"Premium Subscription",
97+
InputMessageContent.invoice({
98+
title: "Premium Subscription",
99+
description: "1 month of premium features",
100+
payload: "sub_123",
101+
currency: "XTR",
102+
prices: [{ label: "1 Month", amount: 500 }], // 500 Stars = $5
103+
})
104+
),
105+
],
106+
{
107+
cache_time: 0,
108+
}
109+
);
110+
```
111+
112+
### Testing Payments
113+
114+
Enable test mode in GramIO configuration:
115+
116+
```typescript
117+
const bot = new Bot(process.env.BOT_TOKEN, {
118+
api: {
119+
useTest: true, // Use Telegram's test environment
120+
},
121+
});
122+
```
123+
124+
### Handling Disputes
125+
126+
Implement refund logic using GramIO's API:
127+
128+
```typescript
129+
bot.command("refund", async (context) => {
130+
const result = await context.api.refundStarPayment({
131+
user_id: context.from.id,
132+
telegram_payment_charge_id: paymentId,
133+
});
134+
});
135+
```
136+
137+
> Always check current rates in [Telegram's official documentation](https://core.telegram.org/bots/payments)
138+
139+
[Learn more about monetization](https://promote.telegram.org/)

docs/ru/guides/index.md

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
---
1+
<!-- ---
22
title: Руководства по GramIO - Мощный фреймворк для создания ботов Telegram на TypeScript/JavaScript
33
44
head:
@@ -10,25 +10,4 @@ head:
1010
- name: "keywords"
1111
content: телеграм бот, фреймворк, как создать бота, Telegram, Telegram Bot API, GramIO, TypeScript, JavaScript, Node.JS, Nodejs, Deno, Bun, руководства по созданию ботов, гайды, пошаговые инструкции, документация API, разработка Telegram ботов, обучающие материалы, туториалы, практические примеры, примеры кода для ботов
1212
---
13-
14-
# Руководства
15-
16-
Добро пожаловать в раздел руководств GramIO! Здесь вы найдете полезные инструкции и примеры для разработки Telegram ботов с помощью нашего фреймворка.
17-
18-
## Содержание
19-
20-
- [Начало работы](/ru/get-started) - Базовые шаги для создания вашего первого бота
21-
- [Бот API](/ru/bot-api) - Подробная информация о работе с Telegram Bot API
22-
- [Класс Bot](/ru/bot-class) - Документация по основному классу бота
23-
- [Плагины](/ru/plugins/index) - Расширение функциональности вашего бота с помощью плагинов
24-
- [Хуки](/ru/hooks/overview) - Использование хуков для создания гибких ботов
25-
- [Форматирование](/ru/formatting/index) - Создание красивых сообщений с форматированием текста
26-
- [Клавиатуры](/ru/keyboards/index) - Добавление интерактивных клавиатур в ваши сообщения
27-
28-
## Примеры проектов
29-
30-
Скоро мы добавим здесь ссылки на примеры проектов, которые помогут вам быстрее освоить GramIO. Следите за обновлениями документации!
31-
32-
## Обратная связь
33-
34-
Если у вас есть вопросы или предложения по улучшению этих руководств, пожалуйста, создайте issue в нашем [GitHub репозитории](https://github.com/gramiojs/documentation) документации.
13+
-->

docs/ru/guides/telegram-stars.md

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
title: Прием платежей через Telegram Stars в GramIO - Руководство
3+
4+
head:
5+
- - meta
6+
- name: "description"
7+
content: "Полное руководство по реализации платежей через Telegram Stars в вашем боте на GramIO. Научитесь обрабатывать транзакции, создавать счета, управлять платежами и соблюдать политики Telegram."
8+
9+
- - meta
10+
- name: "keywords"
11+
content: "telegram бот, gramio, telegram stars, платежи в ботах, цифровые товары, api платежей telegram, stars payments, обработка платежей в gramio, инвойсы в telegram, pre checkout query, споры по платежам, возвраты stars"
12+
---
13+
14+
# Платежи через Telegram Stars в GramIO
15+
16+
> [Официальная документация Telegram](https://core.telegram.org/bots/payments-stars)
17+
18+
Telegram Stars - виртуальная валюта для покупки цифровых товаров и услуг прямо в ботах. Это руководство покажет, как реализовать прием Stars в вашем боте на GramIO.
19+
20+
## Обзор реализации
21+
22+
### 1. Создание обработчика платежей
23+
24+
```typescript
25+
bot.command("buy", async (context) => {
26+
const invoice = await context.bot.api.sendInvoice({
27+
chat_id: context.chat.id,
28+
title: "Премиум подписка",
29+
description: "1 месяц премиум-функций",
30+
payload: "sub_123",
31+
currency: "XTR",
32+
prices: [{ label: "1 Месяц", amount: 500 }], // 500 Stars = $5
33+
});
34+
35+
return context.send("Счет создан!");
36+
});
37+
```
38+
39+
### 2. Обработка pre-checkout запросов
40+
41+
```typescript
42+
bot.on("pre_checkout_query", async (context) => {
43+
// Проверка наличия товара/услуги
44+
// answerPreCheckoutQuery
45+
return context.answer({
46+
ok: true,
47+
});
48+
});
49+
```
50+
51+
### 3. Обработка успешных платежей
52+
53+
```typescript
54+
bot.on("successful_payment", async (context) => {
55+
await context.send("Платеж получен! Доставляем товар...");
56+
// Логика доставки цифрового товара
57+
});
58+
```
59+
60+
## Ключевые детали реализации
61+
62+
### Создание инвойсов
63+
64+
#### Кнопка оплаты
65+
66+
```typescript
67+
// Подстроки "⭐" и "XTR" будут заменены на иконку Telegram Stars
68+
const keyboard = new InlineKeyboard().pay("XTR Купить сейчас");
69+
70+
context.send("Премиум функции", {
71+
reply_markup: keyboard,
72+
// ... другие параметры сообщения
73+
});
74+
```
75+
76+
#### Ссылка для оплаты
77+
78+
```ts
79+
const link = await context.bot.api.createInvoiceLink({
80+
title: "Премиум подписка",
81+
description: "1 месяц премиум-функций",
82+
payload: "sub_123",
83+
currency: "XTR",
84+
subscription_period: 2592000, // 30 дней в секундах
85+
prices: [{ label: "1 Месяц", amount: 500 }],
86+
});
87+
```
88+
89+
### Инвойсы в inline-режиме
90+
91+
```ts
92+
context.anser(
93+
[
94+
InlineQueryResult.article(
95+
"id-1",
96+
"Премиум подписка",
97+
InputMessageContent.invoice({
98+
title: "Премиум подписка",
99+
description: "1 месяц премиум-функций",
100+
payload: "sub_123",
101+
currency: "XTR",
102+
prices: [{ label: "1 Месяц", amount: 500 }],
103+
})
104+
),
105+
],
106+
{
107+
cache_time: 0,
108+
}
109+
);
110+
```
111+
112+
### Тестирование платежей
113+
114+
Активируйте тестовый режим в конфигурации GramIO:
115+
116+
```typescript
117+
const bot = new Bot(process.env.BOT_TOKEN, {
118+
api: {
119+
useTest: true, // Используем тестовое окружение Telegram
120+
},
121+
});
122+
```
123+
124+
### Обработка возвратов
125+
126+
Реализация возврата средств:
127+
128+
```typescript
129+
bot.command("refund", async (context) => {
130+
const result = await context.api.refundStarPayment({
131+
user_id: context.from.id,
132+
telegram_payment_charge_id: paymentId,
133+
});
134+
});
135+
```
136+
137+
> Актуальные курсы валют смотрите в [официальной документации Telegram](https://core.telegram.org/bots/payments)
138+
139+
[Узнать о монетизации](https://promote.telegram.org/)

0 commit comments

Comments
 (0)