@W1SE2018
Вёрстка, дизайн, инвестиции, бизнес

Отправка деталей заказа в телеграм WP Woocommerce (Хук woocommerce_new_order)?

Здравствуйте.
Реализовал отправку уведомлений в functions.php файле темы, все данные о заказе приходят, кроме product details...

Вот сам код:
add_action( 'woocommerce_new_order', 'telegram_notification',  1, 1  );
function telegram_notification( $order_id ) {

            $order = wc_get_order( $order_id );
		$order_data = $order->get_data(); // The Order data	


$items = $order->get_items();

        foreach ($items as $item) {
            $product = $item->get_product();
            $qty     = $item->get_quantity() ? $item->get_quantity() : 1;
            $price   = wc_format_localized_price($item->get_total() / $qty);
            $text2    .= 'Товар :' . $product->get_name() . ' Кол-во :' . $qty . ' Цена :' . $price;
        }
		
		
$order_id = $order_data['id'];
$order_payment_method_title = $order_data['payment_method_title'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

$order_currency = $order_data['currency'];
$order_shipping_method = $order_data['shipping_method'];

$order_total = $order_data['total'];

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

			


//Далее создаем переменную, в которую помещаем PHP массив
$arr = array(
  'Номер заказа: ' => $order_id,
  'Дата: ' => $order_date_modified,
  'Название товара: ' => $text2,
  'Артикул: ' => $sku,
  'Мета продукта:' => $somemeta,
  'Цена товара: ' => $order_total,
  'Валюта: ' => $order_currency,
  'Имя: ' => $order_billing_first_name,
  'Фамилия: ' => $order_billing_last_name,
  'Телефон: ' => $order_billing_phone,
  'Email: ' => $order_billing_email,
  'Страна: ' => $order_billing_country,
  'Область: ' => $order_billing_state,
  'Город: ' => $order_billing_city,
  'Адрес1: ' => $order_billing_address_1,
  'Адрес2: ' => $order_billing_address_2,
  'Индекс: ' => $order_billing_postcode,
  'Метод доставки: ' => $shipping_data_method_title,
  'Метод оплаты: ' => $order_payment_method_title
);

//При помощи цикла перебираем массив и помещаем переменную $txt текст из массива $arr
foreach($arr as $key => $value) {
  $txt .= "<b>".$key."</b> ".$value."%0A";
};


            $xsl = file_get_contents("https://api.telegram.org/botxxxxxxxxxxxxxxxxx/sendMessage?parse_mode=html&chat_id=-xxxxx&text=" . $txt);
}


Кто в теме, подскажите пожалуйста как решить данную проблему, спасибо!
  • Вопрос задан
  • 1345 просмотров
Решения вопроса 1
wppanda5
@wppanda5 Куратор тега WordPress
WordPress Mедведь
Поясните вопрос вот у вас же есть получение данных продуктов

foreach ($items as $item) {
            $product = $item->get_product();
            $qty     = $item->get_quantity() ? $item->get_quantity() : 1;
            $price   = wc_format_localized_price($item->get_total() / $qty);
            $text2    .= 'Товар :' . $product->get_name() . ' Кол-во :' . $qty . ' Цена :' . $price;
        }


Вот примерно так можно получить всякое
foreach ( $order->get_items() as $item_id => $item ) {
   $product_id = $item->get_product_id();
   $variation_id = $item->get_variation_id();
   $product = $item->get_product();
   $name = $item->get_name();
   $quantity = $item->get_quantity();
   $subtotal = $item->get_subtotal();
   $total = $item->get_total();
   $tax = $item->get_subtotal_tax();
   $taxclass = $item->get_tax_class();
   $taxstat = $item->get_tax_status();
   $allmeta = $item->get_meta_data();
   $custom_meta = $item->get_meta( 'custom_meta_key', true );
   $type = $item->get_type();
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
Kleindberg
@Kleindberg
Full stack
Позвольте и свою лепту внести, вот обновлённый код для последних версий WooCommerce:

add_action( 'woocommerce_new_order', 'send_order_data', 10, 2);
function send_order_data( $order_id, $order ) {
	
	// Products array
	$order_items = array();
	foreach ( $order->get_items() as $item_id => $item ) {
		if( $item->is_type( 'line_item' ) ) {
			$product = $item->get_product();
			$order_items[] = array(
				'id' => $item->get_product_id(),
				'name' => $item->get_name(),
				'url' => get_permalink($product->get_id()),
				'image' => get_the_post_thumbnail_url($item->get_product_id()),
				'price' => $product->get_price(),
				'quantity' => $item->get_quantity(),
				'total' => $item->get_total(),
			);	
		}
	}

	// Order data
	$data = array(
		'id' => $order_id,
		'first_name' => $order->get_billing_first_name(),
		'last_name' => $order->get_billing_last_name(),
		'company' => $order->get_billing_company(),
		'address_1' => $order->get_billing_address_1(),
		'address_2' => $order->get_billing_address_2(),
		'city' => $order->get_billing_city(),
		'state' => $order->get_billing_state(),
		'postcode' => $order->get_billing_postcode(),
		'country' => $order->get_billing_country(),
		'email' => $order->get_billing_email(),
		'phone' => $order->get_billing_phone(),
		'items' => $order_items,
		'shipping_method' => $order->get_shipping_method(),
		'payment_method' => $order->get_payment_method_title(),
		'ttn' => $order->get_transaction_id(),
		'notes' => $order->get_customer_note(),
		'cutomer_id' => $order->get_customer_id() ?: $order->get_user_id(),
		'ip' => $order->get_customer_ip_address(),
		'agent' => $order->get_customer_user_agent(),
		'source' => $_SERVER['SERVER_NAME'],
		'date_created' => date("Y-m-d H:i:s", strtotime($order->get_date_created())),
		'date_modified' => date("Y-m-d H:i:s", strtotime($order->get_date_modified())),
		'date_completed' => $order->get_date_completed() ? date("Y-m-d H:i:s", strtotime($order->get_date_completed())) : null,
		'date_paid' => $order->get_date_paid() ? date("Y-m-d H:i:s", strtotime($order->get_date_paid())) : null,
	);

	$json = json_encode($data);
	
	// Путь к папке uploads
	$uploads_dir = wp_upload_dir();

	// Создаем путь к файлу (название файла может быть любым)
	$file_path = $uploads_dir['basedir'] . '/order_'.$order_id.'.json';

	// Записываем информацию в файл
	file_put_contents($file_path, $json, FILE_APPEND | LOCK_EX);

}


Функция woocommerce_new_order теперь принимает два аргумента - номер заказа и сам объект заказ, а это очень упрощает работу с заказом. Приведённый код сохраняет информацию о заказе в json файл в папку uploads, но вы можете переписать его и сделать, например, POST отправку через wp_remote_post() или сохранять данные в базу данных с помощью wpdb.
Ответ написан
Комментировать
@murrr
Решили проблему? Что-то с массивом. Не передаются поля
Название товара:
Артикул:
Мета продукта:

Вот уведомление, которое приходит в телеграм:
===
Номер заказа: 272
Дата: 2021-12-06 22:52:55
Название товара:
Артикул:
Мета продукта:
Цена товара: 8040
Валюта: RUB
Имя: Татьяна
Фамилия: Тестова
Телефон: 7999884455
Email: mail@mail.ru
Страна: RU
Область: Респ Татарстан
Город: г Москва
Адрес1: ул Академика Губкина, д 99
Адрес2:
Индекс: 111111
Метод доставки:
Метод оплаты: Оплата при доставке
===
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы