GrassFlow API

Документация APIAPI documentation

GrassFlow API

Баланс, спонсоры и проверка подписок, статистика по вашим ботам и вебхуки о подтверждённых подписках. Все запросы идут на один адрес и возвращают JSON. Balance, sponsors and subscription checks, statistics for your bots and webhooks for confirmed subscriptions. All requests go to one address and return JSON.

Базовый адресBase URL https://api.grassflow.ru
POSTотправка данных в JSON-теле запросаsend data in a JSON body
GETполучение данных, параметры в адресеread data, parameters in the URL

Быстрый стартQuick start

  1. Добавьте бота через @GrassFlowBot и дождитесь модерации.Add your bot through @GrassFlowBot and wait for moderation.
  2. Возьмите ключ бота (для спонсоров и проверки подписок) или токен владельца из кабинета (для баланса, статистики и вебхуков).Take the bot key (sponsors and subscription checks) or the owner token from the cabinet (balance, statistics and webhooks).
  3. Отправьте первый запрос: POST /get-balance.Send the first request: POST /get-balance.

АвторизацияAuthorization

Ключ передаётся заголовком Authorization: Bearer. Ключи нельзя публиковать в клиентском JavaScript, публичных репозиториях и открытых чатах. Pass the key in the Authorization: Bearer header. Never publish keys in client-side JavaScript, public repositories or open chats.

HTTP
Authorization: Bearer ВАШ_КЛЮЧ
Content-Type: application/json

Также принимается заголовок Auth: ВАШ_КЛЮЧ. Для GET /statistic ключ можно передать параметром api_token в адресе. The Auth: YOUR_KEY header is also accepted. For GET /statistic the key can be passed as the api_token URL parameter.

Ключ ботаBot key

Выдаётся для каждого подключённого бота. Используется в get-sponsors и get-user-subscriptions. Вебхук, созданный таким ключом, относится к этому боту.Issued for each connected bot. Used by get-sponsors and get-user-subscriptions. A webhook created with this key belongs to that bot.

Токен владельцаOwner token

Берётся в кабинете GrassFlow. Используется в get-balance, GET /statistic и /webhooks и охватывает все ваши боты.Taken from the GrassFlow cabinet. Used by get-balance, GET /statistic and /webhooks and covers all your bots.

Ключ бота и токен владельца — разные секреты. Telegram-токен бота (от @BotFather) в API не передаётся.The bot key and the owner token are different secrets. The Telegram bot token (from @BotFather) is never sent to the API.

Формат ответа и ошибкиResponse format and errors

Каждый ответ — JSON вида {"status": "ok", "code": 200, "message": "…"} плюс данные метода. При ошибке status равен error, а message объясняет причину.Every response is JSON like {"status": "ok", "code": 200, "message": "…"} plus the method data. On error status is error and message explains the reason.

КодCodeЗначениеMeaning
400Неверные параметры, например user_id must be an integer или start_date must be in YYYY-MM-DD format.Invalid parameters, for example user_id must be an integer or start_date must be in YYYY-MM-DD format.
401Ключ не передан или неверен: Bearer API key is required.Key is missing or invalid: Bearer API key is required.
403Ключ не привязан к аккаунту владельца.The key is not linked to an owner account.
404Объект не найден: бот, вебхук или адрес метода.Object not found: bot, webhook or endpoint.
405Неверный HTTP-метод: GET /get-balance вернёт 405, нужен POST.Wrong HTTP method: GET /get-balance returns 405, POST is required.
500Внутренняя ошибка сервера. Повторите запрос позже.Internal server error. Retry the request later.
POST/get-balance

Баланс владельца и список его ботов с числом подписчиков и заработком. Тело запроса не нужно.Owner balance and the list of bots with subscriber count and earnings. No request body is needed.

Ключ: токен владельцаKey: owner token

curl
curl -X POST https://api.grassflow.ru/get-balance \
  -H "Authorization: Bearer ВАШ_ТОКЕН_ВЛАДЕЛЬЦА"
200 OK
{
  "status": "ok",
  "code": 200,
  "message": "Balance and connected bot information retrieved",
  "balance": 125.5,
  "bots_info": [
    { "bot_id": 8974541619, "bot_username": "@my_bot", "total_followers": 340, "revenue": 238.0 }
  ]
}
balancenumberБаланс в ₽, 2 знака после запятой.Balance in ₽, 2 decimal places.
bots_info[].bot_idintegerID бота в Telegram.Telegram bot ID.
bots_info[].bot_usernamestringUsername бота (с @).Bot username (with @).
bots_info[].total_followersintegerВсего подписчиков, приведённых ботом.Total subscribers brought by the bot.
bots_info[].revenuenumberЗаработок бота в ₽.Bot earnings in ₽.
POST/get-sponsors

