Skip to content

Commit

Permalink
Merge pull request #420 from amocrm/feature/api_templates
Browse files Browse the repository at this point in the history
Feature/api templates
  • Loading branch information
bessudnov authored Dec 24, 2021
2 parents 808e71e + ffe83d7 commit 597eef6
Show file tree
Hide file tree
Showing 27 changed files with 1,016 additions and 27 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ $leadsService = $apiClient->leads();
| shortLinks | Короткие ссылки |
| talks | Беседы |
| sources | Источники |
| chatTemplates | Шаблоны чатов |
| entitySubscriptions | Подписчики сущности |
| getOAuthClient | oAuth сервис |
| getRequest | Голые запросы |
Expand Down Expand Up @@ -544,6 +545,7 @@ $leadsService = $apiClient->leads();
|```unsorted``` |```\AmoCRM\Filters\UnsortedSummaryFilter```|Фильтр для метода `\AmoCRM\EntitiesServices\Unsorted::summary` |❌ |
|```webhooks``` |```\AmoCRM\Filters\WebhooksFilter``` |Фильтр для метода получения хуков |❌ |
|```sources``` |```\AmoCRM\Filters\SourcesFilter``` |Фильтр для метода получения источников `\AmoCRM\EntitiesServices\Sources::get` |❌ |
|```chatTemplates``` |```\AmoCRM\Filters\Chats\TemplatesFilter```|Фильтр для метода получения шаблонов чатов `\AmoCRM\EntitiesServices\Chats\Templates::get` |❌ |
|Сервисы, где необходима постраничная навигация |```\AmoCRM\Filters\PagesFilter``` |Фильтр, который подходит для любого сервиса, где есть постраничная навигация |❌ |


Expand Down Expand Up @@ -817,6 +819,8 @@ $lead->setTags((new NullTagsCollection()));
20. ```\AmoCRM\Models\CompanyModel``` - константы для аргумента with для сервиса ```companies```
21. ```\AmoCRM\Models\CatalogElementModel``` - константы для аргумента with для сервиса ```catalogElements```
22. ```\AmoCRM\Enum\InvoicesCustomFieldsEnums``` - константы для работы с полями каталога счетов
23. ```\AmoCRM\Enum\Chats\Templates\Buttons\ButtonsEnums``` - типы кнопок шаблонов чатов
24. ```\AmoCRM\Enum\Sources\SourceServiceTypeEnum``` - типы сервисов для источников

