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

// AppServiceProvider
$this->app->instance(\Psr\Http\Client\ClientInterface::class, $yourClient);

use GeekCo\LaravelMaxClient\WebApp\WebAppContext;
use Illuminate\Http\Request;

class WebAppController
{
    public function __invoke(Request $request, WebAppContext $webAppContext)
    {
        $identity = $webAppContext->resolve($request); // GeekCo\MaxPhpClient\Dto\WebAppIdentity|null

        if ($identity === null) {
            abort(403);
        }

        // $identity->userId, $identity->chatId
    }
}

$webAppData = $request->header('X-Max-WebApp-Data');

if (is_string($webAppData) && $webAppContext->verifyData($webAppData)) {
    $identity = $webAppContext->resolveData($webAppData);
    // $identity->userId, $identity->chatId
}

// routes/web.php
Route::get('/webapp', WebAppController::class)->middleware('max.webapp');

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 — номер в цифрах без «+»
    }
}

Route::get('/webapp', WebAppController::class)->middleware(['max.webapp', 'max.csp']);

$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);

   // app/Providers/EventServiceProvider.php
   protected $listen = [
       \GeekCo\LaravelMaxClient\Webhook\MaxUpdateReceived::class => [
           YourUpdateListener::class,
       ],
   ];
   

   use GeekCo\LaravelMaxClient\Webhook\MaxUpdateReceived;

   class YourUpdateListener
   {
       public function handle(MaxUpdateReceived $event): void
       {
           $update = $event->update; // GeekCo\MaxPhpClient\Dto\Update
           // бизнес-обработка апдейта
       }
   }
   

Route::get('/webapp', WebAppController::class)->middleware(['max.webapp', 'max.log']);
bash
php artisan vendor:publish --tag=laravel-max-client-config
bash
   php artisan migrate
   
bash
php artisan migrate        # создаёт таблицу max_chat_users
php artisan max:upgrade    # переносит данные на новую структуру
bash
ls database/migrations/0001_01_01_00000{1,2}_create_max_{users,chats}_table.php
bash
rm database/migrations/0001_01_01_000001_create_max_users_table.php
rm database/migrations/0001_01_01_000002_create_max_chats_table.php
php artisan migrate
bash
php artisan max:listen