🚀 PHP клиент для интеграции с сервисом API чатов amoCRM
- ✨ Возможности
- 📦 Установка
- 🚀 Быстрый старт
- 🔌 Кастомные middleware
- 📢 Обработка ошибок
- 🔐 Работа с WebHooks
- 📝 Документация
- 📄 Лицензия
- Полное покрытие API чатов amoCRM
- Строгая типизация данных через DTO
- Гибкая система Middleware
- Предсказуемые данные в WebHooks
- Поддержка сегментов .ru и .com
- Подробная обработка ошибок
- Инструменты разработчика
- Строгая типизация (strict_types)
- PSR-12 совместимый код
- Полная документация PHPDoc
- Поддержка Guzzle и PSR-18
Установка через Composer:
composer require fcritic/amojo-api-client- PHP 7.4+
use AmoJo\Client\AmoJoClient;
use AmoJo\Models\Channel;
$channel = new Channel(uuid: 'channel-uuid', secretKey: 'secret-key');
$client = new AmoJoClient(
channel: $channel,
additionalMiddleware: [],
segment: 'ru'
);
$response = $client->connect(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
title: 'Мой канал',
hookVersion: 'v2'
);
echo 'Scope ID: ' . $response->getScopeId();$client->disconnect(accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d');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(
accountUuid: '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())->setUuid('MSG_100')->setText('Hello');
$response = $client->sendMessage(
accountUuid: '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())->setUuid('MSG_101')->setText('Hello');
$response = $client->sendMessage(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
payload: (new Payload())
->setConversation($conversation)
->setSender($sender)
->setReceiver($contact)
->setMessage($message),
externalId: 'Источник'
);$message = (new TextMessage())->setUuid('MSG_101')->setText('Hello, Richard');
$response = $client->editMessage(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
(new Payload())
->setConversation($conversation)
->setMessage($message)
);use AmoJo\Models\Messages\ReplyTo;
$message = (new TextMessage())->setUuid('MSG_102')->setText('I want to place an order');
$response = $client->sendMessage(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
payload: (new Payload())
->setConversation($conversation)
->setSender($contact)
->setMessage($message)
->setReplyTo((new ReplyTo())->setReplyUuid('MSG_101'))
);$response = $client->getHistoryChat(
accountUuid: '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;
$client->deliverStatus(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
messageUuid: $message->getRefUuid(),
deliver: (new Deliver(DeliveryStatus::ERROR))
->setErrorCode(ErrorCode::WITH_DESCRIPTION)
->setMessageError('User deleted')
);$client->react(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
conversation: $conversation,
sender: $contact,
message: $message,
emoji: '👍'
);$client->typing(
accountUuid: 'f36b8c48-ed97-4866-8aba-d55d429da86d',
conversation: $conversation,
sender: $contact,
);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]
);Клиент выбрасывает исключения при ошибках:
AmoJoException- Базовое исключениеEmptyMessageErrorException- Не передано сообщение об ошибки при 905 коде ошибке deliverStatus()InvalidRequestWebHookException- не валидном вебхуке об исходящим сообщенииInvalidResponseException- Некорректный ответ сервераNotFountException- некорректный URL запросаRequiredParametersMissingException- Отсутствуют обязательные параметрыSenderException- Не был передан ID внутреннего пользователя при исходящим сообщениеUnsupportedMessageTypeException- Передано неподдерживаемый типа сообщения
Пример обработки:
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\ValidatorHook;
if (!ValidatorHook::isValid(request: $request, secretKey: '465c28d756f...')) {
// Обработка не валидного вебхука
}use AmoJo\Webhook\AmoJoHookFactory;
$event = (new AmoJoHookFactory())->fromArray($requestBody);
var_dump($event->toArray());Официальная документация API чатов amoCRM:
Проект распространяется под лицензией MIT - подробности в файле LICENSE
