L
L
lucsieus2021-03-03 09:40:07
PHP
lucsieus, 2021-03-03 09:40:07

How to integrate telegram bot with Bitrix24 via incoming webhook?

There is a function to display the basket, the code is not my ready-made bot. We were given the task of integrating this bot with Bitrix24 via an incoming webhook (To form a new deal through the bot). Got the webhook figured out, but still difficult with OOP. Help, just give steps on how to implement this so that a webhook is executed through this function.

//function

private  function drawOrder($user_id = 0, $begin = 0)
    {
        if (!$user_id) {
            $dop_user_id = "";
            $dop_user_arr = [];
        } else {
            $dop_user_id = " WHERE user_id = :user_id ";
            $dop_user_arr = ['user_id' => $user_id];
        }
        // достаем из корзины товар
        $order = $this->pdo->prepare("SELECT * FROM bot_shop_order " . $dop_user_id . " ORDER BY id DESC LIMIT " . $begin . ", 1");
        $order->execute($dop_user_arr);
        if ($order->rowCount() > 0) {
            $orderRaw = $order->fetch();
            // считаем общую сумму
            $orderProduct = $this->pdo->prepare("SELECT * FROM bot_shop_order_product WHERE parent_id = :parent_id");
            $orderProduct->execute(['parent_id' => $orderRaw['id']]);
            // итоговую сумму определяем как ноль
            $total = 0;
            $goods = "";
            // перебираем массив
            while ($row = $orderProduct->fetch()) {
                $model_product = $this->pdo->prepare("SELECT * FROM bot_shop_product WHERE id = :id");
                $model_product->execute(['id' => $row['product_id']]);
                $product = $model_product->fetch();
                // увеличиваем сумму
                $sum = $product['price'] * $row['product_count'];
                $total += $sum;
                // складываем товары
                $goods .= " - " . $product['name'] . " = " . $row['product_count'] . " x " . $product['price'] . " тг. \n";
            }
            // готовим данные
            $text = "<b>Заказ: </b> № ".$orderRaw['id']." \n<b>Дата: </b> ".$orderRaw['date']."\n\n";
            $text .= "<b>Телефон:</b> " . $orderRaw['phone'] . "\n";
            $text .= "<b>Адрес/Самовывоз:</b> " . $orderRaw['adress'] . "\n";
            $text .= "<b>Доп. комментарий:</b> " . $orderRaw['comment'] . "\n";
            $text .= "<b>\nВаш заказ :</b> \n" . $goods;
            $text .= "\n<b>Сумма заказа:</b> " . $total . " тг\n";
            if (!$user_id) {
                $user_data = $this->pdo->prepare("SELECT * FROM bot_shop_profile WHERE user_id = :user_id");
                $user_data->execute(['user_id' => $orderRaw['user_id']]);
                $user_data_raw = $user_data->fetch();
                $text .= "<b>Пользователь:</b> " . trim($user_data_raw['first_name'] . " " . $user_data_raw['last_name']) . "\n";
            }
            if ($orderRaw['type_pay']) {
                $text.= "\n\n<b>✅ Ваш заказ принят.</b>\n\n<em>Благодарим вас за заказ.В ближайшее время с вами свяжутся наши операторы. Желаем вам приятного аппетита!</em>\n\n<b>Чтобы оформить новый заказ нажмите на\n\n\n                               /start </b>";
            }
            if (!$orderRaw['status']) {
                if (!$orderRaw['type_pay'] && $user_id) {
                    // готовим кнопку для перехода в Яндекс. Деньги
                    $url = $this->getUrl($total, $user_id, $orderRaw['id']);
                    $buttons[][] = $this->buildInlineKeyBoardButton("Отменить заказ ❌️", "showCatalog");
                }
            } else {
                // если заказ оплачен то уведомляем
                $text .= "\n<b>Заказ оплачен</b>\n";
            }
        // возвращаем данные
        return [
            'text' => $text,
            'buttons' => $buttons,
        ];
    }


//Incoming webhook (Bitrix24) in this case, it takes data from the form.
<?php
  $name 		    = isset($_POST['name']) ? $_POST['name'] : '';
  $phone 		    = isset($_POST['phone']) ? $_POST['phone'] : '';
  $description      = isset($_POST['description']) ? $_POST['description'] : '';
  $address 			= isset($_POST['address']) ? $_POST['address'] : '';
  $opportunity		= isset($_POST['opportunity']) ? $_POST['opportunity'] : '';
  $dealName		= isset($_POST['dealName']) ? $_POST['dealName'] : '';
  $dealCom		= isset($_POST['dealCom']) ? $_POST['dealCom'] : '';

  $contact = array(
    'NAME' => $name,
    'PHONE' => $phone,
    'DESCRIPTION' => $description,
    'ADDRESS' => $address,
    'OPPORTUNITY' => $opportunity,
    'UF_CRM_1611636092550' => $dealName,
    'UF_CRM_1611636752001' => $dealCom,
    'CONTACT_ID' => 0,
    'DEAL_ID' => 0,
  );

  $contact['CONTACT_ID'] = addContact($contact);
  $contact['DEAL_ID'] = addDeal($contact);
  if($contact['DESCRIPTION'] != '') addMessage($contact);
  echo json_encode($contact['DEAL_ID'], JSON_UNESCAPED_UNICODE);

  function sendDataToBitrix($method, $data) {
    $queryUrl = 'https://letscall.bitrix24.ru/rest/70/rshtbubb4gvbze9q/'.$method ;
    $queryData = http_build_query($data);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_SSL_VERIFYPEER => 0,
      CURLOPT_POST => 1,
      CURLOPT_HEADER => 0,
      CURLOPT_RETURNTRANSFER => 1,
      CURLOPT_URL => $queryUrl,
      CURLOPT_POSTFIELDS => $queryData,
    ));
    $result = curl_exec($curl);
    curl_close($curl);
    return json_decode($result, 1);
  }

  function addDeal($contact) {
    $dealData = sendDataToBitrix('crm.deal.add', [
      'fields' => [
        'TITLE' => 'Заявка с сайта',
        'OPPORTUNITY' => $contact['OPPORTUNITY'],
        'UF_CRM_1611636092550' => $contact['UF_CRM_1611636092550'],
        'UF_CRM_1611636752001' => $contact['UF_CRM_1611636752001'],
        'STAGE_ID' => 'NEW',
        'CONTACT_ID' => $contact['CONTACT_ID'],
      ], 'params' => [
        'REGISTER_SONET_EVENT' => 'Y'
      ]
    ]);

    return $dealData['result'];
  }

  function addContact($contact) {
    $check = checkContact($contact);
    if($check['total'] != 0) return $check['result'][0]['ID'];
    $contactData = sendDataToBitrix('crm.contact.add', [
      'fields' => [
        'NAME' => $contact['NAME'],
        'ADDRESS' => $contact['ADDRESS'],
        'PHONE' => ,
        'TYPE_ID' => 'CLIENT',
      ], 'params' => [
        'REGISTER_SONET_EVENT' => 'Y'
      ]
    ]);

    return $contactData['result'];
  }

  function addMessage($contact) {
    $messageData = sendDataToBitrix('crm.livefeedmessage.add', [
      'fields' => [
        'MESSAGE' => $contact['DESCRIPTION'],
        'POST_TITLE' => 'Сообщение с формы сайта',
        'ENTITYTYPEID' => 2,
        'ENTITYID' => $contact['DEAL_ID'],
      ], 'params' => [
        'REGISTER_SONET_EVENT' => 'Y'
      ]
    ]);
    return $messageData['result'];
  }

  function checkContact($contact){
    $list = sendDataToBitrix('crm.contact.list', [
      'filter' => [ 'PHONE' =>  $contact['PHONE']],
      'select' => [ 'ID'],
    ]);
    return $list;
  }
 ?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lucsieus, 2021-03-04
@lucsieus

Крч нашел решение, входящий вебхук работает. Только ошибку сделал с ООП, а именно $this.

Роман, 2021-03-03
@Ramapriya

используйте для работы с вебхуком SDK CRest

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question