Skip to content

Instantly share code, notes, and snippets.

@nkarpeev
Last active February 28, 2018 07:51
Show Gist options
  • Save nkarpeev/51f033db7b021ad69e80e968a51ac579 to your computer and use it in GitHub Desktop.
Save nkarpeev/51f033db7b021ad69e80e968a51ac579 to your computer and use it in GitHub Desktop.
amocrm create lead and add contact
<?php
class Base {
public $subdomain = 'test';
public $responsible_user_id = 7292136; //id ответственного по сделке, контакту, компании
public $lead_name = 'тест Заявка с сайта'; //Название добавляемой сделки
public $lead_status_id = '11331793'; //id этапа продаж, куда помещать сделку
public $contact_name; //Название добавляемого контакта
public $contact_phone; //Телефон контакта
public $contact_email; //Емейл контакта
public $subject_message;
public function __construct() {
$this->contact_name = $_POST['name'];
$this->contact_phone = $_POST['phone'];
$this->contact_email = $_POST['email'];
$this->subject_message = $_POST['type'];
/*
$this->contact_name = 'name';
$this->contact_phone = 'phone';
$this->contact_email = 'email';
$this->subject_message = 'type';
*/
# An array of parameters that must be passed by the POST method to the API
$user = array(
'USER_LOGIN'=>'test@test.ru', # Your login (email)
'USER_HASH'=>'your hash' # Hash to access the API (see profile)
);
$link = 'https://'.$this->subdomain.'.amocrm.com/private/api/auth.php?type=json';
$curl = curl_init(); # Save the cURL session handle
# Set the necessary options for cURL session
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($user));
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out = curl_exec($curl); # Initiate a request to the API and stores the response to variable
$code = curl_getinfo($curl,CURLINFO_HTTP_CODE); # Obtain the HTTP-server response code
curl_close($curl); # Close cURL session
$response = json_decode($out, true);
echo '<b>Авторизация:</b>';
echo '<pre>';
print_r($response);
echo '</pre>';
}
}
class Account extends Base{
public function getInfo() {
$link = 'https://'.$this->subdomain.'.amocrm.ru/private/api/v2/json/accounts/current'; #$subdomain уже объявляли выше
$curl = curl_init(); #Сохраняем дескриптор сеанса cURL
#Устанавливаем необходимые опции для сеанса cURL
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out = curl_exec($curl); #Инициируем запрос к API и сохраняем ответ в переменную
$code = curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
$response =json_decode($out,true);
$account = $response['response']['account'];
//echo '<pre>';
//print_r($account['custom_fields']);
//echo '</pre>';
//echo '<b>Данные аккаунта:</b>'; echo '<pre>'; print_r($Response); echo '</pre>';
//ПОЛУЧАЕМ СУЩЕСТВУЮЩИЕ ПОЛЯ
$amoAllFields = $account['custom_fields']; //Все поля
$amoConactsFields = $account['custom_fields']['contacts']; //Поля контактов
//echo '<b>Поля из амо:</b>'; echo '<pre>'; print_r($amoConactsFields); echo '</pre>';
//ФОРМИРУЕМ МАССИВ С ЗАПОЛНЕННЫМИ ПОЛЯМИ КОНТАКТА
//Стандартные поля амо:
$sFields = array_flip(array(
'PHONE', //Телефон. Варианты: WORK, WORKDD, MOB, FAX, HOME, OTHER
'EMAIL' //Email. Варианты: WORK, PRIV, OTHER
)
);
foreach($amoConactsFields as $afield) {
if(isset($sFields[$afield['code']])) {
$sFields[$afield['code']] = $afield['id'];
}
}
//set id by custom field
$sFields['SUBJECT'] = 449769;
return $sFields;
}
}
class Lead extends Base{
public function create() {
$leads['request']['leads']['add'] = array(
array(
'name' => $this->lead_name,
'status_id' => $this->lead_status_id, //id статуса
'responsible_user_id' => $this->responsible_user_id, //id ответственного по сделке
//'date_create'=>1298904164, //optional
//'price'=>300000,
//'tags' => 'Important, USA', #Теги
//'custom_fields'=>array()
)
);
# Create a link for request
$link='https://'.$this->subdomain.'.amocrm.com/private/api/v2/json/leads/set';
$curl=curl_init(); # Save the cURL session handle
# Set the necessary options for cURL session
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($leads));
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out=curl_exec($curl); # Initiate a request to the API and stores the response to variable
$code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
$response=json_decode($out,true);
if(is_array($response['response']['leads']['add']))
foreach($response['response']['leads']['add'] as $lead) {
$lead_id = $lead["id"]; //id новой сделки
};
return $lead_id;
}
}
class Contact extends Base{
public function create() {
$account = new Account();
$lead = new Lead();
$sFields = $account->getInfo();
$lead_id = $lead->create();
$contact = array(
'name' => $this->contact_name,
'linked_leads_id' => array($lead_id), //id сделки
'responsible_user_id' => $this->responsible_user_id, //id ответственного
'custom_fields'=>array(
array(
'id' => $sFields['PHONE'],
'values' => array(
array(
'value' => $this->contact_phone,
'enum' => 'MOB'
)
)
),
array(
'id' => $sFields['EMAIL'],
'values' => array(
array(
'value' => $this->contact_email,
'enum' => 'WORK'
)
)
),
array(
'id' => $sFields['SUBJECT'],
'values' => array(
array(
'value' => $this->subject_message
)
)
)
)
);
echo 'var contact:' . '<br>';
print_r($contact);
$set['request']['contacts']['add'][]=$contact;
#Формируем ссылку для запроса
$link='https://'.$this->subdomain.'.amocrm.ru/private/api/v2/json/contacts/set';
$curl=curl_init(); #Сохраняем дескриптор сеанса cURL
#Устанавливаем необходимые опции для сеанса cURL
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($set));
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_COOKIEFILE,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_COOKIEJAR,dirname(__FILE__).'/cookie.txt'); #PHP>5.3.6 dirname(__FILE__) -> __DIR__
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out=curl_exec($curl); #Инициируем запрос к API и сохраняем ответ в переменную
$code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
//CheckCurlResponse($code);
$response=json_decode($out,true);
echo 'add Contact' . '<br>';
print_r($response);
}
}
$contact = new Contact();
$contact->create();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment