PHP code example of geekcodev / laravel-max-client
1. Go to this page and download the library: Download geekcodev/laravel-max-client 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/ */
geekcodev / laravel-max-client example snippets
use GeekCo\LaravelMaxClient\Facades\Max;
use GeekCo\MaxPhpClient\Dto\Recipient;
use GeekCo\MaxPhpClient\Dto\NewMessageBody;
$me = Max::getMe();
Max::sendMessage(
new Recipient(chatId: $chatId),
new NewMessageBody(text: 'Привет!'),
);
// Фасад делегирует все методы ядра (см. PHPDoc @method): чаты, участники,
// админы, закреп, команды, медиа, подписки.
Max::sendBotAction($chatId, SenderAction::Typing);
$admins = Max::getChatAdmins($chatId); // ChatAdminsResult::$members
use GeekCo\LaravelMaxClient\WebApp\ResolveWebAppIdentity;
class WebAppController
{
public function __invoke(Request $request)
{
$identity = $request->attributes->get(ResolveWebAppIdentity::REQUEST_ATTRIBUTE); // WebAppIdentity|null
// $request->session()->get('user_id'), $request->session()->get('chat_id')
}
}
use GeekCo\LaravelMaxClient\WebApp\WebAppSession;
class CabinetController
{
public function __invoke(Request $request, WebAppSession $webAppSession)
{
$userId = $webAppSession->userId($request); // int|null (ключ webapp.session.user_id)
$chatId = $webAppSession->chatId($request); // int|null
if (!$webAppSession->contactConfirmed($request, $userId ?? 0)) {
// контакт requestContact ещё не подтверждён для этого user_id
}
}
}
use GeekCo\LaravelMaxClient\WebApp\WebAppContactService;
use GeekCo\LaravelMaxClient\WebApp\WebAppSession;
class ContactController
{
public function __invoke(Request $request, WebAppContactService $contacts, WebAppSession $webAppSession)
{
// $request->input(...) — поля, переданные фронтендом из ответа requestContact()
$contact = $contacts->resolve(
$request->string('auth_date'),
$request->string('phone'),
$request->string('user_id'),
$request->string('hash'),
);
if ($contact === null) {
// подпись не сошлась / authDate просрочен — в лог уходит только факт и user_id
abort(403);
}
$webAppSession->confirm($request, $contact->userId); // contact->phone — номер в цифрах без «+»
}
}
$chat->maxUsers(); // HasManyThrough<MaxUser> — пользователи, чьи апдейты бот получал в чате
$chat->chatUsers(); // HasMany<MaxChatUser> — строки связей с их статусом и активностью
$user->maxChats(); // HasManyThrough<MaxChat> — чаты пользователя (сохранено с v1.1.x)
$user->chatLinks(); // HasMany<MaxChatUser>
$chat->displayName(); // title, а при пустом title — имя пользователя
$chat->maxUsers()->pluck('max_users.user_id');
use GeekCo\LaravelMaxClient\Services\MaxUserProfileService;
$profile = app(MaxUserProfileService::class);
// Подтянуть профили: chat_id берётся из активных max_chats (бот добавлен).
$profile->refresh(111); // один пользователь
$profile->refresh([111, 222, 333]); // группа
// Сохранить профиль из DTO ChatMember (getChatMembers / getChatAdmins).
$profile->upsertFromMember($member);
// Дозаполнить аватар, если пуст. chatId — явное указание (без реестра).
$profile->ensureAvatar($user);
$profile->ensureAvatar($user, chatId: 222);