Выдаёт пользователю бота список спонсоров (обязательных подписок). Пользователь подписывается на каналы и чаты из списка; владелец бота получает 0.70 ₽ за каждую подтверждённую подписку.Returns the list of sponsors (mandatory subscriptions) for a bot user. The user subscribes to the channels and chats in the list; the bot owner receives 0.70 RUB for every confirmed subscription.

Ключ: ключ бота (заголовок Authorization: Bearer или Auth)Key: bot key (header Authorization: Bearer or Auth)

curl
curl -X POST https://api.grassflow.ru/get-sponsors \
  -H "Authorization: Bearer КЛЮЧ_БОТА" \
  -H "Content-Type: application/json" \
  -d '{"user_id": 123456789, "chat_id": -1001234567890, "action": "subscribe", "get_links": 1, "max_sponsors": 5}'
user_idintegerTelegram ID пользователя. Обязательный.Telegram user ID. Required.
chat_idintegerID чата, откуда идёт запрос; для лички равен user_id. Может быть отрицательным. Обязательный.ID of the chat the request comes from; for a private chat it equals user_id. Can be negative. Required.
actionstringПо умолчанию subscribe. subscribe — список закрепляется за пользователем; newtask — каждый раз новый список; task — гибрид: список удаляется после успешной подписки.Default subscribe. subscribe — the list is pinned to the user; newtask — a new list on every request; task — hybrid: the list is removed after a successful subscription.
max_sponsorsinteger 1–10Максимум спонсоров в ответе. По умолчанию 5.Maximum number of sponsors in the response. Default 5.
get_links0 | 1По умолчанию 1: при status = warning в ответе есть массив links. При 0 массив пустой, и сервис сам показывает блок обязательной подписки.Default 1: with status = warning the response contains the links array. With 0 the array is empty and the service shows the mandatory-subscription block itself.
list_reset_minutesinteger 5–10080Через сколько минут невыполненный список спонсоров пересобирается заново (максимум 7 суток). Действует только на этот запрос и только для subscribe. Если не указано — список не сбрасывается по времени. Для newtask не применяется.After how many minutes an unfinished sponsor list is collected again (maximum 7 days). Applies to this request only and only to subscribe. If omitted, the list is not reset by time. Not used for newtask.
exclude_resource_idsstring[]ID ресурсов, которые не выдавать: Telegram ID канала или чата (например "-1001234567890") либо внутренний ID спонсора. Не больше 500 элементов; лишние отбрасываются.Resource IDs that must not be returned: a channel or chat Telegram ID (for example "-1001234567890") or an internal sponsor ID. At most 500 items; extra items are ignored.
exclude_ads_idsstring[]ID заказов, которые не выдавать. Префиксы sp_ и ord_ принимаются. Не больше 500 элементов; лишние отбрасываются.Order IDs that must not be returned. The sp_ and ord_ prefixes are accepted. At most 500 items; extra items are ignored.
is_premium0 | 1Есть ли у пользователя Telegram Premium. Влияет на задания, видимые только Premium-пользователям.Whether the user has Telegram Premium. Affects tasks that are visible only to Premium users.
first_name, username, language_codestringИмя, юзернейм без @ и язык интерфейса (например ru, en). Используются для подбора заданий по языку.First name, username without @, and interface language (for example ru, en). Used to select tasks by language.
200 OK · status warning
{
  "status": "warning",
  "code": 200,
  "message": "User must subscribe to sponsors before accessing content",
  "status_label": "warning",
  "total_fixed_link": 2,
  "links": ["https://t.me/channel_one", "https://t.me/chat_two"],
  "additional": {
    "sponsors": [
      {
        "id": "sp_12",
        "resource_id": "-1001234567890",
        "title": "Channel One",
        "name": "Channel One",
        "resource_name": "Channel One",
        "link": "https://t.me/channel_one",
        "resource_logo": "",
        "button_text": "Подписаться",
        "type": "channel",
        "status": "unsubscribed",
        "available_now": true,
        "is_track": false
      }
    ]
  }
}
statusok | warningok — пользователь подписан на все задания или заданий нет: контент можно выдавать. warning — нужна подписка: показать пользователю links (или блок, если get_links = 0).ok — the user is subscribed to all tasks or there are no tasks: the content can be shown. warning — a subscription is required: show the links (or the block itself when get_links = 0).
total_fixed_linkintegerСколько обязательных подписок в списке и ещё не выполнено. 0, если status = ok.How many mandatory subscriptions in the list are not completed yet. 0 when status = ok.
additional.sponsors[]object[]Все спонсоры списка. status: subscribed — подписан; unsubscribed — не подписан; notgetted — подписан ранее, но по этой ссылке не засчитан. type: channel (канал или чат), bot, resource (мини-приложение). available_now всегда true: остановленные спонсоры не выдаются. Для заданий с трекингом дополнительно есть track_url, max_users, confirmed_users, price_per_user.All sponsors in the list. status: subscribed — subscribed; unsubscribed — not subscribed; notgetted — subscribed earlier, but not credited through this link. type: channel (channel or chat), bot, resource (mini app). available_now is always true: stopped sponsors are not returned. Tracked tasks also include track_url, max_users, confirmed_users, price_per_user.
errorHTTP 4xxНеверный ключ — 401, неверные параметры — 400. В ответе "status": "error" и текст в message. Рекомендуется пропустить пользователя и записать ошибку в лог.Invalid key — 401, invalid parameters — 400. The response has "status": "error" and the text in message. It is recommended to let the user through and log the error.
POST/get-user-subscriptions

