1. Go to this page and download the library: Download targethunter/max-php-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
targethunter / max-php-sdk example snippets
use TH\MAX\Client\MAXClient;
use TH\MAX\Client\Request\MAXRequest;
// Создаем клиент с вашим access_token
$accessToken = 'ваш_access_token_здесь';
$request = new MAXRequest($accessToken);
$client = new MAXClient($request);
// Теперь вы можете использовать все модули API
// Получить информацию о текущем боте
$bot = $client->bots()->getMe();
echo "Имя бота: " . $bot->name;
echo "Описание: " . $bot->description;
// Отправить текстовое сообщение
$message = $client->messages()->send(
user_id: 12345,
text: 'Привет! Это тестовое сообщение от бота.'
);
// Отправить сообщение в чат
$message = $client->messages()->send(
chat_id: 67890,
text: 'Сообщение в групповой чат'
);
// Получить список сообщений
$messages = $client->messages()->getAll(
chat_id: 67890,
count: 20
);
// Обновить сообщение
$result = $client->messages()->update(
message_id: 'message_123',
text: 'Обновленный текст сообщения'
);
// Удалить сообщение
$result = $client->messages()->delete('message_123');
// Получить сообщение по ID
$message = $client->messages()->getById('message_123');
// Получить список чатов
$chats = $client->chats()->getAll(count: 50);
// Получить чат по ID
$chat = $client->chats()->getById(12345);
echo "Название чата: " . $chat->title;
// Обновить информацию о чате
$updatedChat = $client->chats()->update(
chat_id: 12345,
title: 'Новое название чата',
notify: true
);
// Получить список участников
$members = $client->chats()->getMembers(
chat_id: 12345,
count: 20
);
// Добавить участников в чат
$result = $client->chats()->addMembers(
chat_id: 12345,
user_ids: [111, 222, 333]
);
// Закрепить сообщение
$result = $client->chats()->pinMessage(
chat_id: 12345,
message_id: 'message_123',
notify: true
);
// Получить URL для загрузки изображения
$uploadUrl = $client->upload()->getUrl('image');
echo "URL для загрузки: " . $uploadUrl->url;
// Получить URL для загрузки файла
$uploadUrl = $client->upload()->getUrl('file');
// Получить список подписок
$subscriptions = $client->subscriptions()->getAll();
// Создать подписку на webhook
$result = $client->subscriptions()->subscribe(
url: 'https://your-domain.com/webhook',
update_types: ['message', 'chat_member'],
secret: 'your_secret_key'
);
// Удалить подписку
$result = $client->subscriptions()->unsubscribe(
url: 'https://your-domain.com/webhook'
);
// Получить обновления
$updates = $client->subscriptions()->getUpdates(
limit: 100,
timeout: 30
);
use TH\MAX\Exceptions\MAXHttpException;
try {
$message = $client->messages()->send(
user_id: 12345,
text: 'Тестовое сообщение'
);
echo "Сообщение отправлено: " . $message->id;
} catch (MAXHttpException $e) {
echo "Ошибка API: " . $e->getMessage();
echo "HTTP код: " . $e->getCode();
// Получить оригинальное исключение Guzzle для отладки
if ($e->hasOriginalException()) {
$original = $e->getOriginalException();
}
// Или через стандартную цепочку исключений
$previous = $e->getPrevious();
}
use GuzzleHttp\Client;
$customClient = new Client([
'timeout' => 30,
'verify' => false, // Отключить проверку SSL (не рекомендуется для продакшена)
]);
$request = new MAXRequest($accessToken, $customClient);
$client = new MAXClient($request);
use TH\MAX\Client\Request\MAXRequest;
class CustomMAXRequest extends MAXRequest
{
protected function getURL(string $method): string
{
return 'https://api.max.ru/v2/' . ltrim($method, '/');
}
}
use GuzzleHttp\Exception\GuzzleException;
use TH\MAX\Client\Request\MAXRequest;
class AppMAXRequest extends MAXRequest
{
protected function createException(string $message, int $code, GuzzleException $original): \Throwable
{
// Бросаем ваше доменное исключение вместо MAXHttpException
return new \App\Exceptions\ApiException($message, $code, $original);
}
}
H\MAX\Client\MAXClient;
use TH\MAX\Client\Request\MAXRequest;
use TH\MAX\Exceptions\MAXHttpException;
// Инициализация
$accessToken = 'ваш_access_token';
$request = new MAXRequest($accessToken);
$client = new MAXClient($request);
try {
// Получить информацию о боте
$bot = $client->bots()->getMe();
echo "Бот: " . $bot->name . "\n";
// Получить список чатов
$chats = $client->chats()->getAll(count: 10);
echo "Найдено чатов: " . count($chats->chats) . "\n";
// Отправить сообщение в первый чат
if (!empty($chats->chats)) {
$firstChat = $chats->chats[0];
$message = $client->messages()->send(
chat_id: $firstChat->id,
text: 'Привет из PHP SDK!'
);
echo "Сообщение отправлено с ID: " . $message->id . "\n";
}
} catch (MAXHttpException $e) {
echo "Ошибка API MAX: " . $e->getMessage() . "\n";
echo "HTTP код: " . $e->getCode() . "\n";
} catch (Exception $e) {
echo "Общая ошибка: " . $e->getMessage() . "\n";
}
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.