send telegram
This commit is contained in:
64
index3.js
64
index3.js
@@ -22,6 +22,7 @@ const mobileToggle = document.getElementById('mobileToggle')
|
||||
const orderSuccess = document.getElementById('orderSuccess')
|
||||
const contactSuccess = document.getElementById('contactSuccess')
|
||||
const wooCommerceConfig = window.test1WooCommerce || null
|
||||
const leadFormConfig = window.test1LeadForm || null
|
||||
const cartPageUrl = (wooCommerceConfig && wooCommerceConfig.cartUrl) ? wooCommerceConfig.cartUrl : '/cart/'
|
||||
const checkoutPageUrl = (wooCommerceConfig && wooCommerceConfig.checkoutUrl) ? wooCommerceConfig.checkoutUrl : '/checkout/'
|
||||
const cartPanel = cartDrawer?.querySelector('.cart-panel')
|
||||
@@ -138,6 +139,52 @@ const mobileToggle = document.getElementById('mobileToggle')
|
||||
})
|
||||
}
|
||||
|
||||
const submitLeadForm = (formElement, successElement, formType, onSuccess) => {
|
||||
if (!formElement || !successElement) {
|
||||
return
|
||||
}
|
||||
|
||||
formElement.addEventListener('submit', async event => {
|
||||
event.preventDefault()
|
||||
|
||||
if (!leadFormConfig?.ajaxUrl || !leadFormConfig?.action || !leadFormConfig?.nonce) {
|
||||
window.alert('Форма временно недоступна. Обновите страницу и попробуйте снова.')
|
||||
return
|
||||
}
|
||||
|
||||
const formData = new window.FormData(formElement)
|
||||
formData.append('action', leadFormConfig.action)
|
||||
formData.append('nonce', leadFormConfig.nonce)
|
||||
formData.append('form_type', formType)
|
||||
|
||||
try {
|
||||
const response = await window.fetch(leadFormConfig.ajaxUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const payload = await response.json().catch(() => null)
|
||||
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error('submit_failed')
|
||||
}
|
||||
|
||||
successElement.classList.add('visible')
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess()
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
formElement.reset()
|
||||
successElement.classList.remove('visible')
|
||||
}, 2200)
|
||||
} catch (error) {
|
||||
window.alert('Не удалось отправить заявку. Попробуйте еще раз.')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
mobileToggle.addEventListener('click', () => {
|
||||
const isOpen = mobilePanel.classList.contains('active')
|
||||
if (isOpen) {
|
||||
@@ -272,26 +319,15 @@ const mobileToggle = document.getElementById('mobileToggle')
|
||||
})
|
||||
})
|
||||
|
||||
orderForm.addEventListener('submit', event => {
|
||||
event.preventDefault()
|
||||
orderSuccess.classList.add('visible')
|
||||
submitLeadForm(orderForm, orderSuccess, 'landing_order', () => {
|
||||
cart = []
|
||||
renderCart()
|
||||
setTimeout(() => {
|
||||
closeModal()
|
||||
orderForm.reset()
|
||||
orderSuccess.classList.remove('visible')
|
||||
}, 1800)
|
||||
}, 700)
|
||||
})
|
||||
|
||||
contactForm.addEventListener('submit', event => {
|
||||
event.preventDefault()
|
||||
contactSuccess.classList.add('visible')
|
||||
setTimeout(() => {
|
||||
contactForm.reset()
|
||||
contactSuccess.classList.remove('visible')
|
||||
}, 2200)
|
||||
})
|
||||
submitLeadForm(contactForm, contactSuccess, 'contacts')
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key !== 'Escape') {
|
||||
|
||||
@@ -81,6 +81,8 @@ $table_prefix = 'wp_';
|
||||
define( 'WP_DEBUG', false );
|
||||
|
||||
/* Произвольные значения добавляйте между этой строкой и надписью "дальше не редактируем". */
|
||||
define( 'TWENTYTWENTYFOUR_TELEGRAM_BOT_TOKEN', '8607238298:AAH_dZ-EgzFOpT0LtmYuiy4ifcsvLZxXwPk' );
|
||||
define( 'TWENTYTWENTYFOUR_TELEGRAM_CHAT_ID', '-1003995055932' );
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,18 +1,46 @@
|
||||
(() => {
|
||||
const contactForm = document.getElementById('contactForm')
|
||||
const contactSuccess = document.getElementById('contactSuccess')
|
||||
const formConfig = window.test1ContactsForm || null
|
||||
|
||||
if (!contactForm || !contactSuccess) {
|
||||
return
|
||||
}
|
||||
|
||||
contactForm.addEventListener('submit', event => {
|
||||
contactForm.addEventListener('submit', async event => {
|
||||
event.preventDefault()
|
||||
contactSuccess.classList.add('visible')
|
||||
|
||||
setTimeout(() => {
|
||||
contactForm.reset()
|
||||
contactSuccess.classList.remove('visible')
|
||||
}, 2200)
|
||||
if (!formConfig?.ajaxUrl || !formConfig?.action || !formConfig?.nonce) {
|
||||
window.alert('Форма временно недоступна. Обновите страницу и попробуйте снова.')
|
||||
return
|
||||
}
|
||||
|
||||
const formData = new window.FormData(contactForm)
|
||||
formData.append('action', formConfig.action)
|
||||
formData.append('nonce', formConfig.nonce)
|
||||
formData.append('form_type', 'contacts')
|
||||
|
||||
try {
|
||||
const response = await window.fetch(formConfig.ajaxUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const payload = await response.json().catch(() => null)
|
||||
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error('submit_failed')
|
||||
}
|
||||
|
||||
contactSuccess.classList.add('visible')
|
||||
|
||||
setTimeout(() => {
|
||||
contactForm.reset()
|
||||
contactSuccess.classList.remove('visible')
|
||||
}, 2200)
|
||||
} catch (error) {
|
||||
window.alert('Не удалось отправить заявку. Попробуйте еще раз.')
|
||||
}
|
||||
})
|
||||
})()
|
||||
|
||||
@@ -493,6 +493,16 @@ function twentytwentyfour_test1_assets() {
|
||||
true
|
||||
);
|
||||
|
||||
wp_localize_script(
|
||||
'twentytwentyfour-test1-script',
|
||||
'test1LeadForm',
|
||||
array(
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'action' => 'twentytwentyfour_submit_lead',
|
||||
'nonce' => wp_create_nonce( 'twentytwentyfour_submit_lead' ),
|
||||
)
|
||||
);
|
||||
|
||||
if ( class_exists( 'WooCommerce' ) ) {
|
||||
wp_localize_script(
|
||||
'twentytwentyfour-test1-script',
|
||||
@@ -531,12 +541,190 @@ function twentytwentyfour_test1_assets() {
|
||||
(string) filemtime( $contacts_js_file ),
|
||||
true
|
||||
);
|
||||
|
||||
wp_localize_script(
|
||||
'twentytwentyfour-test1-contacts-script',
|
||||
'test1ContactsForm',
|
||||
array(
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'action' => 'twentytwentyfour_submit_lead',
|
||||
'nonce' => wp_create_nonce( 'twentytwentyfour_submit_lead' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
add_action( 'wp_enqueue_scripts', 'twentytwentyfour_test1_assets', 100 );
|
||||
|
||||
/**
|
||||
* Send a formatted message to Telegram.
|
||||
*
|
||||
* Configure credentials in wp-config.php:
|
||||
* define( 'TWENTYTWENTYFOUR_TELEGRAM_BOT_TOKEN', '...' );
|
||||
* define( 'TWENTYTWENTYFOUR_TELEGRAM_CHAT_ID', '...' );
|
||||
*
|
||||
* @param string $title Message title.
|
||||
* @param array $fields Key-value pairs for message rows.
|
||||
* @return bool
|
||||
*/
|
||||
function twentytwentyfour_send_telegram_message( $title, $fields ) {
|
||||
$token = defined( 'TWENTYTWENTYFOUR_TELEGRAM_BOT_TOKEN' ) ? (string) constant( 'TWENTYTWENTYFOUR_TELEGRAM_BOT_TOKEN' ) : '';
|
||||
$chat_id = defined( 'TWENTYTWENTYFOUR_TELEGRAM_CHAT_ID' ) ? (string) constant( 'TWENTYTWENTYFOUR_TELEGRAM_CHAT_ID' ) : '';
|
||||
|
||||
if ( '' === trim( $token ) || '' === trim( $chat_id ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rows = array();
|
||||
$rows[] = '<b>' . esc_html( wp_strip_all_tags( (string) $title ) ) . '</b>';
|
||||
|
||||
foreach ( $fields as $label => $value ) {
|
||||
$clean_value = trim( wp_strip_all_tags( (string) $value ) );
|
||||
|
||||
if ( '' === $clean_value ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = '<b>' . esc_html( wp_strip_all_tags( (string) $label ) ) . ':</b> ' . esc_html( $clean_value );
|
||||
}
|
||||
|
||||
$response = wp_remote_post(
|
||||
'https://api.telegram.org/bot' . rawurlencode( $token ) . '/sendMessage',
|
||||
array(
|
||||
'timeout' => 12,
|
||||
'body' => array(
|
||||
'chat_id' => $chat_id,
|
||||
'parse_mode' => 'HTML',
|
||||
'text' => implode( "\n", $rows ),
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$status_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
|
||||
return $status_code >= 200 && $status_code < 300;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle AJAX lead submissions from landing and contacts forms.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function twentytwentyfour_submit_lead_ajax() {
|
||||
if ( ! check_ajax_referer( 'twentytwentyfour_submit_lead', 'nonce', false ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Ошибка проверки формы. Обновите страницу и попробуйте снова.', 'twentytwentyfour' ) ), 403 );
|
||||
}
|
||||
|
||||
$form_type = isset( $_POST['form_type'] ) ? sanitize_key( wp_unslash( $_POST['form_type'] ) ) : 'contacts';
|
||||
|
||||
if ( 'landing_order' === $form_type ) {
|
||||
$name = isset( $_POST['customerName'] ) ? sanitize_text_field( wp_unslash( $_POST['customerName'] ) ) : '';
|
||||
$phone = isset( $_POST['customerPhone'] ) ? sanitize_text_field( wp_unslash( $_POST['customerPhone'] ) ) : '';
|
||||
$address = isset( $_POST['customerAddress'] ) ? sanitize_text_field( wp_unslash( $_POST['customerAddress'] ) ) : '';
|
||||
$type = isset( $_POST['customerType'] ) ? sanitize_text_field( wp_unslash( $_POST['customerType'] ) ) : '';
|
||||
$comment = isset( $_POST['customerOrder'] ) ? sanitize_textarea_field( wp_unslash( $_POST['customerOrder'] ) ) : '';
|
||||
|
||||
if ( '' === $name || '' === $phone ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Укажите имя и телефон.', 'twentytwentyfour' ) ), 422 );
|
||||
}
|
||||
|
||||
$sent = twentytwentyfour_send_telegram_message(
|
||||
'Новая заявка с главной страницы',
|
||||
array(
|
||||
'Имя' => $name,
|
||||
'Телефон' => $phone,
|
||||
'Адрес' => $address,
|
||||
'Тип' => $type,
|
||||
'Комментарий' => $comment,
|
||||
'Источник' => home_url( '/' ),
|
||||
)
|
||||
);
|
||||
} else {
|
||||
$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
|
||||
$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
|
||||
$address = isset( $_POST['address'] ) ? sanitize_text_field( wp_unslash( $_POST['address'] ) ) : '';
|
||||
$comment = isset( $_POST['comment'] ) ? sanitize_textarea_field( wp_unslash( $_POST['comment'] ) ) : '';
|
||||
|
||||
if ( '' === $name || '' === $phone ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Укажите имя и телефон.', 'twentytwentyfour' ) ), 422 );
|
||||
}
|
||||
|
||||
$sent = twentytwentyfour_send_telegram_message(
|
||||
'Новая заявка с страницы Контакты',
|
||||
array(
|
||||
'Имя' => $name,
|
||||
'Телефон' => $phone,
|
||||
'Адрес' => $address,
|
||||
'Комментарий' => $comment,
|
||||
'Источник' => home_url( '/contacts/' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! $sent ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Не удалось отправить заявку. Проверьте настройки Telegram.', 'twentytwentyfour' ) ), 500 );
|
||||
}
|
||||
|
||||
wp_send_json_success( array( 'message' => __( 'Спасибо! Заявка принята.', 'twentytwentyfour' ) ) );
|
||||
}
|
||||
add_action( 'wp_ajax_twentytwentyfour_submit_lead', 'twentytwentyfour_submit_lead_ajax' );
|
||||
add_action( 'wp_ajax_nopriv_twentytwentyfour_submit_lead', 'twentytwentyfour_submit_lead_ajax' );
|
||||
|
||||
/**
|
||||
* Send WooCommerce checkout orders to Telegram.
|
||||
*
|
||||
* @param int $order_id Order ID.
|
||||
* @param array $posted_data Checkout payload.
|
||||
* @param WC_Order $order Order object.
|
||||
* @return void
|
||||
*/
|
||||
function twentytwentyfour_send_checkout_order_to_telegram( $order_id, $posted_data, $order ) {
|
||||
if ( ! $order instanceof WC_Order ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = array();
|
||||
|
||||
foreach ( $order->get_items() as $item ) {
|
||||
if ( ! $item instanceof WC_Order_Item_Product ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = sprintf( '%s x %d', $item->get_name(), (int) $item->get_quantity() );
|
||||
}
|
||||
|
||||
$address_parts = array_filter(
|
||||
array(
|
||||
$order->get_billing_city(),
|
||||
$order->get_billing_address_1(),
|
||||
(string) get_post_meta( $order_id, '_billing_house', true ),
|
||||
(string) get_post_meta( $order_id, '_billing_flat', true ),
|
||||
(string) get_post_meta( $order_id, '_billing_entrance_floor', true ),
|
||||
)
|
||||
);
|
||||
|
||||
$fields = array(
|
||||
'Заказ' => '#' . $order->get_order_number(),
|
||||
'Имя' => $order->get_billing_first_name(),
|
||||
'Телефон' => $order->get_billing_phone(),
|
||||
'Адрес' => implode( ', ', $address_parts ),
|
||||
'Когда доставить' => (string) get_post_meta( $order_id, '_tw_delivery_day', true ),
|
||||
'Интервал' => (string) get_post_meta( $order_id, '_tw_delivery_time', true ),
|
||||
'Обмен тары' => (string) get_post_meta( $order_id, '_tw_bottle_exchange', true ),
|
||||
'Комментарий' => $order->get_customer_note(),
|
||||
'Состав' => implode( '; ', $items ),
|
||||
'Сумма' => wp_strip_all_tags( $order->get_formatted_order_total() ),
|
||||
);
|
||||
|
||||
twentytwentyfour_send_telegram_message( 'Новый заказ с сайта', $fields );
|
||||
}
|
||||
add_action( 'woocommerce_checkout_order_processed', 'twentytwentyfour_send_checkout_order_to_telegram', 20, 3 );
|
||||
|
||||
/**
|
||||
* Enqueue shared test1 header/footer styles for cart and checkout.
|
||||
*
|
||||
|
||||
38
wp-content/themes/twentytwentyfour/send-telegram.php
Normal file
38
wp-content/themes/twentytwentyfour/send-telegram.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
/* Пример из: https://vc.ru/dev/158136-kak-otpravlyat-zayavki-s-lendinga-pryamo-v-telegram */
|
||||
|
||||
|
||||
//В переменную $token нужно вставить токен, который нам прислал @botFather
|
||||
$token = "1094153697:AAFiLXXXXXLl0hRDsxBij1lddKydKxSSsOg04";
|
||||
|
||||
//Сюда вставляем chat_id
|
||||
$chat_id = "-40XXXX740";
|
||||
|
||||
//Определяем переменные для передачи данных из нашей формы
|
||||
if ($_POST['phone'] !== '') {
|
||||
$name = ($_POST['name']);
|
||||
$phone = ($_POST['phone']);
|
||||
|
||||
//Собираем в массив то, что будет передаваться боту
|
||||
$arr = array(
|
||||
'Имя:' => $name,
|
||||
'Телефон:' => $phone
|
||||
);
|
||||
|
||||
//Настраиваем внешний вид сообщения в телеграме
|
||||
foreach($arr as $key => $value) {
|
||||
$txt .= "<b>".$key."</b> ".$value."%0A";
|
||||
};
|
||||
|
||||
//Передаем данные боту
|
||||
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
|
||||
|
||||
//Выводим сообщение об успешной отправке
|
||||
if ($sendToTelegram) {
|
||||
echo 'Спасибо! Ваша заявка принята. Мы свяжемся с вами в ближайшее время.';
|
||||
}else{
|
||||
echo 'Что-то пошло не так. Попробуйте отправить форму ещё раз.';
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
Reference in New Issue
Block a user