Проверяет статус подписки пользователя на конкретные спонсоры. Нужно передать links или ads_ids. Статус каждого спонсора — в additional.sponsors.Checks the user's subscription status for specific sponsors. Pass links or ads_ids. The status of each sponsor is in additional.sponsors.

Ключ: ключ бота (заголовок Authorization: Bearer или Auth)Key: bot key (header Authorization: Bearer or Auth)

curl
curl -X POST https://api.grassflow.ru/get-user-subscriptions \
  -H "Authorization: Bearer КЛЮЧ_БОТА" \
  -H "Content-Type: application/json" \
  -d '{"user_id": 123456789, "links": ["https://t.me/example_channel"]}'
user_idintegerTelegram ID пользователя. Обязательный.Telegram user ID. Required.
linksstring[]Ссылки спонсоров, которые нужно проверить: ровно такие, как в link ответа get-sponsors. До 50 элементов; лишние отбрасываются.Sponsor links to check, exactly as in the link field of a get-sponsors response. Up to 50 items; extra items are ignored.
ads_idsinteger[]ID заказов (ads_id) для проверки. До 50 элементов; лишние отбрасываются.Order IDs (ads_id) to check. Up to 50 items; extra items are ignored.
start_dateYYYY-MM-DDНачало периода выборки по дате назначения задания. Необязательный.Start of the selection period by the date the task was assigned. Optional.
end_dateYYYY-MM-DDКонец периода выборки. Необязательный. Не может быть раньше start_date.End of the selection period. Optional. Cannot be earlier than start_date.

Нужно передать links или ads_ids (хотя бы один непустой массив). Иначе ответ 400. Ошибка формата дат или массивов тоже даёт 400.Pass links or ads_ids (at least one non-empty array). Otherwise the response is 400. Invalid date or array formats also return 400.

200 OK
{
  "status": "ok",
  "code": 200,
  "message": "Subscription statuses retrieved",
  "additional": {
    "sponsors": [
      {
        "link": "https://t.me/example_channel",
        "resource_id": "-1001234567890",
        "title": "Example Channel",
        "name": "Example Channel",
        "resource_name": "Example Channel",
        "type": "channel",
        "status": "subscribed"
      }
    ]
  }
}
statusok | errorВерхний уровень ответа: ok при успешной проверке (даже если пользователь не подписан), error при ошибке — текст в message.Top-level result: ok when the check succeeds (even if the user is not subscribed), error on failure — the text is in message.
additional.sponsors[]object[]Проверенные спонсоры. Спонсор, которого нет в вашем списке, в ответе не появляется. status: subscribed — подписан, засчитано; notgetted — подписан ранее, по этой ссылке не засчитан; unsubscribed — не подписан. type: channel, bot, resource. ads_id добавляется, если проверка шла по ads_ids.Checked sponsors. A sponsor that does not exist in GrassFlow is not returned. status: subscribed — subscribed and counted; notgetted — subscribed earlier, not counted for this link; unsubscribed — not subscribed. type: channel, bot, resource. ads_id is added when the check was done by ads_ids.

