custom/plugins/EcBasicTheme/src/Storefront/Event/Subscriber/EventHubSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace EcBasicTheme\Storefront\Event\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Shopware\Models\Order\Repository;
  6. use Shopware\Models\Order\Order;
  7. use Psr\Log\LoggerInterface;
  8. class EventHubSubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var LoggerInterface
  12.      */
  13.     private $logger;
  14.     /**
  15.      * StorefrontRenderEventSubscriber constructor.
  16.      * @param SystemConfigService $systemConfigService
  17.      */
  18.     public function __construct(LoggerInterface $logger)
  19.     {
  20.         $this->logger $logger;
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             CheckoutOrderPlacedEvent::class => 'onPurchase'
  26.         ];
  27.     }
  28.     /**
  29.      * On purchase send data to Event Hub
  30.      *
  31.      * @param CheckoutOrderPlacedEvent $event
  32.      * @return void
  33.      */
  34.     public function onPurchase(CheckoutOrderPlacedEvent  $event)
  35.     {
  36.         $eventHub 'cdp-transaction';
  37.         $eventHubUrl 'https://dymde-dem-shr-evhns.servicebus.windows.net';
  38.         $sasKeyValue 'VS4pzl27L09Ds6ve52Y2z2v3IXnOG92W3+AEhC2CYKA=';
  39.         $sasKeyName 'cdp-transaction-auth';
  40.        
  41.         if(!empty($event) && $orderId $event->getOrderId()){
  42.             $token $this->generateSasToken($eventHubUrl$sasKeyName$sasKeyValue);
  43.             $url $eventHubUrl '/' $eventHub '/messages?timeout=60&api-version=2014-01';
  44.             $productsData $this->prepareOrderData($event);
  45.             foreach($productsData as $product)
  46.             {
  47.                 $responseCode $this->executeCurl($urljson_encode($product), $token);
  48.                 $this->logger->info('Event sent to EvenHub', [
  49.                     'responseCode' => $responseCode['http_code'],
  50.                     'orderId' => $orderId,
  51.                     'product' => $product['data']['attributes']['customAttributes']['product'],
  52.                 ]);
  53.             }
  54.         }
  55.     }
  56.     /**
  57.      * generate SAS token for Event Hub
  58.      *
  59.      * @param string $uri
  60.      * @param string $sasKeyName
  61.      * @param string $sasKeyValue
  62.      * @return string
  63.      */
  64.     public function generateSasToken($uri$sasKeyName$sasKeyValue) : string 
  65.     
  66.         $targetUri strtolower(rawurlencode(strtolower($uri))); 
  67.         $expires time();     
  68.         $expiresInMins 60
  69.         $week 60*60*24*7;
  70.         $expires $expires $week
  71.         $toSign $targetUri "\n" $expires
  72.         $signature rawurlencode(base64_encode(hash_hmac('sha256',             
  73.         $toSign$sasKeyValueTRUE))); 
  74.         $token "SharedAccessSignature sr=" $targetUri "&sig=" $signature "&se=" $expires .         "&skn="$sasKeyName
  75.         return $token
  76.     } 
  77.     /**
  78.      * Execute cURL request for Event Hub
  79.      *
  80.      * @param string $url
  81.      * @param string $data
  82.      * @param string $token
  83.      * @return array
  84.      */
  85.     public function executeCurl($url$data$token) : array
  86.     {
  87.         $curl curl_init();
  88.         curl_setopt_array($curl, array(
  89.             CURLOPT_URL => $url,
  90.             CURLOPT_POST => 1,
  91.             CURLOPT_RETURNTRANSFER => true,
  92.             CURLOPT_MAXREDIRS => 10,
  93.             CURLOPT_TIMEOUT => 0,
  94.             CURLOPT_FOLLOWLOCATION => true,
  95.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  96.             CURLOPT_POSTFIELDS => $data,
  97.             CURLINFO_HEADER_OUT => true,
  98.             CURLOPT_HTTPHEADER => array(
  99.                 'Authorization: ' $token,
  100.                 'Content-Type: application/atom+xml;type=entry;charset=utf-8',
  101.                 'Host: dymde-dem-shr-evhns.servicebus.windows.net',
  102.             ),
  103.         ));
  104.         $response curl_exec($curl);
  105.         // $error = curl_errno($curl);
  106.         $code curl_getinfo($curl);
  107.         // echo '<pre>'; print_r($code); die;
  108.         curl_close($curl);
  109.         return $code;
  110.     }
  111.     /**
  112.      * Prepare data that need to be send to Event Hub
  113.      *
  114.      * @param CheckoutOrderPlacedEvent $event
  115.      * @return array
  116.      */
  117.     public function prepareOrderData(CheckoutOrderPlacedEvent $event) : array
  118.     {
  119.         $orderId $event->getOrderId();
  120.         $order $event->getOrder();
  121.         $orderTime $order->getOrderDateTime()->format('Y-m-d\TH:i:s');
  122.         $customerId $event->getCustomerId();
  123.         $lineItems $event->getOrder()->getLineItems();
  124.         
  125.         $data = [];
  126.         foreach ($lineItems as $item) {
  127.             $data[] =[
  128.                 'data' => [
  129.                     'type' => 'purchase',
  130.                     'id' => $orderId,
  131.                     'attributes' => [
  132.                         'timestamp' => $orderTime,
  133.                         'customAttributes' => [
  134.                             'product' => $item->getLabel(),
  135.                             'itemCount' => $item->getQuantity()
  136.                         ]
  137.                     ],
  138.                     'relationships' => [
  139.                         'customer' => [
  140.                             'data' => [
  141.                                 [
  142.                                     'type' => 'demo-shop',
  143.                                     'id' => $customerId,
  144.                                 ]
  145.                             ],
  146.                         ],
  147.                     ],
  148.                 ]
  149.             ];
  150.         }
  151.         return $data;
  152.     }
  153. }