Andrei | b24 integration fixex

pull/36/head
parent 2e4273165f
commit 3d891c588c
  1. 88
      wp-content/themes/cosmopet/modules/forms/module-ajax-controller.php
  2. 118
      wp-content/themes/cosmopet/modules/forms/module-controller.php
  3. 4
      wp-content/themes/cosmopet/templates/forms/author-form.twig
  4. 2
      wp-content/themes/cosmopet/templates/shop/cart-bottom.twig
  5. 2
      wp-content/themes/cosmopet/woocommerce/checkout/form-checkout.php

@ -18,6 +18,51 @@ function get_current_user_data(){
); );
} }
add_action('wp_ajax_blogauth_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => $formData['phone'],
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Предложить статью или стать автором',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_nopriv_blogauth_form', function() {
$enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data();
$formData = json_decode($_POST['formData']);
$crmData = array(
'phone' => null,
'name' => $formData['name'],
'email' => $formData['email'],
'msg' => $formData['msg'],
'url' => $formData['url'],
'stage' => 'C4:NEW',
'fName' => 4,
'order_total' => 0,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Предложить статью или стать автором',
'is_subscribe' => false,
'order_id' => '',
);
process_form($enabledHandlers, $crmData);
});
add_action('wp_ajax_contact_form', function() { add_action('wp_ajax_contact_form', function() {
$enabledHandlers = ['b24', 'email', 'tg']; $enabledHandlers = ['b24', 'email', 'tg'];
$user_data = get_current_user_data(); $user_data = get_current_user_data();
@ -162,8 +207,6 @@ function process_form($enabledHandlers, $crmData = array()) {
wp_send_json($response); wp_send_json($response);
} }
// Отправляем данные в Bitrix24 при создании заказа // Отправляем данные в Bitrix24 при создании заказа
add_action('woocommerce_checkout_order_created', 'send_order_to_bitrix_on_create', 10, 1); add_action('woocommerce_checkout_order_created', 'send_order_to_bitrix_on_create', 10, 1);
@ -250,17 +293,50 @@ function send_order_data($order_id) {
// Добавляем товары (префикс PRODUCT_1_, PRODUCT_2_ и т.д.) // Добавляем товары (префикс PRODUCT_1_, PRODUCT_2_ и т.д.)
$product_index = 1; $product_index = 1;
$product_summary = "🛒 Состав заказа:\n\n";
foreach ($order->get_items() as $item) { foreach ($order->get_items() as $item) {
$product = $item->get_product(); $product = $item->get_product();
$formData["PRODUCT_{$product_index}_NAME"] = $product->get_name(); $formData["PRODUCT_{$product_index}_NAME"] = $product->get_name();
$formData["PRODUCT_{$product_index}_QTY"] = $item->get_quantity(); $formData["PRODUCT_{$product_index}_QTY"] = $item->get_quantity();
$formData["PRODUCT_{$product_index}_PRICE"] = $item->get_total(); $formData["PRODUCT_{$product_index}_PRICE"] = $item->get_total();
$formData["PRODUCT_{$product_index}_SKU"] = $product->get_sku(); $formData["PRODUCT_{$product_index}_SKU"] = $product->get_sku();
// Добавляем в текстовую сводку
$product_summary .= "{$product_index}) {$name}\n";
$product_summary .= " Кол-во: {$qty}\n";
$product_summary .= " Сумма: {$total}\n";
if ($sku) {
$product_summary .= " Артикул: {$sku}\n";
}
$product_summary .= "\n";
$product_index++; $product_index++;
} }
$handler = FormHandlerFactory::getHandler(['tg']); $message = "📋 Данные формы:\n\n";
$response = $handler->handle($formData, array()); foreach ($formData as $key => $value) {
if (is_array($value)) {
$value = implode(', ', $value); // на случай, если в значении массив
}
$message .= sprintf("%s: %s\n", $key, $value);
}
$crmData = array(
'phone' => $customer_phone,
'name' => $customer_name,
'email' => $customer_email,
'msg' => $product_summary,
'url' => null,
'stage' => 'C2:UC_ZMY1QV',
'fName' => 2,
'order_total' => $order_total,
'user_id' => $user_data['user_id'],
'method' => 'crm.deal.add',
'form_title' => 'Заказ на сайте',
'is_subscribe' => false,
'order_id' => $order_id,
);
$handler = FormHandlerFactory::getHandler(['tg', 'b24']);
$response = $handler->handle($formData, $crmData);
} }
add_action('woocommerce_payment_complete', 'notify_order_paid', 10, 1); add_action('woocommerce_payment_complete', 'notify_order_paid', 10, 1);
@ -278,5 +354,9 @@ function notify_order_paid($order_id) {
$handler = FormHandlerFactory::getHandler(['tg']); $handler = FormHandlerFactory::getHandler(['tg']);
$handler->handle($formData, []); $handler->handle($formData, []);
$b24Handler = new b24Handler();
$b24Handler->b24_update_deal_stage_by_order_id($order_id);
} }
?> ?>

@ -52,9 +52,6 @@ class b24Handler extends FormHandler {
$crmData['is_subscribe'], $crmData['is_subscribe'],
$crmData['order_id'], $crmData['order_id'],
); );
error_log('----------CRM_DATA----------------');
error_log(json_encode($crmData));
error_log('----------CRM_DATA----------------');
// Вызываем следующий обработчик в цепочке // Вызываем следующий обработчик в цепочке
return parent::handle($data, $crmData); return parent::handle($data, $crmData);
} }
@ -78,7 +75,7 @@ class b24Handler extends FormHandler {
$searchFilters = []; $searchFilters = [];
if (!empty($userID)) { if (!empty($userID)) {
$searchFilters[] = ['UF_CRM_1744373080655' => $userID]; $searchFilters[] = ['UF_CRM_1751610129971' => $userID];
} }
if (!empty($phone)) $searchFilters[] = ['PHONE' => $phone]; if (!empty($phone)) $searchFilters[] = ['PHONE' => $phone];
@ -87,7 +84,7 @@ class b24Handler extends FormHandler {
foreach ($searchFilters as $filter) { foreach ($searchFilters as $filter) {
$response = $this->b24_request('crm.contact.list', [ $response = $this->b24_request('crm.contact.list', [
'filter' => $filter, 'filter' => $filter,
'select' => ['ID', 'NAME', 'PHONE', 'EMAIL', 'UF_CRM_1744373080655', 'IM'] 'select' => ['ID', 'NAME', 'PHONE', 'EMAIL', 'UF_CRM_1751610129971', 'IM']
]); ]);
if (!empty($response['result'])) { if (!empty($response['result'])) {
@ -103,7 +100,7 @@ class b24Handler extends FormHandler {
foreach ($foundContacts as $contact) { foreach ($foundContacts as $contact) {
$matches = 0; $matches = 0;
if (!empty($userID) && isset($contact['UF_CRM_1744373080655']) && $contact['UF_CRM_1744373080655'] == $userID) { if (!empty($userID) && isset($contact['UF_CRM_1751610129971']) && $contact['UF_CRM_1751610129971'] == $userID) {
$matches += 3; $matches += 3;
} }
@ -145,8 +142,8 @@ class b24Handler extends FormHandler {
$updateFields['UTM_SOURCE'] = $utm; $updateFields['UTM_SOURCE'] = $utm;
} }
if (!empty($userID) && (!isset($bestMatch['UF_CRM_1744373080655']) || $bestMatch['UF_CRM_1744373080655'] != $userID)) { if (!empty($userID) && (!isset($bestMatch['UF_CRM_1751610129971']) || $bestMatch['UF_CRM_1751610129971'] != $userID)) {
$updateFields['UF_CRM_1744373080655'] = $userID; $updateFields['UF_CRM_1751610129971'] = $userID;
} }
if ($isSubscribe) { if ($isSubscribe) {
@ -197,7 +194,7 @@ class b24Handler extends FormHandler {
$newContact['fields']['UTM_SOURCE'] = $utm_source; $newContact['fields']['UTM_SOURCE'] = $utm_source;
} }
if (!empty($userID)) { if (!empty($userID)) {
$newContact['fields']['UF_CRM_1744373080655'] = $userID; $newContact['fields']['UF_CRM_1751610129971'] = $userID;
} }
if ($isSubscribe) { if ($isSubscribe) {
$newContact['fields']['UF_CRM_1744562461053'] = true; $newContact['fields']['UF_CRM_1744562461053'] = true;
@ -342,8 +339,8 @@ class b24Handler extends FormHandler {
// Ищем контакт по ID пользователя // Ищем контакт по ID пользователя
$response = $this->b24_request('crm.contact.list', [ $response = $this->b24_request('crm.contact.list', [
'filter' => ['UF_CRM_1744373080655' => $userID], 'filter' => ['UF_CRM_1751610129971' => $userID],
'select' => ['ID', 'NAME', 'PHONE', 'EMAIL', 'UF_CRM_1744373080655', 'IM', 'UF_CRM_1744562461053'] 'select' => ['ID', 'NAME', 'PHONE', 'EMAIL', 'UF_CRM_1751610129971', 'IM', 'UF_CRM_1744562461053']
]); ]);
if (empty($response['result'])) { if (empty($response['result'])) {
@ -412,6 +409,46 @@ class b24Handler extends FormHandler {
return ['success' => true, 'contact_id' => $contactId]; return ['success' => true, 'contact_id' => $contactId];
} }
function b24_update_deal_stage_by_order_id($order_id, $new_stage = 'C2:FINAL_INVOICE') {
if (empty($order_id)) {
return ['success' => false, 'error' => 'Не указан order_id'];
}
$b24 = new b24Handler();
// 1. Найдём сделку по полю UF_CRM_1745741833259
$searchResponse = $b24->b24_request('crm.deal.list', [
'filter' => ['UF_CRM_1745741833259' => $order_id],
'select' => ['ID', 'TITLE', 'STAGE_ID']
]);
if (!empty($searchResponse['error'])) {
return ['success' => false, 'error' => 'Ошибка поиска сделки: ' . $searchResponse['error']];
}
$deals = $searchResponse['result'] ?? [];
if (empty($deals)) {
return ['success' => false, 'error' => 'Сделка с таким order_id не найдена'];
}
$dealId = $deals[0]['ID'];
// 2. Обновим стадию сделки
$updateResponse = $b24->b24_request('crm.deal.update', [
'id' => $dealId,
'fields' => ['STAGE_ID' => $new_stage]
]);
if (!empty($updateResponse['error'])) {
return ['success' => false, 'error' => 'Ошибка обновления стадии: ' . $updateResponse['error']];
}
return ['success' => true, 'deal_id' => $dealId];
}
} }
class zohoHandler extends FormHandler { class zohoHandler extends FormHandler {
@ -518,48 +555,31 @@ class FormHandlerFactory {
} }
// обработка обновления профиля пользователя
add_action('profile_update', 'handle_profile_update', 10, 2);
function handle_profile_update($userID, $old_user_data) {
$user = get_user_by('ID', $userID);
// // Пример обработки обновления профиля пользователя $email = $user->user_email;
// add_action('profile_update', 'handle_profile_update', 10, 2); $phone = get_user_meta($userID, 'billing_phone', true);
$first_name = get_user_meta($userID, 'first_name', true);
// function handle_profile_update($userID, $old_user_data) { $last_name = get_user_meta($userID, 'last_name', true);
// $user = get_user_by('ID', $userID); $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,
// ];
// $result = b24_update_contact_by_user_id($userID, $newData);
// if (!$result['success']) {
// error_log('Ошибка обновления контакта в Bitrix24: ' . $result['error']);
// }
// }
// add_action('woocommerce_thankyou', 'add_b24_tracking_script', 10, 1);
// function add_b24_tracking_script($order_id) { $newData = [
// if (!$order_id) return; 'name' => $name,
'email' => $email,
'phone' => $phone,
];
$handler = new b24Handler();
$result = $handler->b24_update_contact_by_user_id($userID, $newData);
// $order = wc_get_order($order_id); if (!$result['success']) {
error_log('Ошибка обновления контакта в Bitrix24: ' . $result['error']);
}
}
// echo '<script>
// (window.b24order = window.b24order || []).push({
// id: "' . $order_id . '",
// sum: "' . $order->get_total() . '"
// });
// </script>';
// }
function get_utm_data() { function get_utm_data() {
$utm_data = []; $utm_data = [];
@ -572,7 +592,6 @@ function get_utm_data() {
return $utm_data; return $utm_data;
} }
// Функция для сохранения UTM в куки (если нужно хранить между сессиями) // Функция для сохранения UTM в куки (если нужно хранить между сессиями)
function save_utm_to_cookies() { function save_utm_to_cookies() {
$utm_params = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term']; $utm_params = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
@ -583,5 +602,4 @@ function save_utm_to_cookies() {
} }
} }
} }
save_utm_to_cookies(); save_utm_to_cookies();

@ -5,7 +5,7 @@
<h2 class="mform-title">ПРЕДЛОЖИТЕ СТАТЬЮ</h2> <h2 class="mform-title">ПРЕДЛОЖИТЕ СТАТЬЮ</h2>
<p class="mform-subtitle">или станьте автором</p> <p class="mform-subtitle">или станьте автором</p>
<form class="mform-form form-process" action="contact_form"> <form class="mform-form form-process" action="blogauth_form">
<div class="form-group full-width"> <div class="form-group full-width">
<input type="text" name="name" placeholder="Ваше имя *" required> <input type="text" name="name" placeholder="Ваше имя *" required>
</div> </div>
@ -18,7 +18,7 @@
</div> </div>
</div> </div>
<div class="form-group half-width message-container"> <div class="form-group half-width message-container">
<textarea name="message" placeholder="Текст обращения"></textarea> <textarea name="msg" placeholder="Текст обращения"></textarea>
</div> </div>
<div class="form-group half-width"> <div class="form-group half-width">

@ -2,7 +2,7 @@
<div class="modal__block-price"> <div class="modal__block-price">
<p class="modal-block-price__title">{{ __('Total', 'woocommerce') }}</p> <p class="modal-block-price__title">{{ __('Total', 'woocommerce') }}</p>
<p class="modal-block-price__price"> <p class="modal-block-price__price">
{{ fn('wc_cart_totals_order_total_html') }} {{ fn('wc_cart_totals_subtotal_html') }}
</p> </p>
</div> </div>

@ -10,5 +10,5 @@
if (!defined('ABSPATH')) { if (!defined('ABSPATH')) {
exit; exit;
} }
$context = Timber::context();
Timber::render('shop/checkout.twig', $context); Timber::render('shop/checkout.twig', $context);
Loading…
Cancel
Save