Оплата владельцу начисляется только за первое подтверждение каждой подписки. Повторная проверка уже засчитанной подписки деньги не дублирует.The owner is paid only for the first confirmation of each subscription. Re-checking an already counted subscription does not pay twice.

GET/statistic

Подписчики и суммы по дням за период: по всем ботам, по одному боту или по спонсорам одного бота.Subscribers and amounts by day for a period: for all bots, for one bot, or for sponsors of one bot.

Ключ: токен владельца — заголовком или параметром api_tokenKey: owner token — header or api_token parameter

curl
curl "https://api.grassflow.ru/statistic?action=bots&bot_id=8974541619&start_date=2026-10-01&end_date=2026-10-12" \
  -H "Authorization: Bearer ВАШ_ТОКЕН_ВЛАДЕЛЬЦА"
actionstringallbots (по умолчанию) — все боты; bots — один бот; sponsor — спонсоры одного бота.allbots (default) — all bots; bots — one bot; sponsor — sponsors of one bot.
bot_idintegerОбязателен для bots и sponsor.Required for bots and sponsor.
start_dateYYYY-MM-DDНачало периода. По умолчанию — за 9 дней до end_date.Start of the period. Default — 9 days before end_date.
end_dateYYYY-MM-DDКонец периода. По умолчанию — сегодня. Не может быть раньше start_date.End of the period. Default — today. Cannot be earlier than start_date.
output_formatjson | htmlПо умолчанию json. html отдаёт страницу с графиком.Default json. html returns a page with a chart.
200 OK
{
  "status": "ok",
  "code": 200,
  "message": "Statistic retrieved",
  "action": "bots",
  "period": { "start_date": "2026-10-01", "end_date": "2026-10-12" },
  "data": {
    "labels": ["2026-10-01", "…"],
    "subscribers_data": [12, "…"],
    "value_data": [8.4, "…"],
    "avg_price_data": [0.7, "…"],
    "total_subscribers": 240,
    "total_value": 168.0
  }
}

При action=allbots в data добавляется таблица по ботам: bot_id, bot_nickname, subscribers, value.With action=allbots, data also contains a table per bot: bot_id, bot_nickname, subscribers, value.

Вебхук подтверждения подпискиSubscription confirmed webhook

GrassFlow отправляет POST-запрос на ваш HTTPS-адрес, когда пользователь подтвердил подписку на задание и выплата начислена.GrassFlow sends a POST request to your HTTPS address when a user has confirmed a subscription to a task and the payout has been credited.

Где настроитьWhere to configure

Регистрация через APIRegistering via the API

Авторизация: Authorization: Bearer API_TOKEN или Auth: API_TOKEN. Подходят ключ бота и ключ владельца.Authorization: Authorization: Bearer API_TOKEN or Auth: API_TOKEN. Both a bot key and an owner key work.

POST/webhooks

Поля: url (обязательно, https://), events (по умолчанию ["subscription.confirmed"]; другие значения отклоняются), secret (8–256 символов; если не передан, сервер создаёт случайный и возвращает его один раз). Ответ 201.Fields: url (required, https://), events (default ["subscription.confirmed"]; other values are rejected), secret (8–256 characters; if omitted the server generates one and returns it once). Response 201.

curl
curl -X POST https://api.grassflow.ru/webhooks \
  -H "Authorization: Bearer API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/grassflow/webhook", "events": ["subscription.confirmed"], "secret": "my-secret-123"}'
JSON — 201
{
  "status": "ok",
  "code": 201,
  "message": "Webhook registered",
  "webhook": {
    "id": 12,
    "bot_id": null,
    "url": "https://example.com/grassflow/webhook",
    "events": ["subscription.confirmed"],
    "secret": "my-secret-123"
  }
}
GET/webhooks

Список всех ваших вебхуков, от новых к старым. Секрет не возвращается. created_at — UTC, ISO 8601. last_status — см. раздел «Как должен отвечать ваш webhook».All your webhooks, newest first. The secret is not returned. created_at is UTC, ISO 8601. last_status — see «How your webhook must respond».

curl
curl https://api.grassflow.ru/webhooks \
  -H "Authorization: Bearer API_TOKEN"
JSON — 200
{
  "status": "ok",
  "code": 200,
  "message": "Webhooks retrieved",
  "webhooks": [
    {
      "id": 12,
      "bot_id": null,
      "url": "https://example.com/grassflow/webhook",
      "events": ["subscription.confirmed"],
      "active": true,
      "created_at": "2026-10-27T04:10:00+00:00",
      "last_status": 200
    }
  ]
}

