<?php
namespace EcBasicTheme\Storefront\Event\Subscriber;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Models\Order\Repository;
use Shopware\Models\Order\Order;
use Psr\Log\LoggerInterface;
class EventHubSubscriber implements EventSubscriberInterface
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* StorefrontRenderEventSubscriber constructor.
* @param SystemConfigService $systemConfigService
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'onPurchase'
];
}
/**
* On purchase send data to Event Hub
*
* @param CheckoutOrderPlacedEvent $event
* @return void
*/
public function onPurchase(CheckoutOrderPlacedEvent $event)
{
$eventHub = 'cdp-transaction';
$eventHubUrl = 'https://dymde-dem-shr-evhns.servicebus.windows.net';
$sasKeyValue = 'VS4pzl27L09Ds6ve52Y2z2v3IXnOG92W3+AEhC2CYKA=';
$sasKeyName = 'cdp-transaction-auth';
if(!empty($event) && $orderId = $event->getOrderId()){
$token = $this->generateSasToken($eventHubUrl, $sasKeyName, $sasKeyValue);
$url = $eventHubUrl . '/' . $eventHub . '/messages?timeout=60&api-version=2014-01';
$productsData = $this->prepareOrderData($event);
foreach($productsData as $product)
{
$responseCode = $this->executeCurl($url, json_encode($product), $token);
$this->logger->info('Event sent to EvenHub', [
'responseCode' => $responseCode['http_code'],
'orderId' => $orderId,
'product' => $product['data']['attributes']['customAttributes']['product'],
]);
}
}
}
/**
* generate SAS token for Event Hub
*
* @param string $uri
* @param string $sasKeyName
* @param string $sasKeyValue
* @return string
*/
public function generateSasToken($uri, $sasKeyName, $sasKeyValue) : string
{
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$week = 60*60*24*7;
$expires = $expires + $week;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256',
$toSign, $sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig=" . $signature . "&se=" . $expires . "&skn=". $sasKeyName;
return $token;
}
/**
* Execute cURL request for Event Hub
*
* @param string $url
* @param string $data
* @param string $token
* @return array
*/
public function executeCurl($url, $data, $token) : array
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POSTFIELDS => $data,
CURLINFO_HEADER_OUT => true,
CURLOPT_HTTPHEADER => array(
'Authorization: ' . $token,
'Content-Type: application/atom+xml;type=entry;charset=utf-8',
'Host: dymde-dem-shr-evhns.servicebus.windows.net',
),
));
$response = curl_exec($curl);
// $error = curl_errno($curl);
$code = curl_getinfo($curl);
// echo '<pre>'; print_r($code); die;
curl_close($curl);
return $code;
}
/**
* Prepare data that need to be send to Event Hub
*
* @param CheckoutOrderPlacedEvent $event
* @return array
*/
public function prepareOrderData(CheckoutOrderPlacedEvent $event) : array
{
$orderId = $event->getOrderId();
$order = $event->getOrder();
$orderTime = $order->getOrderDateTime()->format('Y-m-d\TH:i:s');
$customerId = $event->getCustomerId();
$lineItems = $event->getOrder()->getLineItems();
$data = [];
foreach ($lineItems as $item) {
$data[] =[
'data' => [
'type' => 'purchase',
'id' => $orderId,
'attributes' => [
'timestamp' => $orderTime,
'customAttributes' => [
'product' => $item->getLabel(),
'itemCount' => $item->getQuantity()
]
],
'relationships' => [
'customer' => [
'data' => [
[
'type' => 'demo-shop',
'id' => $customerId,
]
],
],
],
]
];
}
return $data;
}
}