app/Plugin/AmazonPayV2_42/Controller/AmazonRedirectController.php line 234

Open in your IDE?
  1. <?php
  2. /*
  3.  * Amazon Pay V2 for EC-CUBE4.2
  4.  * Copyright(c) 2023 EC-CUBE CO.,LTD. all rights reserved.
  5.  *
  6.  * https://www.ec-cube.co.jp/
  7.  *
  8.  * This program is not free software.
  9.  * It applies to terms of service.
  10.  *
  11.  */
  12. namespace Plugin\AmazonPayV2_42\Controller;
  13. use Eccube\Controller\AbstractController;
  14. use Eccube\Repository\CustomerRepository;
  15. use Eccube\Repository\ClassCategoryRepository;
  16. use Eccube\Repository\ProductRepository;
  17. use Eccube\Repository\ProductClassRepository;
  18. use Eccube\Common\EccubeConfig;
  19. use Eccube\Service\CartService;
  20. use Eccube\Service\OrderHelper;
  21. use Eccube\Service\PurchaseFlow\PurchaseContext;
  22. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  23. use Plugin\AmazonPayV2_42\Repository\ConfigRepository;
  24. use Plugin\AmazonPayV2_42\Service\AmazonOrderHelper;
  25. use Plugin\AmazonPayV2_42\Service\AmazonRequestService;
  26. use Plugin\AmazonPayV2_42\Service\AmazonIPNService;
  27. use Symfony\Component\Routing\Annotation\Route;
  28. use Symfony\Component\HttpFoundation\ParameterBag;
  29. use Symfony\Component\HttpFoundation\Request;
  30. use Symfony\Component\HttpFoundation\Response;
  31. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  32. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  33. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  34. class AmazonRedirectController extends AbstractController
  35. {
  36.     /**
  37.      * @var string プロファイル情報キー
  38.      */
  39.     private $sessionAmazonProfileKey 'amazon_pay_v2.profile';
  40.     /**
  41.      * @var string プロファイル情報キー
  42.      */
  43.     private $sessionAmazonCheckoutSessionIdKey 'amazon_pay_v2.checkout_session_id';
  44.     /**
  45.      * @var string shippingを更新するか
  46.      */
  47.     private $sessionIsShippingRefresh 'amazon_pay_v2.is_shipping_refresh';
  48.     /**
  49.      * @var string Amazonログインステート
  50.      */
  51.     private $sessionAmazonLoginStateKey 'amazon_pay_v2.amazon_login_state';
  52.     /**
  53.      * @var CartService
  54.      */
  55.     protected $cartService;
  56.     /**
  57.      * @var ConfigRepository
  58.      */
  59.     protected $configRepository;
  60.     /**
  61.      * @var AmazonRequestService
  62.      */
  63.     protected $amazonRequestService;
  64.     /**
  65.      * @var AmazonIPNService
  66.      */
  67.     protected $amazonIPNService;
  68.     public function __construct(
  69.         PurchaseFlow $cartPurchaseFlow,
  70.         OrderHelper $orderHelper,
  71.         CartService $cartService,
  72.         CustomerRepository $customerRepository,
  73.         ClassCategoryRepository $classCategoryRepository,
  74.         ProductRepository $productRepository,
  75.         ProductClassRepository $productClassRepository,
  76.         ConfigRepository $configRepository,
  77.         AmazonOrderHelper $amazonOrderHelper,
  78.         AmazonRequestService $amazonRequestService,
  79.         AmazonIPNService $amazonIPNService,
  80.         ParameterBag $parameterBag,
  81.         EccubeConfig $eccubeConfig,
  82.         TokenStorageInterface $tokenStorage
  83.     ) {
  84.         $this->purchaseFlow $cartPurchaseFlow;
  85.         $this->orderHelper $orderHelper;
  86.         $this->cartService $cartService;
  87.         $this->customerRepository $customerRepository;
  88.         $this->classCategoryRepository $classCategoryRepository;
  89.         $this->productRepository $productRepository;
  90.         $this->productClassRepository $productClassRepository;
  91.         $this->configRepository $configRepository;
  92.         $this->amazonOrderHelper $amazonOrderHelper;
  93.         $this->amazonRequestService $amazonRequestService;
  94.         $this->amazonIPNService $amazonIPNService;
  95.         $this->parameterBag $parameterBag;
  96.         $this->eccubeConfig $eccubeConfig;
  97.         $this->tokenStorage $tokenStorage;
  98.         $this->Config $configRepository->get();
  99.     }
  100.     /**
  101.      * @Route("/amazon_checkout_review", name="amazon_checkout_review")
  102.      *
  103.      * @param Request $request
  104.      *
  105.      * @return RedirectResponse
  106.      */
  107.     public function amazonCheckoutReview(Request $request)
  108.     {
  109.         logs('amazon_pay_v2')->info('AmazonRedirect::amazonCheckoutReview start.');
  110.         try {
  111.             $checkoutSession $this->amazonRequestService->getCheckoutSession($request->get('amazonCheckoutSessionId'));
  112.             $buyer $checkoutSession->buyer;
  113.             // buyerIdがnullの場合は例外スロー
  114.             if ($buyer->buyerId == null) {
  115.                 throw new \Exception("** buyerIdがnullです.処理を中断します. **");
  116.             }
  117.         } catch (\Exception $e) {
  118.             logs('amazon_pay_v2')->error($e->getMessage() . ' amazonCheckoutSessionId = ' $request->get('amazonCheckoutSessionId'));
  119.             return $this->redirectToRoute('shopping_error');
  120.         }
  121.         $cartKey $request->get('cart');
  122.         $this->cartService->setPrimary($cartKey);
  123.         $this->cartService->save();
  124.         // 自動ログイン
  125.         if (
  126.             !$this->isGranted('ROLE_USER') && $this->Config->getAutoLogin() == $this->eccubeConfig['amazon_pay_v2']['toggle']['on'] &&
  127.             $Customer $this->customerRepository->getNonWithdrawingCustomers(['v2_amazon_user_id' => $buyer->buyerId])
  128.         ) {
  129.             $token = new UsernamePasswordToken($Customer[0], 'customer', ['ROLE_USER']);
  130.             $this->tokenStorage->setToken($token);
  131.             $request->getSession()->migrate(true);
  132.             $this->cartService->mergeFromPersistedCart();
  133.             foreach ($this->cartService->getCarts() as $Cart) {
  134.                 $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$Customer[0]));
  135.             }
  136.             $this->cartService->save();
  137.         }
  138.         if ($this->isGranted('IS_AUTHENTICATED_FULLY') && $this->Config->getOrderCorrect() == $this->eccubeConfig['amazon_pay_v2']['toggle']['on']) {
  139.             $Customer $this->getUser();
  140.             $revise_flg false;
  141.             // 名前補正
  142.             $name02 $Customer->getName02();
  143.             if (empty($name02) || $name02 == ' ') {
  144.                 $arrFixName $this->amazonOrderHelper->reviseName($Customer->getName01());
  145.                 if (!empty($arrFixName)) {
  146.                     $Customer->setName01($arrFixName['name01'])
  147.                         ->setName02($arrFixName['name02']);
  148.                     $revise_flg true;
  149.                     logs('amazon_pay_v2')->info('*** 会員情報 名前補正 *** customer_id = ' $Customer->getId());
  150.                 }
  151.             }
  152.             // フリガナ補正
  153.             $kana01 $Customer->getKana01();
  154.             $kana02 $Customer->getKana02();
  155.             if ((empty($kana01) || $kana01 === ' ') && (empty($kana02) || $kana02 === ' ')) {
  156.                 $arrFixKana $this->amazonOrderHelper->reviseKana($Customer->getName01(), $Customer->getName02(), $Customer->getEmail());
  157.                 if (!empty($arrFixKana)) {
  158.                     $Customer->setKana01($arrFixKana['kana01'])
  159.                         ->setKana02($arrFixKana['kana02']);
  160.                     $revise_flg true;
  161.                     logs('amazon_pay_v2')->info('*** 会員情報 フリガナ補正 *** customer_id = ' $Customer->getId());
  162.                 }
  163.             }
  164.             if ($revise_flg) {
  165.                 $this->entityManager->persist($Customer);
  166.                 $this->entityManager->flush();
  167.             }
  168.         }
  169.         // AmazonのユーザIDをセッションに保存
  170.         $this->session->set($this->sessionAmazonProfileKeyserialize($buyer));
  171.         $this->session->set($this->sessionAmazonCheckoutSessionIdKey$request->get('amazonCheckoutSessionId'));
  172.         // shippingの更新フラグを保存
  173.         $this->session->set($this->sessionIsShippingRefreshtrue);
  174.         logs('amazon_pay_v2')->info('AmazonRedirect::index end.');
  175.         return $this->redirectToRoute('amazon_pay_shopping', []);
  176.     }
  177.     /**
  178.      * @Route("/amazon_instant_payment_notifications", name="instant_payment_notifications")
  179.      */
  180.     public function instantPaymentNotifications(Request $request)
  181.     {
  182.         logs('amazon_pay_v2')->info('AmazonRedirect::instantPaymentNotifications start.');
  183.         $json $request->getContent();
  184.         $content json_decode($jsontrue);
  185.         if (isset($content['Type']) && $content['Type'] == 'Notification') {
  186.             $arrParam json_decode($content['Message'], true);
  187.             $this->amazonIPNService->mainProcess($arrParam);
  188.         } else {
  189.             throw new \Exception('IPN Type Error.');
  190.         }
  191.         logs('amazon_pay_v2')->info('AmazonRedirect::instantPaymentNotifications end.');
  192.         return new Response();
  193.     }
  194.     /**
  195.      * @Route("/mypage/login_with_amazon", name="login_with_amazon")
  196.      */
  197.     public function loginWithAmazon(Request $request)
  198.     {
  199.         logs('amazon_pay_v2')->info('AmazonRedirect::loginWithAmazon start.');
  200.         $route 'homepage';
  201.         $buyerToken $request->get('buyerToken');
  202.         $state $request->get('state');
  203.         $sessionState =$this->session->get($this->sessionAmazonLoginStateKey);
  204.         if (!isset($buyerToken) || !isset($state)) {
  205.             throw new AccessDeniedHttpException('不正なアクセスです。');
  206.         }
  207.         if ($state !== $sessionState) {
  208.             $this->addError('amazon_pay_v2.front.error','amazon_pay_v2');
  209.             $route 'mypage_login';
  210.             return $this->redirectToRoute($route);
  211.         }
  212.         $this->session->remove($this->sessionAmazonLoginStateKey);
  213.         try {
  214.             // ログイン済みでなければ処理
  215.             if (!$this->isGranted('ROLE_USER')) {
  216.                 $buyer $this->amazonRequestService->getBuyer($request->get('buyerToken'));
  217.                 $buyerId $buyer->buyerId;
  218.                 $isLogin $this->amazonRequestService->loginWithBuyerId($request$buyerId);
  219.                 if (!$isLogin) {
  220.                     // Buyerが一致する会員が存在しない場合はエラー
  221.                     $this->addError('amazon_pay_v2.front_mypage_fail_to_login','amazon_pay_v2');
  222.                     $route 'mypage_login';
  223.                 }
  224.             }
  225.         } catch (\Exception $e) {
  226.             logs('amazon_pay_v2')->info($e->getMessage());
  227.             $this->addError('amazon_pay_v2.front.error','amazon_pay_v2');
  228.             $route 'mypage_login';
  229.         }
  230.         logs('amazon_pay_v2')->info('AmazonRedirect::loginWithAmazon end.');
  231.         return $this->redirectToRoute($route);
  232.     }
  233. }