PHP code example of fcritic / amojo-api-client

1. Go to this page and download the library: Download fcritic/amojo-api-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/ */

    

fcritic / amojo-api-client example snippets


use AmoJo\Client\AmoJoClient;
use AmoJo\Models\Channel;

$channel = new Channel(uid: 'channel-uid', secretKey: 'secret-key');
$client = new AmoJoClient(
    channel: $channel,
    additionalMiddleware: [],
    segment: 'ru'
);

$response = $client->connect(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    title: 'Мой канал',
    hookVersion: 'v2'
);

echo 'Scope ID: ' . $response->getScopeId();

$response = $client->disconnect(accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d');
if ($response->getDisconnect()) {
    echo 'Канал успешно отключен';
}

use AmoJo\Models\Conversation;
use AmoJo\Models\Users\Sender;

$conversation = (new Conversation())->setId('chat-123');
$contact = (new Sender())
    ->setId('user-123')
    ->setName('Иван Иванов')
    ->setAvatar('https://picsum.photos/300/300')
    ->setProfile((new UserProfile())->setPhone('+1464874556719'));

$response = $client->createChat(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    conversation: $conversation,
    contact: $contact
);

echo 'ID чата в API чатов: ' . $response->getConversationRefId();

use AmoJo\Models\Payload;
use AmoJo\Models\Messages\TextMessage;

$message = (new TextMessage())->setUid('MSG_100')->setText('Hello');

$response = $client->sendMessage(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    payload: (new Payload())
        ->setConversation($conversation)
        ->setSender($contact)
        ->setMessage($message),
    externalId: 'Источник'
);

echo 'ID чата в API чатов: ' . $response->getReceiverRefId();

use AmoJo\Models\Users\Receiver;

// amojo_id пользователя amoCRM
$sender = (new Sender())->setRefId('113de373-a2d3-4eb7-a67c-04660332df07');
$message = (new TextMessage())->setUid('MSG_101')->setText('Hello');

$response = $client->sendMessage(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    payload: (new Payload())
        ->setConversation($conversation)
        ->setSender($sender)
        ->setReceiver($contact)
        ->setMessage($message),
    externalId: 'Источник'
);

$message = (new TextMessage())->setUid('MSG_101')->setText('Hello, Richard');

$response = $client->editMessage(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    (new Payload())
        ->setConversation($conversation)
        ->setMessage($message)
);

use AmoJo\Models\Messages\ReplyTo;

$message = (new TextMessage())->setUid('MSG_102')->setText('I want to place an order');

$response = $client->sendMessage(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    payload: (new Payload())
        ->setConversation($conversation)
        ->setSender($contact)
        ->setMessage($message)
        ->setReplyTo((new ReplyTo())->setReplyUid('MSG_101'))
);

$response = $client->getHistoryChat(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    conversationRefId: $conversation->getRefId()
);

foreach ($response->getMessages() as $message) {
    echo 'Текст сообщения: ' . $message->getMessage()->getText();
}

use AmoJo\Enum\DeliveryStatus;
use AmoJo\Enum\ErrorCode;
use AmoJo\Models\Deliver;

$response = $client->deliverStatus(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    messageUid: $message->getRefUid(),
    deliver: (new Deliver(DeliveryStatus::ERROR))
        ->setErrorCode(ErrorCode::WITH_DESCRIPTION)
        ->setMessageError('User deleted')
);

if ($response->getDelivery()) {
    echo 'Статус установлен';
}

$response = $client->react(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    conversation: $conversation,
    sender: $contact,
    message: $message,
    emoji: '👍'
);

if ($response->getReact()) {
    echo 'Реакция установлена';
}

$response = $client->typing(
    accountUid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
    conversation: $conversation,
    sender: $contact,
);

if ($response->getTyping()) {
    echo 'Информация доставлена';
}

use AmoJo\Middleware\MiddlewareInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Closure;

final class LoggingMiddleware implements MiddlewareInterface
{
    public function __invoke(callable $handler): Closure
    {
        return function (RequestInterface $request, array $options) use ($handler) {
            error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());
            return $handler($request, $options);
        };
    }
}

$client = new AmoJoClient(
    channel: $channel,
    additionalMiddleware: [LoggingMiddleware::class]
);

try {
    // Вызов API метода
} catch (RequiredParametersMissingException $e) {
    echo "Ошибка: " . $e->getMessage();
} catch (AmoJoException $e) {
    var_dump([
        'type'    => $e->getType(),
        'message' => $e->getMessage(),
        'code'    => $e->getCode(),
        'context' => $e->getContext(),
        'file'    => $e->getFile(),
    ]);
}

use AmoJo\Webhook\ValidatorWebHooks;

if (! ValidatorWebHooks::isValid(request: $request, secretKey: '465c28d756f...')) {
    // Обработка не валидного вебхука
}

use AmoJo\Webhook\ParserWebHooks;
use AmoJo\Webhook\OutgoingMessageEvent;
use AmoJo\Webhook\ReactionEvent;
use AmoJo\Webhook\TypingEvent;

$event = (new ParserWebHooks())->parse($requestBody);
        
var_dump($event->toArray());