## Работа в случае смены субдомена аккаунта

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"symfony/dotenv": "3.* || 4.* || 5.* || 6.*",
"fig/http-message-util": "1.*",
"ramsey/uuid": "^3 || ^4",
"lcobucci/jwt": "^3.4 || 4.*",
"lcobucci/jwt": "^3.4 || ^4.0.4",
"nesbot/carbon": "^2.52"
},
"require-dev": {
Expand All @@ -38,6 +38,7 @@
"psr-4": {
"AmoCRM\\": "src/",
"AmoCRM\\Client\\": "src/AmoCRM/Client",
"AmoCRM\\Enum\\": "src/AmoCRM/Enum",
"AmoCRM\\OAuth\\": "src/AmoCRM/OAuth",
"AmoCRM\\EntitiesServices\\": "src/AmoCRM/EntitiesServices",
"AmoCRM\\Exceptions\\": "src/AmoCRM/Exceptions",
Expand Down
99 changes: 99 additions & 0 deletions examples/chat_templates_actions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

use AmoCRM\Collections\Chats\Templates\Buttons\ButtonsCollection;
use AmoCRM\Exceptions\AmoCRMApiException;
use AmoCRM\Models\Chats\Templates\Buttons\TextButtonModel;
use AmoCRM\Models\Chats\Templates\TemplateModel;
use League\OAuth2\Client\Token\AccessTokenInterface;

include_once __DIR__ . '/bootstrap.php';

$accessToken = getToken();

$apiClient->setAccessToken($accessToken)
->setAccountBaseDomain($accessToken->getValues()['baseDomain'])
->onAccessTokenRefresh(
function (AccessTokenInterface $accessToken, string $baseDomain) {
saveToken(
[
'accessToken' => $accessToken->getToken(),
'refreshToken' => $accessToken->getRefreshToken(),
'expires' => $accessToken->getExpires(),
'baseDomain' => $baseDomain,
]
);
}
);


$chatTemplatesService = $apiClient->chatTemplates();

// Создадим редактируемый шаблон
$chatTemplate = new TemplateModel();
$chatTemplate
->setName('Название шаблона')
->setContent('Название сделки - {{lead.name}}')
->setExternalId('qwedsgfsdg-dsgsdg') //Идентификатор шаблона на стороне интеграции
->setIsEditable(true);

try {
$chatTemplate = $chatTemplatesService->addOne($chatTemplate);
} catch (AmoCRMApiException $e) {
printError($e);
die;
}
echo 'Добавленный шаблон: ';
var_dump($chatTemplate->toArray());
echo PHP_EOL;


// Обновим шаблон и добавим в него кнопки. Кнопок разного типа быть не может
$buttonsCollection = new ButtonsCollection();
$buttonsCollection
->add(
(new TextButtonModel())->setText('Текст кнопки')
)
->add(
(new TextButtonModel())->setText('Текст кнопки2')
);
$chatTemplate->setButtons($buttonsCollection);


try {
$chatTemplatesService->updateOne($chatTemplate);
} catch (AmoCRMApiException $e) {
printError($e);
die;
}


// Получим шаблоны
try {
$chatTemplatesCollection = $chatTemplatesService->get();
} catch (AmoCRMApiException $e) {
printError($e);
die;
}
var_dump($chatTemplatesCollection->toArray());


// Получим шаблоны по ExternalId
$templatesFilter = new \AmoCRM\Filters\Chats\TemplatesFilter();
$templatesFilter->setExternalIds(['qwedsgfsdg-dsgsdg']);
try {
$chatTemplate = $chatTemplatesService->get($templatesFilter)->first();
} catch (AmoCRMApiException $e) {
printError($e);
die;
}
var_dump($chatTemplate->toArray());

// Удалим первый шаблон
try {
$chatTemplatesService->deleteOne($chatTemplate);
} catch (AmoCRMApiException $e) {
printError($e);
die;
}
4 changes: 2 additions & 2 deletions examples/sources_actions.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

use AmoCRM\AmoCRM\Models\Sources\SourceServiceTypeEnumInterface;
use AmoCRM\Enum\Sources\SourceServiceTypeEnum;
use AmoCRM\Collections\Sources\SourceServicesCollection;
use AmoCRM\Collections\Sources\SourceServicesPagesCollection;
use AmoCRM\Collections\SourcesCollection;
Expand Down Expand Up @@ -45,7 +45,7 @@ function (AccessTokenInterface $accessToken, string $baseDomain) {
$page->setId($page->getLink());

$whatsappSourceService = new SourceServiceModel();
$whatsappSourceService->setType(SourceServiceTypeEnumInterface::TYPE_WHATSAPP);
$whatsappSourceService->setType(SourceServiceTypeEnum::TYPE_WHATSAPP);
$whatsappSourceService->setPages(SourceServicesPagesCollection::make([$page]));
$source->setServices(SourceServicesCollection::make([$whatsappSourceService]));

Expand Down
2 changes: 1 addition & 1 deletion examples/talks_actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

use AmoCRM\AmoCRM\Models\Talks\TalkCloseActionModel;
use AmoCRM\Models\Talks\TalkCloseActionModel;
use AmoCRM\Exceptions\AmoCRMApiException;
use League\OAuth2\Client\Token\AccessTokenInterface;

Expand Down
16 changes: 15 additions & 1 deletion src/AmoCRM/Client/AmoCRMApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use AmoCRM\EntitiesServices\Calls;
use AmoCRM\EntitiesServices\CatalogElements;
use AmoCRM\EntitiesServices\Catalogs;
use AmoCRM\EntitiesServices\Chats\Templates;
use AmoCRM\EntitiesServices\Companies;
use AmoCRM\EntitiesServices\Contacts;
use AmoCRM\EntitiesServices\Customers\BonusPoints;
Expand Down Expand Up @@ -465,7 +466,20 @@ public function sources(): Sources
{
$request = $this->buildRequest();

return new Sources($request);
return new Sources($request);
}

/**
* Метод вернет объект шаблонов чатов
*
* @return Templates
* @throws AmoCRMMissedTokenException
*/
public function chatTemplates(): Templates
{
$request = $this->buildRequest();

return new Templates($request);
}

/**
Expand Down
3 changes: 1 addition & 2 deletions src/AmoCRM/Client/AmoCRMApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class AmoCRMApiRequest
public const CONNECT_TIMEOUT = 5;
public const REQUEST_TIMEOUT = 20;
//TODO Do not forget to change this on each release
public const LIBRARY_VERSION = '0.5.2';
public const LIBRARY_VERSION = '0.7.0';
public const USER_AGENT = 'amoCRM-API-Library/' . self::LIBRARY_VERSION;

public const SUCCESS_STATUSES = [
Expand Down Expand Up @@ -278,7 +278,6 @@ public function patch(
* @return array
* @throws AmoCRMApiException
* @throws AmoCRMoAuthApiException
* @throws AmoCRMApiNoContentException
*/
public function delete(
string $method,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace AmoCRM\Collections\Chats\Templates\Buttons;

use AmoCRM\Collections\BaseApiCollection;
use AmoCRM\Exceptions\InvalidArgumentException;
use AmoCRM\Models\Chats\Templates\Buttons\AbstractButtonModel;

/**
* Class ButtonsCollection
*
* @package AmoCRM\Collections\Chats\Templates\Buttons
*
* @method null|AbstractButtonModel current()
* @method null|AbstractButtonModel last()
* @method null|AbstractButtonModel first()
* @method null|AbstractButtonModel offsetGet($offset)
* @method ButtonsCollection offsetSet($offset, AbstractButtonModel $value)
* @method ButtonsCollection prepend(AbstractButtonModel $value)
* @method ButtonsCollection add(AbstractButtonModel $value)
* @method null|AbstractButtonModel getBy($key, $value)
*/
class ButtonsCollection extends BaseApiCollection
{
public const ITEM_CLASS = AbstractButtonModel::class;

/**
* @param array $array
*
* @return ButtonsCollection
*/
public static function fromArray(array $array): BaseApiCollection
{
$items = array_map(
static function (array $item) {
try {
return AbstractButtonModel::fromArray($item);
} catch (InvalidArgumentException $e) {
return null;
}
},
$array
);

return self::make($items);
}
}
31 changes: 31 additions & 0 deletions src/AmoCRM/Collections/Chats/Templates/TemplatesCollection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace AmoCRM\Collections\Chats\Templates;

use AmoCRM\Collections\BaseApiCollection;
use AmoCRM\Collections\Interfaces\HasPagesInterface;
use AmoCRM\Collections\Traits\PagesTrait;
use AmoCRM\Models\Chats\Templates\TemplateModel;

/**
* Class TemplatesCollection
*
* @package AmoCRM\Collections\Chats\Templates
*
* @method null|TemplateModel current()
* @method null|TemplateModel last()
* @method null|TemplateModel first()
* @method null|TemplateModel offsetGet($offset)
* @method TemplatesCollection offsetSet($offset, TemplateModel $value)
* @method TemplatesCollection prepend(TemplateModel $value)
* @method TemplatesCollection add(TemplateModel $value)
* @method null|TemplateModel getBy($key, $value)
*/
class TemplatesCollection extends BaseApiCollection implements HasPagesInterface
{
use PagesTrait;

public const ITEM_CLASS = TemplateModel::class;
}
2 changes: 2 additions & 0 deletions src/AmoCRM/Collections/SourcesCollection.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

namespace AmoCRM\Collections;

use AmoCRM\Collections\Traits\EntityApiTrait;
Expand Down
4 changes: 3 additions & 1 deletion src/AmoCRM/Collections/SubscriptionsCollection.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<?php

declare(strict_types=1);

namespace AmoCRM\Collections;

use AmoCRM\AmoCRM\Models\SubscriptionModel;
use AmoCRM\Models\SubscriptionModel;
use AmoCRM\Collections\Interfaces\HasPagesInterface;
use AmoCRM\Collections\Traits\PagesTrait;
use AmoCRM\Models\RoleModel;
Expand Down
Loading

0 comments on commit 597eef6

Please sign in to comment.