custom/plugins/KlarnaPayment/src/Components/EventListener/ExpressButtonEventListener.php line 70

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace KlarnaPayment\Components\EventListener;
  4. use KlarnaPayment\Components\ConfigReader\ConfigReaderInterface;
  5. use KlarnaPayment\Components\Extension\TemplateData\ExpressDataExtension;
  6. use KlarnaPayment\Components\Helper\PaymentHelper\PaymentHelperInterface;
  7. use KlarnaPayment\Components\Struct\Configuration;
  8. use KlarnaPayment\Installer\Modules\PaymentMethodInstaller;
  9. use Shopware\Core\Checkout\Customer\Event\GuestCustomerRegisterEvent;
  10. use Shopware\Core\Checkout\Payment\PaymentMethodCollection;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  14. use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
  15. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService;
  16. use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepository;
  17. use Shopware\Core\System\SalesChannel\SalesChannel\AbstractContextSwitchRoute;
  18. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  19. use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
  20. use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
  21. use Shopware\Storefront\Page\Checkout\Register\CheckoutRegisterPageLoadedEvent;
  22. use Shopware\Storefront\Page\PageLoadedEvent;
  23. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  24. class ExpressButtonEventListener implements EventSubscriberInterface
  25. {
  26.     private const ENVIRONMENT_PLAYGROUND 'playground';
  27.     private const ENVIRONMENT_PRODUCTION 'production';
  28.     /** @var PaymentHelperInterface */
  29.     private $paymentHelper;
  30.     /** @var ConfigReaderInterface */
  31.     private $configReader;
  32.     /** @var AbstractContextSwitchRoute */
  33.     private $contextSwitchRoute;
  34.     /** @var SalesChannelRepository */
  35.     private $paymentMethodsRepository;
  36.     public function __construct(
  37.         PaymentHelperInterface $paymentHelper,
  38.         ConfigReaderInterface $configReader,
  39.         AbstractContextSwitchRoute $contextSwitchRoute,
  40.         SalesChannelRepository $paymentMethodsRepository
  41.     ) {
  42.         $this->paymentHelper            $paymentHelper;
  43.         $this->configReader             $configReader;
  44.         $this->contextSwitchRoute       $contextSwitchRoute;
  45.         $this->paymentMethodsRepository $paymentMethodsRepository;
  46.     }
  47.     public static function getSubscribedEvents(): array
  48.     {
  49.         return [
  50.             CheckoutRegisterPageLoadedEvent::class => 'addExpressTemplateData',
  51.             CheckoutCartPageLoadedEvent::class     => 'addExpressTemplateData',
  52.             OffcanvasCartPageLoadedEvent::class    => 'addExpressTemplateData',
  53.             GuestCustomerRegisterEvent::class      => 'changeDefaultPaymentMethod',
  54.         ];
  55.     }
  56.     /**
  57.      * @param CheckoutCartPageLoadedEvent|CheckoutRegisterPageLoadedEvent|OffcanvasCartPageLoadedEvent $event
  58.      */
  59.     public function addExpressTemplateData(PageLoadedEvent $event): void
  60.     {
  61.         $salesChannelContext $event->getSalesChannelContext();
  62.         if (!$this->paymentHelper->isKlarnaPaymentsEnabled($salesChannelContext)) {
  63.             return;
  64.         }
  65.         $configuration $this->configReader->read($salesChannelContext->getSalesChannel()->getId());
  66.         if (!$configuration->get('isKlarnaExpressActive'false)) {
  67.             return;
  68.         }
  69.         $locale  $this->paymentHelper->getSalesChannelLocale($salesChannelContext);
  70.         $country $this->paymentHelper->getShippingCountry($salesChannelContext);
  71.         $testMode    = !empty($configuration->get('testMode'));
  72.         $environment $testMode self::ENVIRONMENT_PLAYGROUND self::ENVIRONMENT_PRODUCTION;
  73.         $user        $this->getApiUsername($salesChannelContext$configuration$testMode);
  74.         $underscorePosition strpos($user'_');
  75.         if ($underscorePosition === false) {
  76.             return;
  77.         }
  78.         $templateData = new ExpressDataExtension(
  79.             substr($user0$underscorePosition),
  80.             $environment,
  81.             substr_replace($locale->getCode(), (string) $country->getIso(), 32),
  82.             $configuration->get('klarnaExpressTheme''default'),
  83.             $configuration->get('klarnaExpressLabel''default'),
  84.             $configuration->get('klarnaExpressCssClass'''),
  85.             $configuration->get('klarnaExpressShape''default')
  86.         );
  87.         $event->getPage()->addExtension(ExpressDataExtension::EXTENSION_NAME$templateData);
  88.     }
  89.     public function changeDefaultPaymentMethod(GuestCustomerRegisterEvent $event): void
  90.     {
  91.         $context $event->getSalesChannelContext();
  92.         $paymentMethod $this->getFirstKlarnaPaymentMethodId($context);
  93.         if ($paymentMethod === null) {
  94.             return;
  95.         }
  96.         $customer $context->getCustomer();
  97.         if ($customer === null) {
  98.             return;
  99.         }
  100.         $this->contextSwitchRoute->switchContext(
  101.             new RequestDataBag([
  102.                 SalesChannelContextService::PAYMENT_METHOD_ID => $paymentMethod,
  103.             ]),
  104.             $context
  105.         );
  106.     }
  107.     private function getFirstKlarnaPaymentMethodId(SalesChannelContext $context): ?string
  108.     {
  109.         $validPaymentMethods = [
  110.             PaymentMethodInstaller::KLARNA_PAY_LATER,
  111.             PaymentMethodInstaller::KLARNA_FINANCING,
  112.             PaymentMethodInstaller::KLARNA_DIRECT_DEBIT,
  113.             PaymentMethodInstaller::KLARNA_DIRECT_BANK_TRANSFER,
  114.             PaymentMethodInstaller::KLARNA_CREDIT_CARD,
  115.             PaymentMethodInstaller::KLARNA_PAY_NOW,
  116.         ];
  117.         $criteria = (new Criteria())
  118.             ->addFilter(new EqualsFilter('active'true))
  119.             ->addSorting(new FieldSorting('position'));
  120.         /** @var PaymentMethodCollection $availablePaymentMethods */
  121.         $availablePaymentMethods $this->paymentMethodsRepository
  122.             ->search($criteria$context)
  123.             ->getEntities();
  124.         $availablePaymentMethods $availablePaymentMethods->filterByActiveRules($context);
  125.         foreach ($validPaymentMethods as $validPaymentMethod) {
  126.             if ($availablePaymentMethods->has($validPaymentMethod)) {
  127.                 return $validPaymentMethod;
  128.             }
  129.         }
  130.         return null;
  131.     }
  132.     /**
  133.      * We are determining the user by the configuration priorizing the config made onto the saleschannel without inheritation
  134.      */
  135.     private function getApiUsername(SalesChannelContext $salesChannelContextConfiguration $configurationbool $testMode): string
  136.     {
  137.         $salesChannelConfiguration $this->configReader->read(
  138.             $salesChannelContext->getSalesChannel()->getId(),
  139.             false
  140.         );
  141.         $configKey $testMode 'testApiUsername' 'apiUsername';
  142.         foreach ([$salesChannelConfiguration$configuration] as $config) {
  143.             if ($user $config->get($configKey)) {
  144.                 return $user;
  145.             }
  146.             if ($user $config->get($configKey 'US')) {
  147.                 return $user;
  148.             }
  149.         }
  150.         return '';
  151.     }
  152. }