<?php
namespace EcBasicTheme\Storefront\Event\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\Event\DataMappingEvent;
use Shopware\Core\Checkout\Customer\Event\CustomerRegisterEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
class CXPDataSubscriber implements EventSubscriberInterface
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* StorefrontRenderEventSubscriber constructor.
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public static function getSubscribedEvents(): array
{
return [
CustomerRegisterEvent::class => 'onRegister',
CustomerEvents::CUSTOMER_ADDRESS_WRITTEN_EVENT => 'onCustomerAddressUpdate',
CustomerEvents::CUSTOMER_WRITTEN_EVENT => 'onCustomerUpdate'
];
}
/**
* Send Customer data to CDP when he register
*
* @param CustomerRegisterEvent $event
* @return void
*/
public function onRegister(CustomerRegisterEvent $event){
$customer = $event-> getCustomer();
$customerNumber = $customer->getId();
$salutation = $this->getSalutation($customer->getSalutationId());
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$email =$customer->getEmail();
$title = $customer->getTitle();
$address = $customer->getDefaultBillingAddress();
$street = $address->getStreet();
$zipcode = $address->getZipcode();
$city = $address->getCity();
$countryId = $address->getCountryId();
$countryState = $this->getCountryState($address->getCountryStateId());
$attributes = [
'salutation' => $salutation,
'title' => $title,
'firstname' => $firstName,
'lastname' => $lastName,
'email' => [
'address' => $email,
'permission' => 'Unknown',
'trackingPermission' => 'Granted'
],
'address' => [
'line1' => $street,
'city' => $city,
'postalcode' => $zipcode,
'province' => $countryState,
'country' => 'germany',
'line3' => 'DEMOSHOP'
],
'identifiers' => [
[
'type' => 'email',
'id' => $email
]
]
];
if (!empty($customer->getBirthday())) {
$attributes['birthdate'] = $customer->getBirthday()->format('Y-m-d');
}
$data = [
'data' => [
'type' => 'demo-shop',
'id' => $customerNumber,
'attributes' => $attributes
]
];
$response= $this->executeCurl(json_encode($data));
return true;
}
/**
* Send data to CDP when customer update address
*
* @param EntityWrittenEvent $event
* @return void
*/
public function onCustomerAddressUpdate(EntityWrittenEvent $event)
{
$input = $event->getPayloads()[0];
//we doing this only on update not on create, this event is called everytime customer is saved.
//so it is called when we register customer too, this prevents it from being executed in that case
if(empty($input) || array_key_exists('createdAt', $input))
{
return true;
}
$customerNumber = $input['customerId'];
$salutation = $this->getSalutation($input['salutationId']);
$firstName = $input['firstName'];
$lastName = $input['lastName'];
$zipcode = $input['zipcode'];
$street = $input['street'];
$city = $input['city'];
$countryState = $this->getCountryState($input['countryStateId']);
$data = [
'data' => [
'type' => 'demo-shop',
'id' => $customerNumber,
'attributes' => [
'salutation' => $salutation,
'firstname' => $firstName,
'lastname' => $lastName,
'address' => [
'line1' => $street,
'city' => $city,
'postalcode' => $zipcode,
'province' => $countryState,
'country' => 'germany'
]
]
]
];
$response = $this->executeCurl(json_encode($data));
return true;
}
/**
* Send data to CDP when customer update his email
*
* @param EntityWrittenEvent $event
* @return void
*/
public function onCustomerUpdate(EntityWrittenEvent $event)
{
$input = $event->getPayloads()[0];
//we doing this only on update not on create, this event is called everytime customer is saved.
//so it is called when we register customer too, this prevents it from being executed in that case
if(empty($input) || array_key_exists('createdAt', $input))
{
return true;
}
$customerNumber = $input['id'];
$data = [];
//if we have email, then we know it is email update change in shopware, otherwise it is update of personal info
if(array_key_exists("email",$input)) {
$email = $input['email'];
$data = [
'data' => [
'type' => 'demo-shop',
'id' => $customerNumber,
'attributes' => [
'email' => [
'address' => $email,
'permission' => 'Unknown',
'trackingPermission' => 'Granted'
],
'identifiers' => [
[
'type' => 'email',
'id' => $email
]
]
]
]
];
} elseif(array_key_exists("firstName",$input)) {
$salutation = $this->getSalutation($input['salutationId']);
$firstName = $input['firstName'];
$lastName = $input['lastName'];
$birthday = is_null($input['birthday']) ? '' : $input['birthday']->format('Y-m-d');
$data = [
'data' => [
'type' => 'demo-shop',
'id' => $customerNumber,
'attributes' => [
'salutation' => $salutation,
'firstname' => $firstName,
'lastname' => $lastName,
'birthdate' => $birthday
]
]
];
}
if(!empty($data)) {
$response = $this->executeCurl(json_encode($data));
}
return true;
}
/**
* Execute cURL request for CDP
*
* @param string $data
* @return string
*/
public function executeCurl($data, $method = "POST"): string
{
$curl = curl_init();
// echo '<pre>'; print_r($data); die;
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://cxp-api-dem.dymatrix.online/722a702302a7ed004cccb5b9f606c25c/cdp/api/customer?api-version=v1',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
'cxp-subscription-key: f7aa444af99f41e2890f7f223ee29262',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
// echo '<pre>'; print_r($data);
// echo '<pre>'; print_r($response); die;
curl_close($curl);
if($response) {
$data = json_decode($response);
if(!empty($data->data->id)) {
$this->logger->info('CDP Customer API: ', [
'id' => $data->data->id,
'responseCode' => $info['http_code'],
]);
}
}
return $response;
}
/**
* Get salutation by id.
*
* @param string $salutation
* @return string
*/
public function getSalutation($salutation): string
{
if ($salutation == 'fcc8e0d6a4764bbba6e49791614f0ae1') {
$salutation = 'Keine Angabe';
} elseif ($salutation == 'bc965dc8237d4a448a9e981663e48a45') {
$salutation = 'Frau';
} elseif ($salutation == '13905f90029e4f638ac122ccb762aff4') {
$salutation = 'Herr';
}
return $salutation;
}
/**
* Get country name by id.
*
* @param string $countryState
* @return string
*/
public function getCountryState($countryState): string
{
switch($countryState) {
case '0ce33d413c904e92acc79c69f8a08d15':
$countryState = 'Hamburg';
break;
case 'f3b08fd5d0a04ba59ba226c85bf59738':
$countryState = 'Bremen';
break;
case 'd712d274bd574428a10d1e2d025e7ab6':
$countryState = 'Niedersachsen';
break;
case 'd230986e91e8441c85e994c0be34089e':
$countryState = 'Mecklenburg-Vorpommern';
break;
case 'd04dbef41d454c7eb6deb84a0c06a699':
$countryState = 'Brandenburg';
break;
case 'b6c91701b703472c8a73e8df30cad101':
$countryState = 'Nordhein-Westfalen';
break;
case '9fc46966f0234e9f8530186f4642bb3c':
$countryState = 'Schleswig-Holstein';
break;
case '98def0aeb554407da2969936b41d34c2':
$countryState = 'Rheinland-Pfalz';
break;
case '744f1bd0196a4156a8dc8f92605b6777':
$countryState = 'Sachsen-Anhalt';
break;
case '6899f042a86c47c298789f12e44e6313':
$countryState = 'Sachsen';
break;
case '670f4eda6c034eb49d729c71a2a4905d':
$countryState = 'Saarland';
break;
case '574d6df925484487a1d0253dc9b1ab6f':
$countryState = 'Bayern';
break;
case '24e210f44daf447db2173b7c9304b2ec':
$countryState = 'Baden-Württemberg ';
break;
case '208691df26cc4788a2848e5f79fa2917':
$countryState = 'Berlin';
break;
case '147f15c078424485b15a5a1671be7096':
$countryState = 'Thüringen';
break;
case 'fce8394d0db04a8f9ecf7e6d82aa9e0c':
$countryState = 'Hessen';
break;
default:
$countryState = '';
}
return $countryState;
}
}