View source
<?php
namespace Drupal\commerce_google_analytics\EventSubscriber;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_price\Price;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SendOrderAnalyticsSubscriber implements EventSubscriberInterface {
static function getSubscribedEvents() {
$events['commerce_order.place.post_transition'] = [
'sendOrderAnalytics',
-100,
];
return $events;
}
public function sendOrderAnalytics(WorkflowTransitionEvent $event) {
$order = $event
->getEntity();
$ga_push_params = $this
->buildGaPushParams($order);
ga_push_add_ecommerce($ga_push_params);
}
public function buildGaPushParams(OrderInterface $order) {
$order_total = $order
->getTotalPrice();
$currency_code = $order_total
->getCurrencyCode();
$billing_profile = $order
->getBillingProfile();
$address = $billing_profile
->get('address')
->first();
$tax_total = 0;
$shipping_total = 0;
if (\Drupal::moduleHandler()
->moduleExists('commerce_shipping')) {
$shipping_adjustments_total = new Price('0', $currency_code);
foreach ($order
->collectAdjustments() as $adjustment) {
if ($adjustment
->getType() == 'shipping') {
$shipping_adjustments_total
->add($adjustment
->getAmount());
}
}
$shipping_total = $shipping_adjustments_total
->getNumber();
}
$transaction = [
'order_id' => $order
->id(),
'affiliation' => $order
->getStore()
->label(),
'total' => $order_total
->getNumber(),
'currency' => $currency_code,
'total_tax' => $tax_total,
'total_shipping' => $shipping_total,
'city' => $address
->getLocality(),
'region' => $address
->getAdministrativeArea(),
'country' => $address
->getCountryCode(),
];
$context = [
'order' => $order,
];
\Drupal::moduleHandler()
->alter('commerce_google_analytics_transaction', $transaction, $context);
$items = [];
foreach ($order
->getItems() as $order_item) {
$purchased_entity = $order_item
->getPurchasedEntity();
$item = [
'order_id' => $order
->id(),
'sku' => $order_item
->id(),
'name' => $order_item
->label(),
'category' => ucfirst($order_item
->bundle()),
'price' => $order_item
->getUnitPrice()
->getNumber(),
'currency' => $order_item
->getUnitPrice()
->getCurrencyCode(),
'quantity' => $order_item
->getQuantity(),
];
if ($purchased_entity instanceof ProductVariationInterface) {
$item['sku'] = $purchased_entity
->getSku();
$item['sku'] = 'Product: ' . $purchased_entity
->bundle();
}
$context = [
'transaction' => $transaction,
'order' => $order,
];
\Drupal::moduleHandler()
->alter('commerce_google_analytics_item', $item, $order_item, $context);
if (!empty($item)) {
$items[] = $item;
}
}
$context = [
'transaction' => $transaction,
'order' => $order,
];
\Drupal::moduleHandler()
->alter('commerce_google_analytics_items', $items, $context);
$ga_push_params = [
'trans' => $transaction,
'items' => $items,
];
return $ga_push_params;
}
}