@ -13,12 +13,29 @@ abstract class FormHandler {
}
return ['success' => true, 'message' => 'Форма обработана'];
}
public function formatData($data) {
if (is_string($data)) {
parse_str($data, $parsedData); // Преобразуем строку в массив
$data = $parsedData;
}
$formattedMessage = "Данные формы:\n\n";
// Проходим по всем полям данных и добавляем их в сообщение
foreach ($data as $key => $value) {
$formattedMessage .= sprintf("%s: %s\n", $key, $value);
}
return $formattedMessage;
}
}
define('WEBHOOK_URL', 'https://b24-f0tsii.bitrix24.ru/rest/10/z5k521mjfkmk7pqj/');
$utm_data = get_utm_data();
class b24Handler extends FormHandler {
public function handle($data) {
// Логика отправки в Mailchimp
error_log("Отправка в b24: " . json_encode($data));
@ -27,9 +44,7 @@ class b24Handler extends FormHandler {
return parent::handle($data);
}
function b24_get_or_create_contact($phone, $name, $email, $utm, $userID = null, $isSubscribe) {
function b24_get_or_create_contact($phone, $name, $email, $utm, $userID = null, $isSubscribe) {
$contactId = null;
$error = null;
$foundContacts = [];
@ -187,18 +202,17 @@ function b24_get_or_create_contact($phone, $name, $email, $utm, $userID = null,
}
return ['contact_id' => $contactId, 'error' => $error];
}
}
// Вспомогательная функция для проверки значений
function valueExists($items, $value) {
// Вспомогательная функция для проверки значений
function valueExists($items, $value) {
foreach ($items as $item) {
if ($item['VALUE'] == $value) return true;
}
return false;
}
}
/* Функция POST-запроса к API Bitrix24 по адреcу Веб-хука */
function b24_request($method, $params = []) {
function b24_request($method, $params = []) {
$url = WEBHOOK_URL . $method; // ТУТ ВСТАВЛЯЕМ ХУК ОТ ИНТЕГРАТОРА
$curl = curl_init();
curl_setopt_array($curl, [
@ -219,9 +233,9 @@ function b24_request($method, $params = []) {
curl_close($curl);
return json_decode($response, true);
}
}
function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method, $form_title, $order_id) {
function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method, $form_title, $order_id) {
// Собираем UTM-метки из URL или POST данных
$utm_data = get_utm_data();
$utm_source = $utm_data['utm_source'] ?? '';
@ -238,15 +252,12 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
'CONTACT_ID' => $contactId,
'CATEGORY_ID' => $fName,
'SOURCE_ID' => "WEB",
// 'ASSIGNED_BY_ID' => "000",
'SOURCE_DESCRIPTION' => '',
// Добавляем UTM-метки
'UTM_SOURCE' => $utm_source,
'UTM_MEDIUM' => $utm_medium,
'UTM_CAMPAIGN' => $utm_campaign,
'UTM_CONTENT' => $utm_content,
'UTM_TERM' => $utm_term,
// Можно добавить дополнительные поля
'COMMENTS' => $msg,
'OPPORTUNITY' => $order_total,
]
@ -255,10 +266,14 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
if ($order_id){
$dealData['fields']['UF_CRM_1745741833259'] = $order_id;
}
error_log('DEAL DATA: ' . json_encode($dealData));
// Отправляем данные в Bitrix24
$newDealResponse = b24_request($method, $dealData);
error_log('DEAL RESP: ' . json_encode($newDealResponse));
// Обработка ответа
$error = null;
if (!empty($newDealResponse['error'])) {
@ -267,7 +282,6 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
$error = 'Ошибка создания сделки';
}
// Возвращаем результат
return [
'success' => empty($error),
'contact_id' => $contactId,
@ -280,30 +294,29 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
'term' => $utm_term
]
];
}
}
// Function to add lead (wraps b24_get_or_create_contact and b24_send_lead)
function b24_add_lead($phone, $name, $email, $msg, $utm, $url, $stage, $fName, $order_total = 0, $userID = null, $method = 'crm.deal.add', $form_title, $isSubscribe = false, $order_id = '') {
$contact = $this->b24_get_or_create_contact($phone, $name, $email, $utm, $userID, $isSubscribe);
function b24_add_lead($phone, $name, $email, $msg, $utm, $url, $stage, $fName, $order_total=0, $userID=null, $method = 'crm.deal.add', $form_title, $isSubscribe=false, $order_id=''){
$contact = b24_get_or_create_contact($phone, $name, $email, $utm, $userID, $isSubscribe);
if (!empty($contact['contact_id'])){
if (!empty($contact['contact_id'])) {
$contactId = $contact['contact_id'];
}
else{
} else {
return ['error' => $contact['error']];
}
$msg = $msg . '
Отправлено со страницы: ' . $url;
b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method, $form_title, $order_id);
$msg = $msg . "\nОтправлено со страницы: " . $url;
return $this-> b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method, $form_title, $order_id);
}
// Function to update contact based on userID
function b24_update_contact_by_user_id($userID, $newData) {
if (empty($userID)) {
return ['success' => false, 'error' => 'Не указан ID пользователя'];
}
// Получаем текущие данные пользователя
$user = get_user_by('ID', $userID);
if (!$user) {
return ['success' => false, 'error' => 'Пользователь не найден'];
@ -326,12 +339,12 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
$contactId = $contact['ID'];
$updateFields = [];
// Обновляем имя, если оно изменилось
// Update name if changed
if (isset($newData['name']) & & $newData['name'] !== $contact['NAME']) {
$updateFields['NAME'] = $newData['name'];
}
// Обновляем телефон, если он изменился
// Update phone if changed
if (isset($newData['phone'])) {
$phoneExists = false;
foreach ($contact['PHONE'] ?? [] as $phoneItem) {
@ -345,7 +358,7 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
}
}
// Обновляем email, если он изменился
// Update email if changed
if (isset($newData['email'])) {
$emailExists = false;
foreach ($contact['EMAIL'] ?? [] as $emailItem) {
@ -359,7 +372,7 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
}
}
// Обновляем Telegram, если он изменился
// Update Telegram if changed
if (!empty($tg_username) & & !imExists($contact['IM'] ?? [], $tg_username)) {
$updateFields['IM'][] = [
'VALUE' => $tg_username,
@ -372,7 +385,7 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
return ['success' => true, 'message' => 'Нет изменений для обновления'];
}
// Отправляем обновление в Bitrix24
// Send update request
$updateResponse = b24_request('crm.contact.update', [
'id' => $contactId,
'fields' => $updateFields
@ -384,7 +397,6 @@ function b24_send_lead($contactId, $msg, $stage, $fName, $order_total, $method,
return ['success' => true, 'contact_id' => $contactId];
}
}
class zohoHandler extends FormHandler {
@ -396,6 +408,62 @@ class zohoHandler extends FormHandler {
}
}
class tgHandler extends FormHandler {
public function handle($data) {
global $site_env;
if ($site_env->site_region == 'ru'){
$botToken = '7689949404:AAHLTKmopffoNkndHJt-rOmAIZ7Hb6aKf80';
$chatId = '-1002591296904';
}
else if ($site_env->site_region == 'ae'){
$botToken = '7589204557:AAHh2qa5mUwRBq4fUyjQzqARpk4jDfUu5Yc';
$chatId = '-1002537433508';
}
// Форматируем данные для отправки в Telegram
$message = strip_tags($this->formatData($data));
// Отправляем сообщение в Telegram
$this->sendToTelegram($botToken, $chatId, $message);
// Вызываем следующий обработчик в цепочке
return parent::handle($data);
}
// Функция для отправки данных в Telegram
private function sendToTelegram($botToken, $chatId, $message) {
$url = "https://api.telegram.org/bot$botToken/sendMessage";
$maxLength = 4096;
// Разбиваем сообщение на части, если оно длиннее лимита
$messages = str_split($message, $maxLength);
foreach ($messages as $msgPart) {
$data = [
'chat_id' => $chatId,
'text' => $msgPart,
'parse_mode' => 'HTML',
];
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($data),
],
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
// Логируем HTTP-код и тело ответа
$httpCode = isset($http_response_header[0]) ? $http_response_header[0] : 'No HTTP response';
}
}
}
class emailHandler extends FormHandler {
public function handle($data) {
@ -412,21 +480,6 @@ class emailHandler extends FormHandler {
// Вызываем следующий обработчик в цепочке
return parent::handle($data);
}
private function formatData($data) {
if (is_string($data)) {
parse_str($data, $parsedData); // Преобразуем строку в массив
$data = $parsedData;
}
$formattedMessage = "Данные формы:\n\n";
// Проходим по всем полям данных и добавляем их в сообщение
foreach ($data as $key => $value) {
$formattedMessage .= sprintf("%s: %s\n", $key, $value);
}
return $formattedMessage;
}
}
class FormHandlerFactory {
@ -438,14 +491,12 @@ class FormHandlerFactory {
if (in_array('zoho', $enabledHandlers)) {
$handler = new zohoHandler($handler);
}
// if (in_array('mindbox ', $enabledHandlers)) {
// $handler = new mindbox Handler($handler);
// }
if (in_array('tg ', $enabledHandlers)) {
$handler = new tg Handler($handler);
}
if (in_array('b24', $enabledHandlers)) {
$handler = new b24Handler($handler);
}
return $handler ?: new DefaultHandler();
}
}
@ -453,46 +504,46 @@ class FormHandlerFactory {
// Пример обработки обновления профиля пользователя
add_action('profile_update', 'handle_profile_update', 10, 2);
// // Пример обработки обновления профиля пользователя
// add_action('profile_update', 'handle_profile_update', 10, 2);
function handle_profile_update($userID, $old_user_data) {
$user = get_user_by('ID', $userID);
// function handle_profile_update($userID, $old_user_data) {
// $user = get_user_by('ID', $userID);
$email = $user->user_email;
$phone = get_user_meta($userID, 'billing_phone', true);
$first_name = get_user_meta($userID, 'first_name', true);
$last_name = get_user_meta($userID, 'last_name', true);
$name = trim($first_name . ' ' . $last_name);
// $email = $user->user_email;
// $phone = get_user_meta($userID, 'billing_phone', true);
// $first_name = get_user_meta($userID, 'first_name', true);
// $last_name = get_user_meta($userID, 'last_name', true);
// $name = trim($first_name . ' ' . $last_name);
$newData = [
'name' => $name,
'email' => $email,
'phone' => $phone,
];
// $newData = [
// 'name' => $name,
// 'email' => $email,
// 'phone' => $phone,
// ];
$result = b24_update_contact_by_user_id($userID, $newData);
// $result = b24_update_contact_by_user_id($userID, $newData);
if (!$result['success']) {
error_log('Ошибка обновления контакта в Bitrix24: ' . $result['error']);
}
}
// if (!$result['success']) {
// error_log('Ошибка обновления контакта в Bitrix24: ' . $result['error']);
// }
// }
add_action('woocommerce_thankyou', 'add_b24_tracking_script', 10, 1);
// add_action('woocommerce_thankyou', 'add_b24_tracking_script', 10, 1);
function add_b24_tracking_script($order_id) {
if (!$order_id) return;
// function add_b24_tracking_script($order_id) {
// if (!$order_id) return;
$order = wc_get_order($order_id);
// $order = wc_get_order($order_id);
echo '< script >
(window.b24order = window.b24order || []).push({
id: "' . $order_id . '",
sum: "' . $order->get_total() . '"
});
< / script > ';
}
// echo '< script >
// (window.b24order = window.b24order || []).push({
// id: "' . $order_id . '",
// sum: "' . $order->get_total() . '"
// });
// < / script > ';
// }
function get_utm_data() {
$utm_data = [];