amoCRM integration with API site

AmoCRM is one of the most popular CRMs, while its API is one of the strangest, in my subjective opinion. It was necessary to transfer form data from the site to crm. I do not want to use CRM Forms instead of my design ones. It would be great to open an article in Google, substitute the key and not worry too much, but surprisingly I did not find a single article with up-to-date information, somewhere the api version is no longer relevant, somewhere instead of using the default contact fields, custom ones are created. In general, I decided to share my solution, for those who find it difficult / too lazy to delve into their API.

In this article, I will be creating a deal in Unparsed, a contact, and a company.

Creating integration files

Create a folder amo, for example in the root of the site.

Files inside:
amo.php
access.php
config.php
get.php
cookies.txt
tokens.txt
The names can be arbitrary.

Getting the keys

Open AmoCRM, go to Settings > Integrations.

Click “+ Create Integration” and create an external integration.

Provide a link to our amo.php file, check the box for granting access and enter an arbitrary name and description:

PS Before saving, read this section to the end

We will have 3 keys and 20 minutes to do the following:

We open config.php and put them in there:

<?php
$subdomain     = ''; // поддомен AmoCRM
$client_secret=""; // Секретный ключ
$client_id     = ''; // ID интеграции
$code=""; // Код авторизации
$token_file="tokens.txt";
$redirect_uri  = 'https://site.com/amo/amo.php';

We take the AmoCRM subdomain from the url of our CRM
V $redirect_uri don’t forget to change your website domain

Then we go to the file auth.php and paste the following:

<?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);

Here we send a request to AmoCRM to receive tokens. Tokens are saved to a file (45-57 lines)you can store them in the database.

Run the file, https://site.com/amo/auth.php
As a result, data should appear in the tokens.txt file.

Token refresh

The access token is temporary and needs to be updated.

Opening the file access.php and add the following:

<?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"];
}

If you saved the data of the previous request in the database, register getting them from the database (59-61 lines).

Moving on to integration

I will not give an example of an html form, you need to process the form and pass it to amo.php required data. Open amo.php and add:

<?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;

At the very beginning, we have a list of variables where we need to pass data from the form, for example: $name = $_POST['name'];

In $pipeline_id you need to write funnel idit can be obtained from url crm:
Open the “Deals” section, take the id of the opened funnel (number at the end of url)or switch to another.

We will return to $user_amo a little later. Fill in the rest of the variables.

Fill in the $data array with information of your choice, according to documentation.

Getting field id

Obtaining field identifiers, users, and everything else is implemented through GET requests. More details can be found in the documentation, and for our purposes I have prepared a separate file, this data is needed. Opening the file get.php and add to it:

<?php
require_once 'config.php';

function printLink($method, $title, $subdomain) {
    echo '<br>';
    echo "<a href="https://$subdomain.amocrm.ru/$method" target="_blank">$title</a>";
    echo '<br>';
}

printLink('api/v4/leads/custom_fields', 'Список utm меток', $subdomain);
printLink('api/v4/users', 'Список пользователей', $subdomain);
printLink('api/v4/contacts/custom_fields', 'Список полей контакта', $subdomain);

echo '<br>';
echo "<a href="https://www.amocrm.ru/developers/content/crm_platform/custom-fields" target="_blank">Документация</a>";
echo '<br>';

Run the file: https://site.com/amo/get.php
You will see a list of links, by clicking on which you get a list of id and other field parameters for utm tags, users, contacts. By analogy, you can view the rest.
Let’s get back to the $user_amo variable. Here you need to enter the id of the user responsible for the transaction.

Conclusion

That’s all, if everything is done correctly, leads will come to the unparsed, a contact will be created, the name, phone number, as well as custom fields, utm tags that were specified in $data and the company name will be pulled into it.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *