70 lines
2.1 KiB
PHP
70 lines
2.1 KiB
PHP
<?php
|
|
|
|
add_action('woocommerce_order_status_changed', function ($order_id, $old, $new, $order) {
|
|
|
|
// Chỉ khi chuyển sang completed
|
|
if ($new !== 'completed') {
|
|
return;
|
|
}
|
|
|
|
if (!$order instanceof WC_Order) {
|
|
$order = wc_get_order($order_id);
|
|
}
|
|
if (!$order) return;
|
|
|
|
$items = [];
|
|
|
|
foreach ($order->get_items() as $item_id => $item) {
|
|
/** @var WC_Order_Item_Product $item */
|
|
$product = $item->get_product();
|
|
|
|
$items[] = [
|
|
'item_id' => $item_id,
|
|
'product_id' => $product ? $product->get_id() : null,
|
|
'variation_id' => $item->get_variation_id(),
|
|
'type' => $product ? $product->get_type() : null,
|
|
'name' => $item->get_name(),
|
|
'sku' => $product ? $product->get_sku() : null,
|
|
'quantity' => $item->get_quantity(),
|
|
|
|
// Giá
|
|
'subtotal' => $item->get_subtotal(),
|
|
'total' => $item->get_total(),
|
|
'tax' => $item->get_total_tax(),
|
|
|
|
// Giá đơn vị
|
|
'price_per_item' => $item->get_quantity() > 0
|
|
? round($item->get_total() / $item->get_quantity(), 2)
|
|
: 0,
|
|
|
|
// Attributes (variation)
|
|
'attributes' => $item->get_variation_id()
|
|
? wc_get_formatted_variation($product, true, false, true)
|
|
: null,
|
|
|
|
// Meta item
|
|
'item_meta' => array_map(function ($meta) {
|
|
return [
|
|
'key' => $meta->key,
|
|
'value' => $meta->value,
|
|
];
|
|
}, $item->get_meta_data()),
|
|
];
|
|
}
|
|
|
|
$log = [
|
|
'event' => 'order_completed',
|
|
'order_id' => $order_id,
|
|
'old_status' => $old,
|
|
'new_status' => $new,
|
|
'currency' => $order->get_currency(),
|
|
'total' => $order->get_total(),
|
|
'items' => $items,
|
|
];
|
|
|
|
WPI_Logger::log(json_encode(
|
|
$log,
|
|
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
|
|
));
|
|
}, 10, 4);
|