Реализация корзины без личного кабинета с отправкой данных
Вот комплексное решение для реализации корзины без необходимости авторизации пользователя, с возможностью отправки данных на email, Telegram и в CRM.
1. HTML структура корзины
<div class="cart-wrapper">
<div class="cart-items">
<!-- Товары будут добавляться динамически -->
</div>
<div class="cart-total">
Итого: <span class="total-price">0</span> ₽
</div>
<form id="order-form" class="order-form">
<input type="text" name="name" placeholder="Ваше имя" required>
<input type="tel" name="phone" placeholder="Телефон" required>
<input type="email" name="email" placeholder="Email">
<textarea name="comment" placeholder="Комментарий к заказу"></textarea>
<button type="submit">Оформить заказ</button>
</form>
</div>
2. JavaScript реализация (jQuery)
jQuery(document).ready(function($) {
// Инициализация корзины из localStorage
let cart = JSON.parse(localStorage.getItem('cart')) || [];
// Обновление отображения корзины
function updateCartDisplay() {
$('.cart-items').empty();
let total = 0;
cart.forEach(item => {
$('.cart-items').append(`
<div class="cart-item" data-id="${item.id}">
<h4>${item.name}</h4>
<div class="item-price">${item.price} ₽</div>
<div class="item-quantity">
<button class="quantity-minus">-</button>
<span>${item.quantity}</span>
<button class="quantity-plus">+</button>
</div>
<button class="remove-item">×</button>
</div>
`);
total += item.price * item.quantity;
});
$('.total-price').text(total);
localStorage.setItem('cart', JSON.stringify(cart));
}
// Добавление товара в корзину
function addToCart(productId, productName, productPrice) {
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
id: productId,
name: productName,
price: productPrice,
quantity: 1
});
}
updateCartDisplay();
}
// Обработчики событий
$(document).on('click', '.add-to-cart', function() {
const product = $(this).closest('.product');
addToCart(
product.data('id'),
product.find('.product-name').text(),
product.data('price')
);
});
$(document).on('click', '.quantity-plus', function() {
const itemId = $(this).closest('.cart-item').data('id');
const item = cart.find(item => item.id === itemId);
item.quantity += 1;
updateCartDisplay();
});
$(document).on('click', '.quantity-minus', function() {
const itemId = $(this).closest('.cart-item').data('id');
const item = cart.find(item => item.id === itemId);
if (item.quantity > 1) {
item.quantity -= 1;
} else {
cart = cart.filter(item => item.id !== itemId);
}
updateCartDisplay();
});
$(document).on('click', '.remove-item', function() {
const itemId = $(this).closest('.cart-item').data('id');
cart = cart.filter(item => item.id !== itemId);
updateCartDisplay();
});
// Отправка формы заказа
$('#order-form').on('submit', function(e) {
e.preventDefault();
if (cart.length === 0) {
alert('Корзина пуста!');
return;
}
const formData = $(this).serializeArray();
const orderData = {
customer: {},
products: cart,
total: $('.total-price').text()
};
formData.forEach(field => {
orderData.customer[field.name] = field.value;
});
// Отправка данных
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'process_order',
order: orderData,
_ajax_nonce: cart_vars.nonce
},
beforeSend: function() {
$('#order-form button').prop('disabled', true).text('Отправка...');
},
success: function(response) {
if (response.success) {
alert('Заказ успешно оформлен!');
cart = [];
localStorage.removeItem('cart');
updateCartDisplay();
$('#order-form')[0].reset();
} else {
alert('Ошибка: ' + response.data);
}
},
error: function() {
alert('Ошибка соединения с сервером');
},
complete: function() {
$('#order-form button').prop('disabled', false).text('Оформить заказ');
}
});
});
// Инициализация при загрузке
updateCartDisplay();
});
3. PHP обработка заказа
add_action('wp_ajax_process_order', 'process_order_callback');
add_action('wp_ajax_nopriv_process_order', 'process_order_callback');
function process_order_callback() {
check_ajax_referer('cart_nonce', '_ajax_nonce');
if (!isset($_POST['order'])) {
wp_send_json_error('Неверные данные заказа');
}
$order = $_POST['order'];
// Валидация данных
$customer_name = sanitize_text_field($order['customer']['name']);
$customer_phone = sanitize_text_field($order['customer']['phone']);
$customer_email = sanitize_email($order['customer']['email']);
$customer_comment = sanitize_textarea_field($order['customer']['comment']);
if (empty($customer_name) || empty($customer_phone)) {
wp_send_json_error('Заполните обязательные поля');
}
// Формирование сообщения
$message = "Новый заказ:\n\n";
$message .= "Имя: $customer_name\n";
$message .= "Телефон: $customer_phone\n";
$message .= "Email: $customer_email\n";
$message .= "Комментарий: $customer_comment\n\n";
$message .= "Состав заказа:\n";
$total = 0;
foreach ($order['products'] as $product) {
$product_total = $product['price'] * $product['quantity'];
$message .= "{$product['name']} - {$product['quantity']} × {$product['price']} ₽ = $product_total ₽\n";
$total += $product_total;
}
$message .= "\nИтого: $total ₽";
// 1. Отправка на email
$email_sent = wp_mail(
get_option('admin_email'),
'Новый заказ с сайта',
$message,
array('Content-Type: text/plain; charset=UTF-8')
);
// 2. Отправка в Telegram (опционально)
$telegram_sent = send_to_telegram($message);
// 3. Отправка в CRM (пример для Bitrix24)
$crm_sent = send_to_bitrix24($order);
// Сохранение заказа в базу данных (опционально)
save_order_to_db($order);
if ($email_sent || $telegram_sent || $crm_sent) {
wp_send_json_success('Заказ принят в обработку');
} else {
wp_send_json_error('Ошибка при обработке заказа');
}
}
// Функция отправки в Telegram
function send_to_telegram($message) {
$bot_token = 'YOUR_BOT_TOKEN';
$chat_id = 'YOUR_CHAT_ID';
$url = "https://api.telegram.org/bot{$bot_token}/sendMessage";
$data = [
'chat_id' => $chat_id,
'text' => $message,
'parse_mode' => 'HTML'
];
$response = wp_remote_post($url, [
'body' => $data,
'timeout' => 10
]);
return !is_wp_error($response);
}
// Функция отправки в Bitrix24 (пример)
function send_to_bitrix24($order) {
$webhook_url = 'YOUR_BITRIX24_WEBHOOK';
$fields = [
'TITLE' => 'Заказ с сайта',
'NAME' => $order['customer']['name'],
'PHONE' => $order['customer']['phone'],
'COMMENTS' => $order['customer']['comment'],
'OPPORTUNITY' => $order['total']
];
$response = wp_remote_post($webhook_url, [
'body' => [
'fields' => json_encode($fields),
'params' => json_encode(['REGISTER_SONET_EVENT' => 'Y'])
],
'timeout' => 10
]);
return !is_wp_error($response);
}
// Функция сохранения заказа в базу данных
function save_order_to_db($order) {
global $wpdb;
$wpdb->insert('wp_orders', [
'customer_name' => $order['customer']['name'],
'customer_phone' => $order['customer']['phone'],
'customer_email' => $order['customer']['email'],
'customer_comment' => $order['customer']['comment'],
'order_data' => json_encode($order['products']),
'total' => $order['total'],
'created_at' => current_time('mysql')
]);
}
4. CSS стилизация корзины
.cart-wrapper {
border: 1px solid #ddd;
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
.cart-items {
margin-bottom: 20px;
}
.cart-item {
display: flex;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #eee;
}
.cart-item h4 {
flex: 1;
margin: 0;
}
.item-price {
width: 80px;
text-align: center;
}
.item-quantity {
display: flex;
align-items: center;
width: 120px;
justify-content: center;
}
.item-quantity button {
width: 30px;
height: 30px;
border: 1px solid #ddd;
background: none;
cursor: pointer;
}
.item-quantity span {
margin: 0 10px;
}
.remove-item {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #ff0000;
}
.cart-total {
text-align: right;
font-weight: bold;
font-size: 18px;
margin: 20px 0;
}
.order-form input,
.order-form textarea {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.order-form button {
background: #0073aa;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
width: 100%;
}
.order-form button:hover {
background: #005177;
}
5. Создание таблицы для заказов (если нужно сохранять в БД)
Добавьте в functions.php или при активации плагина:
function create_orders_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'orders';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
customer_name varchar(100) NOT NULL,
customer_phone varchar(20) NOT NULL,
customer_email varchar(100),
customer_comment text,
order_data text NOT NULL,
total decimal(10,2) NOT NULL,
created_at datetime NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__, 'create_orders_table');
Особенности реализации
- Хранение данных: корзина сохраняется в localStorage браузера
- Отправка данных: поддержка нескольких каналов (email, Telegram, CRM)
- Безопасность: проверка nonce, санитайзинг данных
- Адаптивность: работает без авторизации пользователя
- Масштабируемость: легко добавить новые способы обработки заказов
Это решение обеспечивает полный цикл работы корзины — от добавления товаров до оформления заказа и отправки данных администратору.