app/Plugin/StripePaymentGateway42/StripePaymentGatewayEvent.php line 304

Open in your IDE?
  1. <?php
  2. /*
  3. * Plugin Name : StripePaymentGateway42
  4. *
  5. * Copyright (C) 2018 Subspire Inc. All Rights Reserved.
  6. * http://www.subspire.co.jp/
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Plugin\StripePaymentGateway42;
  12. include_once(dirname(__FILE__).'/vendor/stripe/stripe-php/init.php');
  13. use Eccube\Application;
  14. use Eccube\Common\EccubeConfig;
  15. use Eccube\Event\TemplateEvent;
  16. use Eccube\Event\EventArgs;
  17. use Eccube\Entity\Payment;
  18. use Eccube\Event\EccubeEvents;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Plugin\StripePaymentGateway42\Repository\StripeConfigRepository;
  21. use Plugin\StripePaymentGateway42\Service\Method\StripeCreditCard;
  22. use Plugin\StripePaymentGateway42\Entity\StripeOrder;
  23. use Plugin\StripePaymentGateway42\Repository\StripeOrderRepository;
  24. use Plugin\StripePaymentGateway42\Entity\StripeCustomer;
  25. use Plugin\StripePaymentGateway42\Entity\StripeConfig;
  26. use Plugin\StripePaymentGateway42\Repository\StripeCustomerRepository;
  27. use Plugin\StripePaymentGateway42\StripeClient;
  28. use Eccube\Repository\Master\OrderStatusRepository;
  29. use Eccube\Entity\Master\OrderStatus;
  30. use Eccube\Entity\Order;
  31. use Eccube\Entity\Customer as Customer;
  32. use Doctrine\ORM\EntityManagerInterface;
  33. use Stripe\PaymentMethod;
  34. use Stripe\PaymentIntent;
  35. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  36. use Symfony\Component\DependencyInjection\ContainerInterface;
  37. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  38. use Eccube\Service\OrderHelper;
  39. use Plugin\StripePaymentGateway42\Service\Method\StripeKonbini;
  40. class StripePaymentGatewayEvent implements EventSubscriberInterface
  41. {
  42.     /**
  43.      * @var エラーメッセージ
  44.      */
  45.     private $errorMessage null;
  46.     /**
  47.      * @var 国際化
  48.      */
  49.     private static $i18n = array();
  50.     /**
  51.      * @var EntityManagerInterface
  52.      */
  53.     protected $entityManager;
  54.     /**
  55.      * @var StripeConfigRepository
  56.      */
  57.     protected $stripeConfigRepository;
  58.     /**
  59.      * @var OrderStatusRepository
  60.      */
  61.     private $orderStatusRepository;
  62.     /**
  63.      * @var StripeOrderRepository
  64.      */
  65.     private $stripeOrderRepository;
  66.     /**
  67.      * @var StripeCustomerRepository
  68.      */
  69.     private $stripeCustomerRepository;
  70.     /**
  71.      * @var string ロケール(jaかenのいずれか)
  72.      */
  73.     private $locale 'en';
  74.     /**
  75.      * @var EccubeConfig
  76.      */
  77.     protected $eccubeConfig;
  78.     /**
  79.      * @var Session
  80.      */
  81.     protected $session;
  82.     protected $container;
  83.     protected $util_service;    
  84.     public function __construct(
  85.         EccubeConfig $eccubeConfig,
  86.         StripeConfigRepository $stripeConfigRepository,
  87.         StripeOrderRepository $stripeOrderRepository,
  88.         StripeCustomerRepository $stripeCustomerRepository,
  89.         OrderStatusRepository $orderStatusRepository,
  90.         EntityManagerInterface $entityManager,
  91.         SessionInterface $session,
  92.         ContainerInterface $container
  93.     )
  94.     {
  95.         $this->eccubeConfig $eccubeConfig;
  96.         $this->locale=$this->eccubeConfig['locale'];
  97.         $this->stripeConfigRepository $stripeConfigRepository;
  98.         $this->stripeOrderRepository $stripeOrderRepository;
  99.         $this->stripeCustomerRepository $stripeCustomerRepository;
  100.         $this->orderStatusRepository $orderStatusRepository;
  101.         $this->entityManager $entityManager;
  102.         $this->session $session;
  103.         $this->container $container;
  104.         $this->util_service $this->container->get("plg_stripe_payment.service.util");        
  105.     }
  106.     /**
  107.      * @return array
  108.      */
  109.     public static function getSubscribedEvents()
  110.     {
  111.         return [
  112.             'Shopping/index.twig'   =>  'onShoppingTwig',
  113.             'Shopping/confirm.twig' => 'onShoppingConfirmTwig',
  114.             'Shopping/complete.twig' => 'onShoppingCompleteTwig',
  115.             // '@StripePaymentGateway42/default/Shopping/stripe_credit_card.twig' => 'onStripePayment',
  116.             'front.shopping.complete.initialize'=>'onFrontShoppingCompleteInitialize',
  117.             'Product/detail.twig'   =>  'onProductDetailTwig',
  118.             // 'index.twig'            =>  'onIndexTestTwig',
  119.             'Cart/index.twig'       =>  'onCartIndexTwig',
  120.             'Mypage/history.twig'   =>  'onMypageHistoryTwig',
  121.             '@admin/Order/index.twig' => 'onAdminOrderIndexTwig',
  122.             '@admin/Order/edit.twig' => 'onAdminOrderEditTwig',
  123.             // EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE    =>  'onShoppingComplete',
  124.             // EccubeEvents::MAIL_ORDER => 'sendOrderMailBefore',
  125.             // EccubeEvents::ADMIN_ORDER_MAIL_INDEX_INITIALIZE => 'adminOrderMailInitAfter',
  126.         ];
  127.     }
  128.     
  129.     public function onShoppingTwig(TemplateEvent $event){
  130.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  131.         $Payment $paymentRepository->findOneBy(['method_class' => StripeCreditCard::class]);
  132.         $Order $event->getParameter('Order');
  133.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  134.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  135.         $payment_id $Payment->getId();
  136.         $stripe_method_name $Payment->getMethod();
  137.         $event->setParameter("stripe_pay_id"$payment_id);
  138.         $event->setParameter("checkout_ga_enable"$checkout_ga_enable);
  139.         $event->setParameter("stripe_method_name"$stripe_method_name);
  140.         $KonbiniPayment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  141.         $event->setParameter("stripe_konbini_pay_id"$KonbiniPayment->getId());
  142.         $event->setParameter("konbini_method_name"$KonbiniPayment->getMethod());
  143.         $event->addSnippet('@StripePaymentGateway42/default/Shopping/paymethod_label.js.twig');
  144.     }
  145.     public function onShoppingConfirmTwig(TemplateEvent $event){
  146.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  147.         $Payment $paymentRepository->findOneBy(['method_class' => StripeCreditCard::class]);
  148.         $Order $event->getParameter('Order');
  149.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  150.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  151.         if($Payment && ($Order->getPayment()->getMethodClass() == StripeCreditCard::class 
  152.                 || $Order->getPayment()->getMethodClass() == StripeKonbini::class)){
  153.             $payment_id $Payment->getId();
  154.             $method_name $Payment->getMethod();
  155.             $event->setParameter("stripe_pay_id"$payment_id);
  156.             $event->setParameter('checkout_ga_enable'$checkout_ga_enable);
  157.             $event->setParameter("method_name"$method_name);
  158.             $event->setParameter("stripe_method_name"$method_name);
  159.             $event->addSnippet('@StripePaymentGateway42/default/Shopping/paymethod_label.js.twig');
  160.             $event->addSnippet('@StripePaymentGateway42/default/Shopping/shopping.js.twig');
  161.         }
  162.     }
  163.     public function onShoppingCompleteTwig(TemplateEvent $event) {
  164.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  165.         $Payment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  166.         $Order $event->getParameter('Order');
  167.         if($Payment && $Order->getPayment()->getMethodClass() == StripeKonbini::class) {
  168.             $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order' => $Order));
  169.             if ($stripeOrder) {
  170.                 $event->setParameter('voucher_url'$stripeOrder->getKonbiniVoucherUrl());
  171.                 $event->addSnippet('@StripePaymentGateway42/default/Shopping/complete_konbini.twig');
  172.             }
  173.         }
  174.     }
  175.     public function onMypageHistoryTwig(TemplateEvent $event) {
  176.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  177.         $Payment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  178.         $Order $event->getParameter('Order');
  179.         if($Payment && $Order->getPayment()->getMethodClass() == StripeKonbini::class) {
  180.             $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order' => $Order));
  181.             if ($stripeOrder) {
  182.                 $event->setParameter('voucher_url'$stripeOrder->getKonbiniVoucherUrl());
  183.                 $event->addSnippet('@StripePaymentGateway42/default/Mypage/history_konbini.twig');
  184.             }
  185.         }
  186.     }
  187.     public function onCartIndexTwig(TemplateEvent $event){
  188.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  189.         if($stripe_config->getCartGaEnable()){
  190.             $event->setParameter('stripeConfig'$stripe_config);
  191.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  192.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  193.             $event->addSnippet('@StripePaymentGateway42/default/Cart/index.js.twig');
  194.         }
  195.     }
  196.     // public function onIndexTestTwig(TemplateEvent $event){
  197.     //     $payrequest = [
  198.     //         'currency_code' =>  'jpy',
  199.     //         'label'         =>  'Pay Now',
  200.     //         'amount'        =>  0,
  201.     //     ];
  202.     //     $stripe_config = $this->entityManager->getRepository(StripeConfig::class)->get();
  203.     //     $event->setParameter('cartKey', "1_2");
  204.     //     $event->setParameter('payrequest', $payrequest);
  205.     //     $event->setParameter('stripeConfig', $stripe_config);
  206.     //     $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  207.     //     $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  208.     //     $event->addSnippet('@StripePaymentGateway42/default/index_test.twig');
  209.     // }
  210.     public function onProductDetailTwig(TemplateEvent $event){
  211.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  212.         if($stripe_config->getProdDetailGaEnable()){
  213.             $product $event->getParameter('Product');
  214.             $first_pc $product->getProductClasses()[0];
  215.             
  216.             $payrequest = [
  217.                 'currency_code' =>  \strtolower($first_pc->getCurrencyCode()),
  218.                 'label'         =>  trans('stripe_payment_gateway.payrequest.button_label'),
  219.                 'amount'        =>  $first_pc->getPrice02IncTax(),
  220.             ];
  221.             
  222.     
  223.             $event->setParameter('payrequest'$payrequest);
  224.             $event->setParameter('stripeConfig'$stripe_config);
  225.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  226.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  227.             $event->addSnippet('@StripePaymentGateway42/default/Product/detail.js.twig');
  228.         }
  229.     }
  230.     public function onStripePayment(TemplateEvent $event){
  231.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  232.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  233.         $event->setParameter('checkout_ga_enable'$checkout_ga_enable);
  234.         // $event->addAsset('StripePaymentGateway42/Resource/assets/css/base.css.twig');
  235.         // $event->addAsset('StripePaymentGateway42/Resource/assets/css/stripe_4.css.twig');
  236.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  237.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_payment.js.twig');
  238.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_elements.js.twig');
  239.     }
  240.     /**
  241.      * @param EventArgs $event
  242.      */
  243.     public function onFrontShoppingCompleteInitialize(EventArgs $event){
  244.         $Order=$event->getArgument('Order');
  245.         $this->session->getFlashBag()->set('stripe_payment_gateway_intent_id'false);
  246.         if($Order) {
  247.             if ($Order->getPayment()->getMethodClass() === StripeCreditCard::class) {
  248.                 $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order'=>$Order));
  249.                 if($stripeOrder) {
  250.                     $stripeChargeID $stripeOrder->getStripeChargeId();
  251.                     if (!empty($stripeChargeID)) {
  252.                         $Today = new \DateTime();
  253.                         $Order->setPaymentDate($Today);
  254.                         $OrderStatus $this->orderStatusRepository->find(OrderStatus::PAID);
  255.                         $Order->setOrderStatus($OrderStatus);
  256.                         $this->entityManager->persist($Order);
  257.                         $this->entityManager->flush($Order);
  258.                     }
  259.                 }
  260.             }
  261.         }
  262.     }
  263.     /**
  264.      * @param TemplateEvent $event
  265.      */
  266.     public function onAdminOrderIndexTwig(TemplateEvent $event)
  267.     {
  268.         // 表示対象の受注一覧を取得
  269.         $pagination $event->getParameter('pagination');
  270.         if (empty($pagination) || count($pagination) == 0)
  271.         {
  272.             return;
  273.         }
  274.         $OrderToSearch=array();
  275.         foreach ($pagination as $Order){
  276.             $OrderToSearch[] = $Order;
  277.         }
  278.         if (empty($OrderToSearch)) {
  279.             return;
  280.         }
  281.         $StripeOrders $this->stripeOrderRepository->findBy(array('Order'=>$OrderToSearch));
  282.         if (!$StripeOrders)
  283.         {
  284.             return;
  285.         }
  286.         $StripeOrdersMapping = array();
  287.         foreach($StripeOrders as $stripeOrder) {
  288.             $Order $stripeOrder->getOrder();
  289.             $OrderId $Order->getId();
  290.             $StripeConfig $this->stripeConfigRepository->getConfigByOrder($Order);
  291.             if($StripeConfig) {
  292.                 $publishableKey=$StripeConfig->publishable_key;
  293.                 if(strpos($publishableKey'live') !== false) {
  294.                     $isLive true;
  295.                 } else {
  296.                     $isLive false;
  297.                 }
  298.                 $dashboard_url $this->getStripeChargeDashboardLink($isLive) . $stripeOrder->getStripeChargeId();
  299.             } else {
  300.                 $dashboard_url "#" $stripeOrder->getStripeChargeId();
  301.             }
  302.             $order_edit_url $this->container->get('router')->generate('admin_order_edit', array('id' => $OrderId), UrlGeneratorInterface::ABSOLUTE_URL);
  303.             $StripeOrdersMapping[] = (object)[ 
  304.                 'order_edit_url' => $order_edit_url
  305.                 'charge_id' => $stripeOrder->getStripeChargeId(), 
  306.                 'dashboard_url' => $dashboard_url,
  307.                 'Order'     =>  $Order,
  308.             ];
  309.         }
  310.         $event->setParameter('StripeOrdersMapping'$StripeOrdersMapping);
  311. //        $event->setParameter('StripeChargeDashboardLink',$this->getStripeChargeDashboardLink());
  312.         $asset 'StripePaymentGateway42/Resource/assets/js/admin/order_index.js.twig';
  313.         $event->addAsset($asset);
  314.     }
  315.     /**
  316.      * @param TemplateEvent $event
  317.      */
  318.     public function onAdminOrderEditTwig(TemplateEvent $event)
  319.     {
  320.         // 表示対象の受注情報を取得
  321.         $Order $event->getParameter('Order');
  322.         if (!$Order)
  323.         {
  324.             return;
  325.         }
  326.         $StripeConfig $this->stripeConfigRepository->getConfigByOrder($Order);
  327.         // EC-CUBE支払方法の取得
  328.         $Payment $Order->getPayment();
  329.         if (!$Payment)
  330.         {
  331.             return;
  332.         }
  333.         if ($Order->getPayment()->getMethodClass() === StripeCreditCard::class) {
  334.             $StripeOrder $this->stripeOrderRepository->findOneBy(array('Order'=>$Order));
  335.             if (!$StripeOrder)
  336.             {
  337.                 return;
  338.             }
  339.             if($StripeOrder->getIsChargeRefunded()==&& $StripeOrder->getSelectedRefundOption()==&& $StripeOrder->getRefundedAmount()==0) {
  340.                 $StripeOrder->setSelectedRefundOption(1);
  341.                 $StripeOrder->setRefundedAmount($Order->getPaymentTotal());
  342.                 $this->entityManager->persist($StripeOrder);
  343.                 $this->entityManager->flush($StripeOrder);
  344.             }
  345. //            $StripeConfig = $this->stripeConfigRepository->get();
  346.             $publishableKey=$StripeConfig->publishable_key;
  347.             if(strpos($publishableKey'live') !== false) {
  348.                 $isLive true;
  349.             } else {
  350.                 $isLive false;
  351.             }
  352.             $event->setParameter('StripeConfig'$StripeConfig);
  353.             $event->setParameter('StripeOrder'$StripeOrder);
  354.             $event->setParameter('StripeChargeDashboardLink',$this->getStripeChargeDashboardLink($isLive));
  355.             $event->addSnippet('@StripePaymentGateway42/admin/Order/edit.twig');
  356.         }
  357.     }
  358.     private function getScriptDiskPath() {
  359.         return dirname(__FILE__).'/Resource/assets/js/stripe_' $this->locale '.js.twig';
  360.     }
  361.     private function makeScript() {
  362.         return;
  363.         $buff file_get_contents(dirname(__FILE__) . '/Resource/assets/js/stripe_js.twig');
  364.         $out_path $this->getScriptDiskPath();
  365.         $m = array();
  366.         preg_match_all('/\{\{ (\w+) \}\}/'$buff$m);
  367.         for ($i 0$i sizeof($m[0]); $i++) {
  368.             //$buff = str_replace($m[0][$i], self::getLocalizedString($m[1][$i], $this->locale), $buff);
  369.             if($m[1][$i]=='locale'){
  370.                 $buff str_replace($m[0][$i], $this->locale$buff);
  371.             }
  372.         }
  373.         file_put_contents($out_path$buff);
  374.     }
  375.     private function getStripeChargeDashboardLink($isLive){
  376.             if($isLive){
  377.                 $chargeDashboardLink='https://dashboard.stripe.com/payments/';
  378.             } else {
  379.                 $chargeDashboardLink='https://dashboard.stripe.com/test/payments/';
  380.         }
  381.         return $chargeDashboardLink;
  382.     }
  383.     public static function getLocalizedString($id$locale) {
  384.         if (! isset(self::$i18n[$locale])) {
  385.             $tmp_loader = new \Symfony\Component\Translation\Loader\YamlFileLoader();
  386.             $catalogue $tmp_loader->load(dirname(__FILE__) . "/Resource/locale/messages.$locale.yml"'ja''stripe');
  387.             self::$i18n[$locale] = $catalogue->all('stripe');
  388.         }
  389.         if (isset(self::$i18n[$locale][$id])) {
  390.             return self::$i18n[$locale][$id];
  391.         }
  392.         return '--';
  393.     }
  394.     private function isEligiblePaymentMethod(Payment $Payment,$total){
  395.         $min $Payment->getRuleMin();
  396.         $max $Payment->getRuleMax();
  397.         if (null !== $min && $total $min) {
  398.             return false;
  399.         }
  400.         if (null !== $max && $total $max) {
  401.             return false;
  402.         }
  403.         return true;
  404.     }
  405.     
  406. }