You are here

public function PixelSubscriber::purchaseEvent in Simple Facebook Pixel 8

Adds Purchase event.

Parameters

\Drupal\state_machine\Event\WorkflowTransitionEvent $event: The workflow transition event.

File

src/EventSubscriber/PixelSubscriber.php, line 200

Class

PixelSubscriber
Class PixelSubscriber.

Namespace

Drupal\simple_facebook_pixel\EventSubscriber

Code

public function purchaseEvent(WorkflowTransitionEvent $event) {
  if ($this->pixelBuilder
    ->isEnabled() && $this->configFactory
    ->get('purchase_enabled')) {
    $commerce_order = $event
      ->getEntity();
    $skus = [];
    $contents = [];

    /** @var \Drupal\commerce_order\Entity\OrderItem $item */
    foreach ($commerce_order
      ->getItems() as $item) {
      $skus[] = $item
        ->getPurchasedEntity()
        ->getSku();
      $contents[] = [
        'id' => $item
          ->getPurchasedEntity()
          ->getSku(),
        'quantity' => $item
          ->getQuantity(),
        'item_price' => $item
          ->getPurchasedEntity()
          ->getPrice()
          ->getNumber(),
      ];
    }
    $data = [
      'num_items' => count($commerce_order
        ->getItems()),
      'value' => $commerce_order
        ->getTotalPrice()
        ->getNumber(),
      'currency' => $commerce_order
        ->getTotalPrice()
        ->getCurrencyCode(),
      'content_ids' => $skus,
      'contents' => $contents,
      'content_type' => 'product',
    ];
    $this->pixelBuilder
      ->addEvent('Purchase', $data, TRUE);
  }
}