Документация по интеграции для партнёров
Partner API позволяет авторизованным партнёрам пополнять гемы пользователям игры Tiny Pet.
https://tinypet.ru/api/partner
Все запросы должны содержать следующие заголовки:
| Заголовок | Описание | Пример |
|---|---|---|
X-Partner-Key |
Ваш API ключ (выдаётся при регистрации) | pk_live_abc123... |
X-Signature |
HMAC-SHA256 подпись запроса | sha256=a1b2c3... |
X-Timestamp |
Unix timestamp (секунды) | 1703683200 |
Content-Type |
Тип контента | application/json |
Подпись создаётся по алгоритму HMAC-SHA256:
message = timestamp + "." + request_body signature = "sha256=" + HMAC-SHA256(message, secret_key).hex()
import hmac
import hashlib
import time
import json
import requests
API_KEY = "pk_live_your_api_key"
SECRET_KEY = "sk_live_your_secret_key"
BASE_URL = "https://tinypet.ru/api/partner"
def create_signature(body: str, timestamp: str) -> str:
message = f"{timestamp}.{body}"
signature = hmac.new(
SECRET_KEY.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return f"sha256={signature}"
def deposit_gems(user_id: int, gems_amount: int, transaction_id: str):
timestamp = str(int(time.time()))
body = json.dumps({
"transaction_id": transaction_id,
"user_id": user_id,
"gems_amount": gems_amount,
"payment_amount": 100.00,
"payment_currency": "RUB"
})
headers = {
"X-Partner-Key": API_KEY,
"X-Signature": create_signature(body, timestamp),
"X-Timestamp": timestamp,
"Content-Type": "application/json"
}
response = requests.post(
f"{BASE_URL}/gems/deposit",
headers=headers,
data=body
)
return response.json()
<?php
$apiKey = "pk_live_your_api_key";
$secretKey = "sk_live_your_secret_key";
$baseUrl = "https://tinypet.ru/api/partner";
function createSignature($body, $timestamp, $secretKey) {
$message = $timestamp . "." . $body;
$signature = hash_hmac('sha256', $message, $secretKey);
return "sha256=" . $signature;
}
function depositGems($userId, $gemsAmount, $transactionId) {
global $apiKey, $secretKey, $baseUrl;
$timestamp = time();
$body = json_encode([
"transaction_id" => $transactionId,
"user_id" => $userId,
"gems_amount" => $gemsAmount,
"payment_amount" => 100.00,
"payment_currency" => "RUB"
]);
$ch = curl_init("$baseUrl/gems/deposit");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"X-Partner-Key: $apiKey",
"X-Signature: " . createSignature($body, $timestamp, $secretKey),
"X-Timestamp: $timestamp",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
?>
Пополнение гемов пользователю.
| Поле | Тип | Обязательно | Описание |
|---|---|---|---|
transaction_id |
string | Да | Уникальный ID транзакции на вашей стороне (для идемпотентности) |
user_id |
integer | Да | ID пользователя (виден в команде !профиль) |
gems_amount |
integer | Да | Количество гемов (1 - 100000) |
payment_amount |
decimal | Нет | Сумма платежа (для статистики) |
payment_currency |
string | Нет | Валюта платежа (RUB, USD, EUR и т.д.) |
{
"transaction_id": "order_12345",
"user_id": 12345,
"gems_amount": 1000,
"payment_amount": 99.00,
"payment_currency": "RUB"
}
200 OK
{
"success": true,
"transaction_id": "order_12345",
"internal_transaction_id": "tpd-abc123def456",
"gems_credited": 1000,
"user_balance": 2500,
"timestamp": "2025-12-27T10:30:00.000Z"
}
transaction_id уже была обработана, API вернёт данные предыдущей транзакции со статусом 200.
400 Bad Request
{
"success": false,
"error": "gems_amount must be positive"
}
401 Unauthorized
{
"success": false,
"error": "Invalid API key"
}
403 Forbidden
{
"success": false,
"error": "Invalid signature"
}
404 Not Found
{
"success": false,
"error": "User not found"
}
Проверка статуса транзакции.
X-Partner-Key, подпись не требуется.
200 OK
{
"success": true,
"transaction_id": "order_12345",
"internal_transaction_id": "tpd-abc123def456",
"status": "completed",
"gems_amount": 1000,
"created_at": "2025-12-27T10:30:00.000Z"
}
| Статус | Описание |
|---|---|
pending |
Транзакция в обработке |
completed |
Транзакция успешно завершена |
failed |
Транзакция не удалась |
refunded |
Транзакция отменена/возвращена |
Проверка работоспособности API (не требует авторизации).
{
"status": "ok",
"timestamp": "2025-12-27T10:30:00.000Z",
"version": "1.0"
}
| Параметр | Значение |
|---|---|
| Rate limit | 100 запросов в минуту (по умолчанию) |
| Максимум гемов за транзакцию | 100,000 |
| Допустимое отклонение timestamp | ±5 минут |
Retry-After.
Пользователь получает свой ID в игре командой !профиль или !profile.
ID отображается в профиле игрока и виден публично.