### Environment Configuration for Examples Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Configure your integration credentials in the .env file to run the provided examples. Ensure the CLIENT_REDIRECT_URI matches the one registered for your integration. ```dotenv CLIENT_ID="UUID интеграци" CLIENT_SECRET="Секретный ключ интеграции" CLIENT_REDIRECT_URI="https://example.com/examples/get_token.php (Важно обратить внимание, что он должен содержать в себе точно тот адрес, который был указан при создании интеграции)" ``` -------------------------------- ### widgets.install Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Installs a widget. ```APIDOC ## widgets.install ### Description Installs a widget. ### Method ```php install(WidgetModel $widgetModel) ``` ### Parameters #### Request Body - **model** (WidgetModel) - Required - The widget model. ### Response #### Success Response - Returns the WidgetModel model. ``` -------------------------------- ### Install a Widget in AmoCRM API Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Installs a widget in the AmoCRM interface. Requires a WidgetModel with the widget's configuration. Returns the installed WidgetModel. ```php install(WidgetModel $widgetModel); ``` -------------------------------- ### Install amoCRM API Library with Composer Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use Composer to install the official PHP library for amoCRM API. Requires PHP 7.1 or higher. ```bash composer require amocrm/amocrm-api-library ``` -------------------------------- ### Get Product Settings in AmoCRM API Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves the current settings for products. Returns a ProductsSettingsModel. ```php settings(); ``` -------------------------------- ### Get Leads Service Instance - PHP Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Instantiate the leads service object to interact with lead-related API methods. Ensure the API client is properly initialized. ```php $leadsService = $apiClient->leads(); ``` -------------------------------- ### Manage Webhooks in AmoCRM Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Provides examples for subscribing to and unsubscribing from amoCRM events using webhooks. Ensure the WebhookModel and AmoCRMApiException are imported. ```php webhooks(); // Подписка на событие добавления сделки $webhook = (new WebhookModel()) ->setDestination('https://example.com/webhook') ->setSettings(['add_lead', 'update_lead', 'add_contact']); try { $webhook = $webhooksService->subscribe($webhook); echo 'Подписка оформлена'; } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Отписка от вебхука try { if ($webhooksService->unsubscribe($webhook)) { echo 'Отписка выполнена'; } } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### AmoCRM Contact Service PHP Examples Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Manage contacts including creation, retrieval, updates, and linking to leads. Supports custom fields like phone and email. ```php setName('Иван Иванов'); try { $contact = $apiClient->contacts()->addOne($contact); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Привязка контакта к сделке $links = new LinksCollection(); $links->add($apiClient->leads()->getOne(3916883)); $apiClient->contacts()->link($contact, $links); // Обновление номера телефона контакта $contactToUpdate = $apiClient->contacts()->getOne(3); $customFields = $contactToUpdate->getCustomFieldsValues(); $phoneField = $customFields->getBy('fieldCode', 'PHONE'); if (empty($phoneField)) { $phoneField = (new MultitextCustomFieldValuesModel())->setFieldCode('PHONE'); $customFields->add($phoneField); } $phoneField->setValues( (new MultitextCustomFieldValueCollection()) ->add( (new MultitextCustomFieldValueModel()) ->setEnum('WORK') ->setValue('+79123456789') ) ); try { $apiClient->contacts()->updateOne($contactToUpdate); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Получение по фильтру $filter = new ContactsFilter(); $filter->setIds([3, 5]); try { $contacts = $apiClient->contacts()->get($filter); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Get List of Currencies Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieve a list of all available currencies using the currencies service. This can be done without any filters. ```php /** @var AmoCRMApiClient $apiClient */ # Получим сервис для работы с валютами $service = $apiClient->currencies(); # Получение списка валют try { $collection = $service->get(); var_dump($collection); } catch (AmoCRMApiException $e) { printError($e); die; } ``` -------------------------------- ### Get Leads with Filters and Includes Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Retrieves leads based on specified filters and includes related data such as contacts and loss reasons. ```APIDOC ## Get Leads ### Description Retrieves a collection of leads based on provided filters. It supports including related entities like contacts and loss reasons. ### Method GET ### Endpoint /api/v2/leads ### Query Parameters - **id** (array) - Optional - Filter leads by their IDs. - **responsible_user_id** (array) - Optional - Filter leads by the responsible user's ID. - **with** (array) - Optional - Specifies related entities to include in the response. Supported values include `contacts` and `loss_reason`. ### Request Example ```php $filter = new LeadsFilter(); $filter->setIds([1, 5170965])->setResponsibleUserId([504141]); $leads = $leadsService->get($filter, [LeadModel::CONTACTS, LeadModel::LOSS_REASON]); ``` ### Response #### Success Response (200) - **leads** (array) - A collection of lead objects matching the filter criteria. Each lead object may contain nested data for contacts and loss reasons if requested via the `with` parameter. ``` -------------------------------- ### Website Buttons Service - get Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves multiple website button entities based on filters. Supports 'with' parameters for additional data. ```APIDOC ## get ### Description Retrieves multiple website button entities. ### Parameters #### Query Parameters - **filter** (BaseEntityFilter) - Optional - A filter for the entities. - **with** (array) - Optional - An array of parameters to include additional data. ``` -------------------------------- ### Get a Single Website Button Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves a single website button by its ID. Supports additional parameters via the 'with' array. ```php getOne($id, array $with => []); ``` -------------------------------- ### Get Account Subdomain and Set API Client Domain Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Use this code to retrieve the account's subdomain using an access token and then set it on the API client. This is crucial when the account's subdomain might change. ```php /** * Получим модель с информацией о домене аккаунта по access_token * Подробнее: @see AccountDomainModel * * Запрос уходит на www.amocrm.ru/oauth2/account/subdomain * С Authorization: Bearer {access_token} * curl 'https://www.amocrm.ru/oauth2/account/subdomain' -H 'Authorization: Bearer {access_token}' * * @example examples/get_account_subdomain.php */ use AmoCRM\Models\AccountDomainModel;$accountDomain = $apiClient->getOAuthClient() ->getAccountDomain($accessToken); // Возьмём из полученной модели текущий subdomain аккаунта и засетим наш апи клиент $apiClient->setAccountBaseDomain($accountDomain->getSubdomain()); // ... дальше продолжаем работу с апи клиентом ``` -------------------------------- ### Customers Service Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Handles the creation and management of customers, including linking contacts, working with segments, and managing bonus points. Examples cover creating a customer, linking a contact, updating customer segments, and awarding bonus points. ```APIDOC ## Customers Service - `customers()` Creation and management of customers, linking contacts, working with segments, and bonus points. ### Usage ```php use AmoCRM\Collections\Customers\Segments\SegmentsCollection; use AmoCRM\Collections\LinksCollection; use AmoCRM\Filters\CustomersFilter; use AmoCRM\Models\Customers\CustomerModel; use AmoCRM\Models\Customers\Segments\SegmentModel; use AmoCRM\Models\Customers\BonusPointsActionModel; use AmoCRM\Exceptions\AmoCRMApiException; $customersService = $apiClient->customers(); // Create a customer $customer = (new CustomerModel())->setName('Regular client'); try { $customer = $customersService->addOne($customer); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Link a contact $contact = $apiClient->contacts()->getOne(9567095); $customersService->link($customer, (new LinksCollection())->add($contact)); // Update customer segment $filter = (new CustomersFilter())->setIds([$customer->getId()]); $customers = $customersService->get($filter); foreach ($customers as $c) { $c->setName('Updated client') ->setSegments((new SegmentsCollection())->add((new SegmentModel())->setId(38))); } try { $customersService->update($customers); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Award bonus points $bonusAction = (new BonusPointsActionModel()) ->setCustomerId($customer->getId()) ->setAmount(500); try { $newBalance = $apiClient->customersBonusPoints()->earnPoints($bonusAction); echo 'New balance: ' . $newBalance; } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` ``` -------------------------------- ### Get Currencies with Filter Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieve a paginated list of currencies using the currencies service with applied filters. You can set the limit and page number for the results. ```php # Получение списка валют с фильтром $filter = new CurrenciesFilter(); $filter->setLimit(50); $filter->setPage(2); try { $collection = $service->get($filter); var_dump($collection); } catch (AmoCRMApiException $e) { printError($e); die; } ``` -------------------------------- ### products.settings Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves product settings. ```APIDOC ## products.settings ### Description Retrieves product settings. ### Method ```php settings() ``` ### Response #### Success Response - Returns the ProductsSettingsModel model. ``` -------------------------------- ### Create Lead Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Demonstrates how to create a new lead with associated contacts and a company, and how to add tags. ```APIDOC ## Create Lead ### Description Creates a new lead, optionally associating it with existing contacts and a company, and allows adding tags. ### Method POST ### Endpoint /api/v2/leads ### Request Body - **name** (string) - Required - The name of the lead. - **price** (integer) - Optional - The price of the lead. - **contacts** (array) - Optional - A collection of contact IDs to associate with the lead. The `is_main` flag can be set for one contact. - **id** (integer) - Required - The ID of the contact. - **is_main** (boolean) - Optional - Indicates if this is the main contact for the lead. - **company** (object) - Optional - An object representing the company to associate with the lead. - **id** (integer) - Required - The ID of the company. - **tags** (array) - Optional - An array of tags to add to the lead. - **name** (string) - Required - The name of the tag. ### Request Example ```php $lead = new LeadModel(); $lead->setName('Новая сделка') ->setPrice(54321) ->setContacts( (new ContactsCollection()) ->add((new ContactModel())->setId(19346889)) ->add((new ContactModel())->setId(19324717)->setIsMain(true)) ) ->setCompany((new CompanyModel())->setId(19187743)); $lead->setTagsToAdd([['name' => 'Тег 123'], ['name' => 'Тег 456']]); $createdLead = $leadsService->addOne($lead); ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the newly created lead. ``` -------------------------------- ### Create Website Button Asynchronously Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Asynchronously creates a website button. Requires a model specifying pipeline ID, trusted websites, and app embedding status. ```php createAsync(WebsiteButtonCreateRequestModel $model); ``` -------------------------------- ### Get Access Token by Authorization Code Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves an access token using an authorization code. The code is a string parameter. ```php getAccessTokenByCode(string $code); ``` -------------------------------- ### Create and Use Tags in AmoCRM Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Demonstrates creating tags with colors, searching for existing tags, and applying them to leads. Ensure the API client and necessary models are imported. ```php tags(EntityTypesInterface::LEADS); // Создание тега с цветом $tag = (new TagModel())->setName('VIP клиент')->setColor(TagColorsEnum::LAPIS_LAZULI); try { $tagsService->add((new TagsCollection())->add($tag)); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Поиск тега try { $foundTags = $tagsService->get((new TagsFilter())->setQuery('VIP клиент')); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Создание сделки с тегом $lead = (new LeadModel())->setName('Новая сделка')->setTags($foundTags); try { $apiClient->leads()->add((new LeadsCollection())->add($lead)); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Удаление всех тегов у сущности $existingLead = $apiClient->leads()->getOne(1); $existingLead->setTags(new NullTagsCollection()); $apiClient->leads()->updateOne($existingLead); ``` -------------------------------- ### Create Lead with Custom Field Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Shows how to create a lead and assign a value to a custom text field. ```APIDOC ## Create Lead with Custom Field ### Description Creates a new lead and sets a value for a specific custom text field. ### Method POST ### Endpoint /api/v2/leads ### Request Body - **name** (string) - Required - The name of the lead. - **custom_fields_values** (array) - Optional - A collection of custom field values. - **field_id** (integer) - Required - The ID of the custom field. - **values** (array) - Required - An array of values for the custom field. - **value** (string) - Required - The text value for the custom field. ### Request Example ```php $lead2 = new LeadModel(); $lead2->setName('Сделка с полем') ->setCustomFieldsValues( (new CustomFieldsValuesCollection()) ->add( (new TextCustomFieldValuesModel()) ->setFieldId(269303) ->setValues( (new TextCustomFieldValueCollection()) ->add((new TextCustomFieldValueModel())->setValue('Значение')) ) ) ); $lead2 = $leadsService->addOne($lead2); ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the newly created lead. ``` -------------------------------- ### Manage Customers in AmoCRM Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Shows how to create customers, link contacts to them, update customer segments, and manage bonus points. Requires importing customer-related models and exceptions. ```php customers(); // Создание покупателя $customer = (new CustomerModel())->setName('Постоянный клиент'); try { $customer = $customersService->addOne($customer); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Привязка контакта $contact = $apiClient->contacts()->getOne(9567095); $customersService->link($customer, (new LinksCollection())->add($contact)); // Обновление сегмента покупателя $filter = (new CustomersFilter())->setIds([$customer->getId()]); $customers = $customersService->get($filter); foreach ($customers as $c) { $c->setName('Обновлённый клиент') ->setSegments((new SegmentsCollection())->add((new SegmentModel())->setId(38))); } try { $customersService->update($customers); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Начисление бонусных баллов $bonusAction = (new BonusPointsActionModel()) ->setCustomerId($customer->getId()) ->setAmount(500); try { $newBalance = $apiClient->customersBonusPoints()->earnPoints($bonusAction); echo 'Новый баланс: ' . $newBalance; } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Website Buttons Service - createAsync Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Asynchronously creates a new website button. Requires a model with pipeline ID, trusted websites, and app embedding status. ```APIDOC ## createAsync ### Description Asynchronously creates a new website button. ### Parameters #### Request Body - **model** (WebsiteButtonCreateRequestModel) - Required - The model containing website button properties: - **pipelineId** (int) - Required - The ID of the pipeline. - **trustedWebsites** (array) - Required - A list of trusted websites where the button will be placed. - **isUsedInApp** (true|false) - Required - Whether the button is used within an application. ``` -------------------------------- ### Get Unsorted Entity Summary in AmoCRM API Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves a summary of unsorted entities based on the provided filter. Returns an UnsortedSummaryModel. ```php summary(BaseEntityFilter $filter); ``` -------------------------------- ### Manage Leads with AmoCRM PHP SDK Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use this snippet to create, retrieve, and update leads. It demonstrates associating leads with contacts and companies, setting custom fields, and managing tags. Ensure the API client is initialized and necessary models are imported. ```php leads(); // Создание сделки с контактами и компанией $lead = new LeadModel(); $lead->setName('Новая сделка') ->setPrice(54321) ->setContacts( (new ContactsCollection()) ->add((new ContactModel())->setId(19346889)) ->add((new ContactModel())->setId(19324717)->setIsMain(true)) ) ->setCompany((new CompanyModel())->setId(19187743)); $lead->setTagsToAdd([['name' => 'Тег 123'], ['name' => 'Тег 456']]); try { $createdLead = $leadsService->addOne($lead); echo 'Создана сделка с ID: ' . $createdLead->getId(); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Создание сделки с дополнительным полем типа текст $lead2 = new LeadModel(); $lead2->setName('Сделка с полем') ->setCustomFieldsValues( (new CustomFieldsValuesCollection()) ->add( (new TextCustomFieldValuesModel()) ->setFieldId(269303) ->setValues( (new TextCustomFieldValueCollection()) ->add((new TextCustomFieldValueModel())->setValue('Значение')) ) ) ); try { $lead2 = $leadsService->addOne($lead2); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Получение по фильтру с дополнительными данными (with) $filter = new LeadsFilter(); $filter->setIds([1, 5170965])->setResponsibleUserId([504141]); try { $leads = $leadsService->get($filter, [LeadModel::CONTACTS, LeadModel::LOSS_REASON]); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Обновление найденных сделок foreach ($leads as $lead) { $lead->setName('Обновлённая сделка') ->setPrice(99) ->setTags(new NullTagsCollection()); // удаляем теги } try { $leadsService->update($leads); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Get Access Token by Refresh Token Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Obtains a new access token using an existing AccessTokenInterface object which contains the refresh token. ```php getAccessTokenByRefreshToken(AccessTokenInterface $accessToken); ``` -------------------------------- ### Paginate Through Entity Services Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use `nextPage()` and `prevPage()` methods on entity services to navigate through large datasets. Handle `AmoCRMApiPageNotAvailableException` if a requested page does not exist. ```php leads(); $filter = new LeadsFilter(); try { // Первая страница (по 50 сущностей по умолчанию) $page1 = $leadsService->get($filter); echo 'Страница 1: ' . $page1->count() . ' сделок'; // Следующая страница $page2 = $leadsService->nextPage($page1); echo 'Страница 2: ' . $page2->count() . ' сделок'; } catch (AmoCRMApiPageNotAvailableException $e) { echo 'Следующая страница недоступна'; } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Get OAuth Authorization URL Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Generates a URL for application authorization. Pass an array of options, including a 'state' string for application state management. ```php getAuthorizeUrl(array $options = []); ``` -------------------------------- ### products.updateSettings Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Updates product settings. ```APIDOC ## products.updateSettings ### Description Updates product settings. ### Method ```php updateSettings(ProductsSettingsModel $productsSettings) ``` ### Parameters #### Request Body - **model** (ProductsSettingsModel) - Required - The widget model. ### Response #### Success Response - Returns the ProductsSettingsModel model. ``` -------------------------------- ### Nullify Custom Field Values for an Entity Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md This example shows how to remove or nullify the values of a custom field for an entity by using `NullCustomFieldValueCollection`. This is useful for resetting fields. ```php //Создадим модель сущности $lead = new LeadModel(); $lead->setId(1); //Создадим коллекцию полей сущности $leadCustomFieldsValues = new CustomFieldsValuesCollection(); //Создадим модель значений поля типа текст $textCustomFieldValuesModel = new TextCustomFieldValuesModel(); //Укажем ID поля $textCustomFieldValuesModel->setFieldId(123); //Обнулим значения $textCustomFieldValuesModel->setValues( (new NullCustomFieldValueCollection()) ); //Добавим значение в коллекцию полей сущности $leadCustomFieldsValues->add($textCustomFieldValuesModel); //Установим сущности эти поля $lead->setCustomFieldsValues($leadCustomFieldsValues); ``` -------------------------------- ### Get Current Account Information in AmoCRM API Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Fetches the current account details. You can specify 'with' parameters to include additional related data in the response. ```php getCurrent(array $with = []); ``` -------------------------------- ### Get OAuth Button HTML Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Generates the HTML code for an OAuth authorization button. Accepts an options array for customization, including state, color, title, and more. ```php getOAuthButton(array $options = []); ``` -------------------------------- ### Authorize with OAuth 2.0 in PHP Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Initialize the API client and obtain an Access Token using the OAuth 2.0 authorization code flow. This involves redirecting the user and then exchanging the code for a token. The token is saved and refreshed automatically. ```php getOAuthClient()->getAuthorizeUrl([ 'state' => $state, 'mode' => 'post_message', ]); header('Location: ' . $authorizationUrl); // Шаг 2: Обработка callback и получение токена // (в обработчике redirect_uri) $accessToken = $apiClient->getOAuthClient()->getAccessTokenByCode($_GET['code']); // Сохраняем токен и устанавливаем домен $apiClient->setAccessToken($accessToken) ->setAccountBaseDomain($apiClient->getAccountBaseDomain()) ->onAccessTokenRefresh( function (AccessTokenInterface $accessToken, string $baseDomain) { // Сохраняем обновлённый токен в хранилище saveToken([ 'accessToken' => $accessToken->getToken(), 'refreshToken' => $accessToken->getRefreshToken(), 'expires' => $accessToken->getExpires(), 'baseDomain' => $baseDomain, ]); } ); ``` -------------------------------- ### Manage Pipelines and Statuses in AmoCRM Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use this service to create, update, retrieve, and delete pipelines and their associated statuses for deals. Ensure proper exception handling for API requests. ```php pipelines(); // Создание воронки со статусами $statusesCollection = (new StatusesCollection()) ->add((new StatusModel())->setName('Новый лид')->setColor('#fffd7f')) ->add((new StatusModel())->setName('В работе')->setColor('#ccc8f9')); $pipeline = (new PipelineModel()) ->setName('Основная воронка') ->setIsMain(true) ->setStatuses($statusesCollection); $pipelinesCollection = (new PipelinesCollection())->add($pipeline); try { $pipelinesCollection = $pipelinesService->add($pipelinesCollection); echo 'Создана воронка с ID: ' . $pipelinesCollection->first()->getId(); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Обновление воронки $pipelineModel = $pipelinesCollection->first(); $pipelineModel->setName('Переименованная воронка')->setIsMain(false); try { $pipelinesService->updateOne($pipelineModel); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Получение всех воронок try { $all = $pipelinesService->get(); echo $all->count() . ' воронок в аккаунте'; } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Удаление воронки try { $pipelinesService->deleteOne($pipelineModel); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Get Entity Links Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieves the links associated with a specific CRM entity. Requires the main entity model and an optional LinksFilter object to specify filtering criteria. ```php getLinks(BaseApiModel $model, LinksFilter $filter); ``` -------------------------------- ### Complex Lead Creation - leads()->addComplex() Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Allows for batch creation of leads along with associated contacts and companies in a single request. Supports duplicate control via `request_id`. ```APIDOC ## leads()->addComplex() ### Description Batch creation of leads with associated contacts and companies in one request. Supports duplicate control by `request_id`. ### Method POST (implied by batch creation and API interaction) ### Endpoint (Not explicitly provided, assumed to be part of the leads API) ### Parameters - **leadsCollection** (LeadsCollection) - Required - A collection of LeadModel objects to be created. ### Request Example ```php setName('Lead name') ->setPrice(54321) ->setTags((new TagsCollection())->add((new TagModel())->setName('Новый клиент'))) ->setContacts( (new ContactsCollection()) ->add( (new ContactModel()) ->setFirstName('Иван') ->setLastName('Иванов') ->setCustomFieldsValues( (new CustomFieldsValuesCollection()) ->add( (new MultitextCustomFieldValuesModel()) ->setFieldCode('PHONE') ->setValues( (new MultitextCustomFieldValueCollection()) ->add((new MultitextCustomFieldValueModel())->setValue('+79129876543')) ) ) ) ) ) ->setCompany((new CompanyModel())->setName('ООО Пример')) ->setRequestId('0752a617-c834-4bde-b4a6-76ff0fe26871') ->setMetadata( (new FormsMetadata()) ->setFormId('my_form') ->setFormName('Обратная связь') ->setFormPage('https://example.com/form') ->setFormSentAt(time()) ->setReferer('https://google.com') ->setIp('192.168.0.1') ); $leadsCollection->add($lead); try { $addedLeads = $apiClient->leads()->addComplex($leadsCollection); foreach ($addedLeads as $addedLead) { $action = $addedLead->isMerged() ? 'обновлены' : 'созданы'; echo "Сделка ({$addedLead->getId()}) {$action}"; } } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` ### Response #### Success Response (200) - **addedLeads** (array of LeadModel) - A collection of created or updated LeadModel objects. ``` -------------------------------- ### Get Multiple Entities - PHP Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieve a collection of entities, optionally filtered by criteria. Supports 'with' parameters for related data. The filter parameter should be an instance of BaseEntityFilter. ```php get(?BaseEntityFilter $filter = null, array $with = []); ``` -------------------------------- ### Handle Unsorted Leads with AmoCRM API PHP SDK Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use this service to add leads via forms or calls to the 'Unsorted' section, accept or reject them, and retrieve statistics. Ensure necessary models and exceptions are imported. ```php unsorted(); // Добавление через форму $formUnsorted = new FormUnsortedModel(); $formUnsorted ->setSourceName('Сайт') ->setSourceUid('site_uid_001') ->setCreatedAt(time()) ->setPipelineId(3166396) ->setMetadata( (new FormsMetadata()) ->setFormId('feedback') ->setFormName('Обратная связь') ->setFormPage('https://example.com/contact') ->setFormSentAt(time()) ->setReferer('https://yandex.ru') ->setIp('10.0.0.1') ) ->setLead((new LeadModel())->setName('Заявка с сайта')->setPrice(0)) ->setContacts((new ContactsCollection())->add((new ContactModel())->setName('Новый клиент'))); try { $unsortedService->add((new FormsUnsortedCollection())->add($formUnsorted)); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Принятие первого неразобранного try { $unsortedCollection = $unsortedService->get( (new UnsortedFilter())->setCategory([BaseUnsortedModel::CATEGORY_CODE_FORMS]) ); $acceptResult = $unsortedService->accept($unsortedCollection->first()); echo 'Принята сделка с ID: ' . $acceptResult->getLeads()->first()->getId(); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Статистика неразобранного за 10 дней try { $summary = $unsortedService->summary( (new UnsortedSummaryFilter()) ->setCreatedAt((new BaseRangeFilter())->setFrom(time() - 864000)->setTo(time())) ); var_dump($summary->toArray()); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Get One Entity - PHP Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieve a single entity by its ID. Supports optional 'with' parameters for including related data. Ensure the ID is of type int or string. ```php getOne($id, array $with = []); ``` -------------------------------- ### Add Multiple Entities - PHP Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Create multiple entities in a batch operation. The entities should be provided as a BaseApiCollection. The result will be a collection of the created entity models. ```php add(BaseApiCollection $collection); ``` -------------------------------- ### Get Notes or Entity Subscriptions by Parent ID in AmoCRM API Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Retrieve notes or entity subscriptions associated with a parent entity ID. Supports filtering and 'with' parameters for related data. ```php getByParentId(int $parentId, ?BaseEntityFilter $filter = null, array $with = []); ``` -------------------------------- ### Set Custom User Agent for AmoCRM API Requests Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Starting from version 1.5.0, you can specify a custom User Agent for requests made with the library. This helps identify your application when interacting with the API. ```php $apiClient = new \AmoCRM\Client\AmoCRMApiClient($clientId, $clientSecret, $redirectUri); $apiClient = $apiClient->setUserAgnet('App Name'); ``` -------------------------------- ### Manage Files with AmoCRM API PHP SDK Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use this service to upload files to AmoCRM Drive, manage them, and link them to entities. Ensure necessary models and exceptions are imported. ```php files(); // Поиск файлов по расширению $filter = (new FilesFilter())->setExtensions(['jpg', 'jpeg', 'png']); try { $files = $filesService->get($filter); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Загрузка файла $uploadModel = (new FileUploadModel()) ->setName('document.pdf') ->setLocalPath('/var/www/uploads/document.pdf'); try { $file = $filesService->uploadOne($uploadModel); echo 'UUID загруженного файла: ' . $file->getUuid(); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Привязка файла к сделке (вкладка "Файлы") try { $apiClient->entityFiles(EntityTypesInterface::LEADS, 21825653)->add( (new FileLinksCollection()) ->add((new FileLinkModel())->setFileUuid($file->getUuid())) ); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } // Получение всех файлов, прикреплённых к сделке try { $entityFiles = $apiClient->entityFiles(EntityTypesInterface::LEADS, 21825653)->get(); var_dump($entityFiles->toArray()); } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Update Website Button Asynchronously Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Asynchronously updates a website button by adding trusted websites. Requires the source ID and a list of websites to add. ```php updateAsync(WebsiteButtonUpdateRequestModel $model); ``` -------------------------------- ### Authorize in User Context in PHP Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Execute API requests on behalf of a specific user by creating a new client instance with the user's ID. This is useful if the access token was issued by an administrator. ```php withContextUserId(123); $leads = $apiClientAsUser->leads()->get(); ``` -------------------------------- ### Handle AmoCRM API Exceptions Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Demonstrates how to catch and handle various AmoCRM API exceptions. Each exception type provides specific error information. ```php catch (AmoCRMApiException $e) { // Handle exception } ``` -------------------------------- ### Complex Lead Creation with AmoCRM API PHP Source: https://context7.com/amocrm/amocrm-api-php/llms.txt Use `leads()->addComplex()` for batch creation of leads with associated contacts and companies. Supports duplicate control via `request_id`. ```php setName('Lead name') ->setPrice(54321) ->setTags((new TagsCollection())->add((new TagModel())->setName('Новый клиент'))) ->setContacts( (new ContactsCollection()) ->add( (new ContactModel()) ->setFirstName('Иван') ->setLastName('Иванов') ->setCustomFieldsValues( (new CustomFieldsValuesCollection()) ->add( (new MultitextCustomFieldValuesModel()) ->setFieldCode('PHONE') ->setValues( (new MultitextCustomFieldValueCollection()) ->add((new MultitextCustomFieldValueModel())->setValue('+79129876543')) ) ) ) ) ) ->setCompany((new CompanyModel())->setName('ООО Пример')) ->setRequestId('0752a617-c834-4bde-b4a6-76ff0fe26871') ->setMetadata( (new FormsMetadata()) ->setFormId('my_form') ->setFormName('Обратная связь') ->setFormPage('https://example.com/form') ->setFormSentAt(time()) ->setReferer('https://google.com') ->setIp('192.168.0.1') ); $leadsCollection->add($lead); try { $addedLeads = $apiClient->leads()->addComplex($leadsCollection); foreach ($addedLeads as $addedLead) { $action = $addedLead->isMerged() ? 'обновлены' : 'созданы'; echo "Сделка ({$addedLead->getId()}) {$action}"; } } catch (AmoCRMApiException $e) { echo $e->getTitle(); die; } ``` -------------------------------- ### Add Online Chat to Website Button Asynchronously Source: https://github.com/amocrm/amocrm-api-php/blob/master/README.md Asynchronously adds an 'Online Chat' communication channel to a website button. Requires the source ID. ```php addOnlineChatAsync(int $sourceId); ```