Запрос от GrassFlowRequest from GrassFlow

HTTP
POST /grassflow/webhook HTTP/1.1
Host: example.com
Content-Type: application/json
User-Agent: GrassFlow-Webhooks/1.0
X-GrassFlow-Signature: 67fc8595aa66db51d78018213de38f5fe168f572f4f8a6981859e42ddd030615
JSON — заказJSON — order
{
  "webhook_id": 12,
  "event": "subscription.confirmed",
  "created_at": "2026-10-27T04:10:00+00:00",
  "bot_id": null,
  "data": {
    "user_id": 123456789,
    "token": "trorder40",
    "status": "subscribed",
    "amount": 1.02
  }
}
JSON — ботJSON — bot
{
  "webhook_id": 13,
  "event": "subscription.confirmed",
  "created_at": "2026-10-27T04:12:31+00:00",
  "bot_id": 8310388287,
  "data": {
    "user_id": 123456789,
    "status": "subscribed",
    "amount": 0.7
  }
}
ПолеFieldТипTypeОписаниеDescription
webhook_idintegerID вебхука из POST /webhooksWebhook ID from POST /webhooks
eventstringСейчас только subscription.confirmedCurrently only subscription.confirmed
created_atstringВремя события, UTC, ISO 8601, например 2026-10-27T04:10:00+00:00Event time, UTC, ISO 8601, e.g. 2026-10-27T04:10:00+00:00
bot_idinteger | nullID бота; null для заказов и трафикаBot ID; null for order and traffic events
data.user_idintegerTelegram ID пользователя, подтвердившего подпискуTelegram ID of the user who confirmed the subscription
data.tokenstringТолько заказы и трафик, например trorder40. В событиях бота нетOrders and traffic only, e.g. trorder40. Not present in bot events
data.statusstringВсегда subscribedAlways subscribed
data.amountnumber, ₽Сумма, начисленная владельцу ключа, 2 знака. Заказ с ценой P: round(P × 0.85, 2), например P = 1.2 → 1.02. Цена не задана: 0.70Amount credited to the key owner, 2 decimals. Order priced P: round(P × 0.85, 2), e.g. P = 1.2 → 1.02. No price set: 0.70

ПодписьSignature

X-GrassFlow-Signature — HMAC-SHA256 от сырого тела запроса, ключ — ваш secret, результат в hex (нижний регистр). Проверяйте подпись до обработки.X-GrassFlow-Signature is HMAC-SHA256 of the raw request body, keyed with your secret, lowercase hex. Verify it before processing.

Python
import hashlib
import hmac

def is_valid(raw_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")

Как должен отвечать ваш webhookHow your webhook must respond

HTTP
HTTP/1.1 200 OK
Content-Type: application/json

{"ok": true}

Пример обработчика на aiohttpaiohttp handler example

Python
import hashlib
import hmac
import os

from aiohttp import web

SECRET = os.environ["GRASSFLOW_WEBHOOK_SECRET"]

async def grassflow_webhook(request: web.Request) -> web.Response:
    raw = await request.read()
    signature = request.headers.get("X-GrassFlow-Signature", "")
    expected = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        return web.json_response({"ok": False}, status=401)

    payload = await request.json()
    if payload.get("event") == "subscription.confirmed":
        user_id = int(payload["data"]["user_id"])
        amount = float(payload["data"]["amount"])
        # Здесь: начислите награду или запишите выплату в вашу базу.
    return web.json_response({"ok": True})

app = web.Application()
app.router.add_post("/grassflow/webhook", grassflow_webhook)
web.run_app(app, host="0.0.0.0", port=8080)

Ответ 401 при неверной подписи приведёт к ошибке доставки (last_status = 0). Это ожидаемо: подпись неверна, значит запрос не от GrassFlow.A 401 for a wrong signature counts as a failed delivery (last_status = 0). This is expected: a wrong signature means the request is not from GrassFlow.

Ошибки APIAPI errors

HTTPmessageКогдаWhen
400url must be a valid HTTPS URLАдрес не начинается с https:// или без доменаAddress does not start with https:// or has no host
400Unsupported webhook eventВ events есть что-то кроме subscription.confirmedevents contains anything other than subscription.confirmed
400secret must be 8-256 charactersСекрет короче 8 или длиннее 256 символовSecret is shorter than 8 or longer than 256 characters
401Bearer API key is requiredНет заголовка Authorization или AuthNo Authorization or Auth header
401Invalid or inactive API keyКлюч неверный или отключёнThe key is wrong or disabled