Skip to content

Работа с чатами #99

@TLTHades

Description

@TLTHades

Подскажите пожалуйста, 3 года назад заказывал хук для публикации уведомлений при переходе на статус воронки. Стандартный SalesBot постил во все чаты подряд и в него нельзя было подставлять название сделки. Поэтому мы заказали как доработку и получили хук, который активируется во воронке на этапах сделки. В хуке функция постинга реализована с помощью

$link='https://amojo.amocrm.ru/chats/'.$amojo_id.'/'.$data_ids['chat_id'].'/messages';
...
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($messages));
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json', 'X-Auth-Token: '.$token));

Токен можно получить через консоль с помощью
localStorage.getItem("amojo_token")
В скрипте мы его получали через
$link='https://'.$subdomain.'.amocrm.ru/ajax/v1/chats/session';
но этот способ перестал работать с 21 февраля и теперь мы можем получить amojo_token только вручную.

Что бы решить проблему попробовал переписать весь хук на основе библиотеки, создал интеграцию в CRM, все запросы переписал с помощью инструкции "Пример по шагам", все необходимые данные от CRM получить удалось, но вот отправить сообщение по прежнему не удаётся.

function sendMessage($ids, $data_ids, $contactname='Клиент', $token){
	$messages_array = array(
		'0',
		'1',
		'3',
		'4'
	);
  file_put_contents('log.txt', "GET: ".json_encode($_GET)."\n", FILE_APPEND);
	$messages = array(
		'text' => $messages_array[$_GET['id']],
		'recipient_id'=> $data_ids[0]->amojo_id,
		'crm_contact_id'=> $data_ids[0]->id, // User ID
		'crm_account_id'=> 16323070, // Telegram Bot ID
	);
  file_put_contents('log.txt', "Сообщение: ".json_encode($messages)."\n", FILE_APPEND);
  $amojo_id = '4eb9569a-41b0-4624-86bb-0ec99cfe317c';
	$link='https://amojo.amocrm.ru/chats/'.$amojo_id.'/'.$data_ids['chat_id'].'/messages';
  $headers = [
    'Authorization: Bearer ' . $token
  ];
	$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_CUSTOMREQUEST,'POST');
	curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($messages));
  curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
  curl_setopt($curl,CURLOPT_HEADER, false);
  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 = [
    400 => 'Bad request',
    401 => 'Unauthorized',
    403 => 'Forbidden',
    404 => 'Not found',
    500 => 'Internal server error',
    502 => 'Bad gateway',
    503 => 'Service unavailable',
  ];
  try
  {
    if ($code < 200 && $code > 204) {
      throw new Exception(isset($errors[$code]) ? $errors[$code] : 'Undefined error', $code);
      file_put_contents('log.txt', "code: ".$code."\n", FILE_APPEND);
    }
  }
  catch(\Exception $e)
  {
    die('Ошибка: ' . $e->getMessage() . PHP_EOL . 'Код ошибки: ' . $e->getCode());
    file_put_contents('log.txt', "Ошибка: ".$e."\n", FILE_APPEND);
  }
	$Response=json_decode($out,true);
  file_put_contents('log.txt', "Response: ".json_encode($Response)."\n", FILE_APPEND);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions