<?php
declare(strict_types=1);
/*
* (c) shopware AG <info@shopware.com>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Swag\AmazonPay\Storefront\EventListeners;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Swag\AmazonPay\Installer\PaymentMethodInstaller;
use Swag\AmazonPay\Storefront\Page\Extension\AmazonPayConfirmExtension;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class AmazonPayConfirmEventListener implements EventSubscriberInterface
{
/**
* @var SessionInterface
*/
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
CheckoutConfirmPageLoadedEvent::class => 'onLoadConfirmPage',
];
}
public function onLoadConfirmPage(CheckoutConfirmPageLoadedEvent $event): void
{
// Only for AmazonPay!
if ($event->getSalesChannelContext()->getPaymentMethod()->getId() !== PaymentMethodInstaller::AMAZON_PAYMENT_ID) {
// Remove the "on hold" checkout session id from the session just to clear things up.
// Will be automatically set again if Amazon Pay is active
$this->session->remove('swag-amazon-pay.checkout-session-id');
return;
}
// Use URL param for checkout determination first and fallback to the value inside the session.
$checkoutSessionId = (string) $event->getRequest()->query->get('amazonPayCheckoutId', $this->session->get('swag-amazon-pay.checkout-session-id'));
$isOneClickCheckout = $event->getRequest()->query->getBoolean('oneClickCheckout');
// No session id but one click checkout requested?
if (!$checkoutSessionId && $isOneClickCheckout) {
return;
}
// Keep the checkoutSessionId on hold for the case that the customer e.g changes the shipping method on the confirm page or returns to confirm page later.
if ($isOneClickCheckout) {
$this->session->set('swag-amazon-pay.checkout-session-id', $checkoutSessionId);
$this->addConfirmPageExtension($event, $checkoutSessionId, true);
return;
}
// Reset from One-Click checkout to the regular Amazon Pay checkout
$this->session->remove('swag-amazon-pay.checkout-session-id');
}
private function addConfirmPageExtension(
CheckoutConfirmPageLoadedEvent $event,
?string $checkoutSessionId,
bool $isOneClickCheckout
): void {
$confirmExtension = new AmazonPayConfirmExtension();
$confirmExtension->setCheckoutSessionId($checkoutSessionId);
$confirmExtension->setIsOneClickCheckout($isOneClickCheckout);
$event->getPage()->addExtension(AmazonPayConfirmExtension::EXTENSION_NAME, $confirmExtension);
}
}