Інтеграція amoCRM із сайтом API

AmoCRM одна з найпопулярніших CRM.
У цій статті ми створимо угоду в “Нерозібраному”, контакт та компанію.
Створюємо файли інтеграції
Створюємо теку amo, наприклад, у корені сайту.
Файли всередині:
amo.php
access.php
config.php
get.php
cookie.txt
tokens.txt
Назви можуть бути довільними.
Отримання ключів
Відкриваємо AmoCRM, заходимо до Установок > Інтеграції.
Тиснемо “+ Створити інтеграцію” та створюємо зовнішню інтеграцію
Вказуємо посилання на наш amo.php файл, ставимо галочку надання доступу та вводимо довільну назву та опис:
Отримуємо 3 ключі.
Відкриваємо config.php і вписуємо їх туди:
$subdomain = ''; // поддомен AmoCRM
$client_secret = ''; // Секретный ключ
$client_id = ''; // ID интеграции
$code = ''; // Код авторизации
$token_file = 'tokens.txt';
$redirect_uri = 'https://site.com/amo/amo.php';
Піддомен AmoCRM беремо з url нашої CRM
У $redirect_uri не забудьте змінити свій домен сайту
Потім йдемо у файл auth.php і вставимо наступне:
require_once 'config.php';
$link = "https://$subdomain.amocrm.ru/oauth2/access_token";
$data = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $redirect_uri,
];
$curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-oAuth-client/1.0');
curl_setopt($curl,CURLOPT_URL, $link);
curl_setopt($curl,CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($curl,CURLOPT_HEADER, false);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 2);
$out = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$code = (int)$code;
$errors = [
301 => 'Moved permanently.',
400 => 'Wrong structure of the array of transmitted data, or invalid identifiers of custom fields.',
401 => 'Not Authorized. There is no account information on the server. You need to make a request to another server on the transmitted IP.',
403 => 'The account is blocked, for repeatedly exceeding the number of requests per second.',
404 => 'Not found.',
500 => 'Internal server error.',
502 => 'Bad gateway.',
503 => 'Service unavailable.'
];
if ($code < 200 || $code > 204) die( "Error $code. " . (isset($errors[$code]) ? $errors[$code] : 'Undefined error') );
$response = json_decode($out, true);
$arrParamsAmo = [
"access_token" => $response['access_token'],
"refresh_token" => $response['refresh_token'],
"token_type" => $response['token_type'],
"expires_in" => $response['expires_in'],
"endTokenTime" => $response['expires_in'] + time(),
];
$arrParamsAmo = json_encode($arrParamsAmo);
$f = fopen($token_file, 'w');
fwrite($f, $arrParamsAmo);
fclose($f);
print_r($arrParamsAmo);
Тут ми надсилаємо запит до AmoCRM для отримання токенів. Токени зберігаються в файл (45-57 рядки), ви можете зберігати їх у БД.
Запустіть файл https://site.com/amo/auth.php
Як результат у файлі tokens.txt повинні з’явитися дані.
Оновлення токена
Access token є тимчасовим та потребує оновлення.
Відкриваємо файл access.php та додаємо наступне:
require_once 'config.php';
$dataToken = file_get_contents($token_file);
$dataToken = json_decode($dataToken, true);
if ($dataToken["endTokenTime"] < time()) { $link = "https://$subdomain.amocrm.ru/oauth2/access_token"; $data = [ 'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'refresh_token',
'refresh_token' => $dataToken["refresh_token"],
'redirect_uri' => $redirect_uri,
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'amoCRM-oAuth-client/1.0');
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
$out = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$code = (int)$code;
$errors = [
301 => 'Moved permanently.',
400 => 'Wrong structure of the array of transmitted data, or invalid identifiers of custom fields.',
401 => 'Not Authorized. There is no account information on the server. You need to make a request to another server on the transmitted IP.',
403 => 'The account is blocked, for repeatedly exceeding the number of requests per second.',
404 => 'Not found.',
500 => 'Internal server error.',
502 => 'Bad gateway.',
503 => 'Service unavailable.'
];
if ($code < 200 || $code > 204) die( "Error $code. " . (isset($errors[$code]) ? $errors[$code] : 'Undefined error') );
$response = json_decode($out, true);
$arrParamsAmo = [
"access_token" => $response['access_token'],
"refresh_token" => $response['refresh_token'],
"token_type" => $response['token_type'],
"expires_in" => $response['expires_in'],
"endTokenTime" => $response['expires_in'] + time(),
];
$arrParamsAmo = json_encode($arrParamsAmo);
$f = fopen($token_file, 'w');
fwrite($f, $arrParamsAmo);
fclose($f);
$access_token = $response['access_token'];
} else {
$access_token = $dataToken["access_token"];
}
Якщо ви зберігали дані попереднього запиту БД, пропишіть отримання їх з БД (59-61 рядка).
Переходимо до інтеграції
Не наводитиму приклад html форми, потрібно обробити форму і передати в amo.php необхідні дані. Відкриваємо amo.php і додаємо:
require_once 'access.php';
$name = 'Имя клиента';
$phone = '+380123456789';
$email = 'email@gmail.com';
$target = 'Цель';
$company = 'Название компании';
$custom_field_id = 454021;
$custom_field_value = 'тест';
$ip = '1.2.3.4';
$domain = 'site.com';
$price = 0;
$pipeline_id = 5059931;
$user_amo = 0;
$utm_source = '';
$utm_content = '';
$utm_medium = '';
$utm_campaign = '';
$utm_term = '';
$utm_referrer = '';
$data = [
[
"name" => $phone,
"price" => $price,
"responsible_user_id" => $user_amo,
"pipeline_id" => $pipeline_id,
"_embedded" => [
"metadata" => [
"category" => "forms",
"form_id" => 1,
"form_name" => "Форма на сайте",
"form_page" => $target,
"form_sent_at" => strtotime(date("Y-m-d H:i:s")),
"ip" => $ip,
"referer" => $domain
],
"contacts" => [
[
"first_name" => $name,
"custom_fields_values" => [
[
"field_code" => "EMAIL",
"values" => [
[
"enum_code" => "WORK",
"value" => $email
]
]
],
[
"field_code" => "PHONE",
"values" => [
[
"enum_code" => "WORK",
"value" => $phone
]
]
],
[
"field_id" => $custom_field_id,
"values" => [
[
"value" => $custom_field_value
]
]
]
]
]
],
"companies" => [
[
"name" => $company
]
]
],
"custom_fields_values" => [
[
"field_code" => 'UTM_SOURCE',
"values" => [
[
"value" => $utm_source
]
]
],
[
"field_code" => 'UTM_CONTENT',
"values" => [
[
"value" => $utm_content
]
]
],
[
"field_code" => 'UTM_MEDIUM',
"values" => [
[
"value" => $utm_medium
]
]
],
[
"field_code" => 'UTM_CAMPAIGN',
"values" => [
[
"value" => $utm_campaign
]
]
],
[
"field_code" => 'UTM_TERM',
"values" => [
[
"value" => $utm_term
]
]
],
[
"field_code" => 'UTM_REFERRER',
"values" => [
[
"value" => $utm_referrer
]
]
],
],
]
];
$method = "/api/v4/leads/complex";
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token,
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'amoCRM-API-client/1.0');
curl_setopt($curl, CURLOPT_URL, "https://$subdomain.amocrm.ru".$method);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_COOKIEFILE, 'amo/cookie.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, 'amo/cookie.txt');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$out = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$code = (int) $code;
$errors = [
301 => 'Moved permanently.',
400 => 'Wrong structure of the array of transmitted data, or invalid identifiers of custom fields.',
401 => 'Not Authorized. There is no account information on the server. You need to make a request to another server on the transmitted IP.',
403 => 'The account is blocked, for repeatedly exceeding the number of requests per second.',
404 => 'Not found.',
500 => 'Internal server error.',
502 => 'Bad gateway.',
503 => 'Service unavailable.'
];
if ($code < 200 || $code > 204) die( "Error $code. " . (isset($errors[$code]) ? $errors[$code] : 'Undefined error') );
$Response = json_decode($out, true);
$Response = $Response['_embedded']['items'];
$output = 'ID добавленных элементов списков:' . PHP_EOL;
foreach ($Response as $v)
if (is_array($v))
$output .= $v['id'] . PHP_EOL;
return $output;
На самому початку ми маємо список змінних, куди необхідно передати дані з форми, наприклад: $name = $_POST[‘name’];
У $pipeline_id необхідно записати id воронки, його можна отримати з url crm:
Відкриваємо розділ “Угоди”, беремо id воронки, що відкрилася (число в кінці url), або перемикаємо іншу.
До $user_amo повернемося трохи згодом. Заповнюємо решту змінних.
Масив $data заповніть інформацією на свій розсуд, згідно з документацією.
Отримання id полів
Отримання ідентифікаторів полів, користувачів та решти реалізовано через GET запити. Докладніше можна ознайомитись у документації, а для наших цілей я підготував окремий файл, потрібні ці дані. Відкриваємо файл get.php і додаємо до нього:
require_once 'config.php';
function printLink($method, $title, $subdomain) {
echo ' ';
echo "$title";
echo ' ';
}
printLink('api/v4/leads/custom_fields', 'Список utm меток', $subdomain);
printLink('api/v4/users', 'Список пользователей', $subdomain);
printLink('api/v4/contacts/custom_fields', 'Список полей контакта', $subdomain);
Запустіть файл: https://site.com/amo/get.php
Ви побачите перелік посилань, перейшовши по яких отримуєте список id та інших параметрів полів для utm міток, користувачів, контактів. За аналогією можна переглянути інше. Повернемося до змінної $user_amo. Сюди потрібно вписати ID користувача, відповідального за угоду.
На цьому все, ліди будуть приходити в нерозібране, створювати контакт, підтягуватися в нього ім’я, телефон, а також кастомні поля, utm мітки, які були вказані в $data і назва компанії. Якщо вам потрібна допомога з інтеграцією CRM систем, напишіть нам 😉
