app/Plugin/StripePaymentGateway42/StripePaymentGatewayEvent.php line 239

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 Psr\Container\ContainerInterface;
  36. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  37. use Eccube\Service\OrderHelper;
  38. use Plugin\StripePaymentGateway42\Service\Method\StripeKonbini;
  39. use Plugin\StripePaymentGateway42\Service\UtilService;
  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(ContainerInterface $container){
  85.         $this->container $container;
  86.         $this->eccubeConfig $this->container->get('Eccube\Common\EccubeConfig');
  87.         $this->entityManager $this->container->get('doctrine.orm.entity_manager');
  88.         $this->locale=$this->eccubeConfig['locale'];
  89.         $this->stripeConfigRepository $this->entityManager->getRepository(StripeConfig::class);
  90.         $this->stripeOrderRepository $this->entityManager->getRepository(StripeOrder::class);
  91.         $this->stripeCustomerRepository $this->entityManager->getRepository(StripeCustomer::class);
  92.         $this->orderStatusRepository $this->entityManager->getRepository(OrderStatus::class);
  93.         $this->session $this->container->get('session')->getSession();
  94.         $this->util_service $this->util_service $this->container->get(UtilService::class);
  95.     }
  96.     /**
  97.      * @return array
  98.      */
  99.     public static function getSubscribedEvents()
  100.     {
  101.         return [
  102.             'Shopping/index.twig'   =>  'onShoppingTwig',
  103.             'Shopping/confirm.twig' => 'onShoppingConfirmTwig',
  104.             'Shopping/complete.twig' => 'onShoppingCompleteTwig',
  105.             // '@StripePaymentGateway42/default/Shopping/stripe_credit_card.twig' => 'onStripePayment',
  106.             'front.shopping.complete.initialize'=>'onFrontShoppingCompleteInitialize',
  107.             'Product/detail.twig'   =>  'onProductDetailTwig',
  108.             // 'index.twig'            =>  'onIndexTestTwig',
  109.             'Cart/index.twig'       =>  'onCartIndexTwig',
  110.             'Mypage/history.twig'   =>  'onMypageHistoryTwig',
  111.             '@admin/Order/index.twig' => 'onAdminOrderIndexTwig',
  112.             '@admin/Order/edit.twig' => 'onAdminOrderEditTwig',
  113.             // EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE    =>  'onShoppingComplete',
  114.             // EccubeEvents::MAIL_ORDER => 'sendOrderMailBefore',
  115.             // EccubeEvents::ADMIN_ORDER_MAIL_INDEX_INITIALIZE => 'adminOrderMailInitAfter',
  116.         ];
  117.     }
  118.     
  119.     public function onShoppingTwig(TemplateEvent $event){
  120.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  121.         $Payment $paymentRepository->findOneBy(['method_class' => StripeCreditCard::class]);
  122.         $Order $event->getParameter('Order');
  123.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  124.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  125.         $payment_id $Payment->getId();
  126.         $stripe_method_name $Payment->getMethod();
  127.         $event->setParameter("stripe_pay_id"$payment_id);
  128.         $event->setParameter("checkout_ga_enable"$checkout_ga_enable);
  129.         $event->setParameter("stripe_method_name"$stripe_method_name);
  130.         $KonbiniPayment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  131.         $event->setParameter("stripe_konbini_pay_id"$KonbiniPayment->getId());
  132.         $event->setParameter("konbini_method_name"$KonbiniPayment->getMethod());
  133.         $event->addSnippet('@StripePaymentGateway42/default/Shopping/paymethod_label.js.twig');
  134.     }
  135.     public function onShoppingConfirmTwig(TemplateEvent $event){
  136.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  137.         $Payment $paymentRepository->findOneBy(['method_class' => StripeCreditCard::class]);
  138.         $Order $event->getParameter('Order');
  139.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  140.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  141.         if($Payment && ($Order->getPayment()->getMethodClass() == StripeCreditCard::class 
  142.                 || $Order->getPayment()->getMethodClass() == StripeKonbini::class)){
  143.             $payment_id $Payment->getId();
  144.             $method_name $Payment->getMethod();
  145.             $event->setParameter("stripe_pay_id"$payment_id);
  146.             $event->setParameter('checkout_ga_enable'$checkout_ga_enable);
  147.             $event->setParameter("method_name"$method_name);
  148.             $event->setParameter("stripe_method_name"$method_name);
  149.             $event->addSnippet('@StripePaymentGateway42/default/Shopping/paymethod_label.js.twig');
  150.             $event->addSnippet('@StripePaymentGateway42/default/Shopping/shopping.js.twig');
  151.         }
  152.     }
  153.     public function onShoppingCompleteTwig(TemplateEvent $event) {
  154.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  155.         $Payment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  156.         $Order $event->getParameter('Order');
  157.         if($Payment && $Order->getPayment()->getMethodClass() == StripeKonbini::class) {
  158.             $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order' => $Order));
  159.             if ($stripeOrder) {
  160.                 $event->setParameter('voucher_url'$stripeOrder->getKonbiniVoucherUrl());
  161.                 $event->addSnippet('@StripePaymentGateway42/default/Shopping/complete_konbini.twig');
  162.             }
  163.         }
  164.     }
  165.     public function onMypageHistoryTwig(TemplateEvent $event) {
  166.         $paymentRepository $this->entityManager->getRepository(Payment::class);
  167.         $Payment $paymentRepository->findOneBy(['method_class' => StripeKonbini::class]);
  168.         $Order $event->getParameter('Order');
  169.         if($Payment && $Order->getPayment()->getMethodClass() == StripeKonbini::class) {
  170.             $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order' => $Order));
  171.             if ($stripeOrder) {
  172.                 $event->setParameter('voucher_url'$stripeOrder->getKonbiniVoucherUrl());
  173.                 $event->addSnippet('@StripePaymentGateway42/default/Mypage/history_konbini.twig');
  174.             }
  175.         }
  176.     }
  177.     public function onCartIndexTwig(TemplateEvent $event){
  178.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  179.         if($stripe_config->getCartGaEnable()){
  180.             $event->setParameter('stripeConfig'$stripe_config);
  181.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  182.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  183.             $event->addSnippet('@StripePaymentGateway42/default/Cart/index.js.twig');
  184.         }
  185.     }
  186.     // public function onIndexTestTwig(TemplateEvent $event){
  187.     //     $payrequest = [
  188.     //         'currency_code' =>  'jpy',
  189.     //         'label'         =>  'Pay Now',
  190.     //         'amount'        =>  0,
  191.     //     ];
  192.     //     $stripe_config = $this->entityManager->getRepository(StripeConfig::class)->get();
  193.     //     $event->setParameter('cartKey', "1_2");
  194.     //     $event->setParameter('payrequest', $payrequest);
  195.     //     $event->setParameter('stripeConfig', $stripe_config);
  196.     //     $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  197.     //     $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  198.     //     $event->addSnippet('@StripePaymentGateway42/default/index_test.twig');
  199.     // }
  200.     public function onProductDetailTwig(TemplateEvent $event){
  201.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  202.         if($stripe_config->getProdDetailGaEnable()){
  203.             $product $event->getParameter('Product');
  204.             $first_pc $product->getProductClasses()[0];
  205.             
  206.             $payrequest = [
  207.                 'currency_code' =>  \strtolower($first_pc->getCurrencyCode()),
  208.                 'label'         =>  trans('stripe_payment_gateway.payrequest.button_label'),
  209.                 'amount'        =>  $first_pc->getPrice02IncTax(),
  210.             ];
  211.             
  212.     
  213.             $event->setParameter('payrequest'$payrequest);
  214.             $event->setParameter('stripeConfig'$stripe_config);
  215.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  216.             $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_request_button.js.twig');
  217.             $event->addSnippet('@StripePaymentGateway42/default/Product/detail.js.twig');
  218.         }
  219.     }
  220.     public function onStripePayment(TemplateEvent $event){
  221.         $stripe_config $this->entityManager->getRepository(StripeConfig::class)->get();
  222.         $checkout_ga_enable $stripe_config->getCheckoutGaEnable();
  223.         $event->setParameter('checkout_ga_enable'$checkout_ga_enable);
  224.         // $event->addAsset('StripePaymentGateway42/Resource/assets/css/base.css.twig');
  225.         // $event->addAsset('StripePaymentGateway42/Resource/assets/css/stripe_4.css.twig');
  226.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_official.js.twig');
  227.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_payment.js.twig');
  228.         // $event->addSnippet('StripePaymentGateway42/Resource/assets/js/stripe_elements.js.twig');
  229.     }
  230.     /**
  231.      * @param EventArgs $event
  232.      */
  233.     public function onFrontShoppingCompleteInitialize(EventArgs $event){
  234.         $Order=$event->getArgument('Order');
  235.         $this->session->getFlashBag()->set('stripe_payment_gateway_intent_id'false);
  236.         if($Order) {
  237.             if ($Order->getPayment()->getMethodClass() === StripeCreditCard::class) {
  238.                 $stripeOrder $this->stripeOrderRepository->findOneBy(array('Order'=>$Order));
  239.                 if($stripeOrder) {
  240.                     $stripeChargeID $stripeOrder->getStripeChargeId();
  241.                     if (!empty($stripeChargeID)) {
  242.                         $Today = new \DateTime();
  243.                         $Order->setPaymentDate($Today);
  244.                         $OrderStatus $this->orderStatusRepository->find(OrderStatus::PAID);
  245.                         $Order->setOrderStatus($OrderStatus);
  246.                         $this->entityManager->persist($Order);
  247.                         $this->entityManager->flush($Order);
  248.                     }
  249.                 }
  250.             }
  251.         }
  252.     }
  253.     /**
  254.      * @param TemplateEvent $event
  255.      */
  256.     public function onAdminOrderIndexTwig(TemplateEvent $event)
  257.     {
  258.         // 表示対象の受注一覧を取得
  259.         $pagination $event->getParameter('pagination');
  260.         if (empty($pagination) || count($pagination) == 0)
  261.         {
  262.             return;
  263.         }
  264.         $OrderToSearch=array();
  265.         foreach ($pagination as $Order){
  266.             $OrderToSearch[] = $Order;
  267.         }
  268.         if (empty($OrderToSearch)) {
  269.             return;
  270.         }
  271.         $StripeOrders $this->stripeOrderRepository->findBy(array('Order'=>$OrderToSearch));
  272.         if (!$StripeOrders)
  273.         {
  274.             return;
  275.         }
  276.         $StripeOrdersMapping = array();
  277.         foreach($StripeOrders as $stripeOrder) {
  278.             $Order $stripeOrder->getOrder();
  279.             $OrderId $Order->getId();
  280.             $StripeConfig $this->stripeConfigRepository->getConfigByOrder($Order);
  281.             if($StripeConfig) {
  282.                 $publishableKey=$StripeConfig->publishable_key;
  283.                 if(strpos($publishableKey'live') !== false) {
  284.                     $isLive true;
  285.                 } else {
  286.                     $isLive false;
  287.                 }
  288.                 $dashboard_url $this->getStripeChargeDashboardLink($isLive) . $stripeOrder->getStripeChargeId();
  289.             } else {
  290.                 $dashboard_url "#" $stripeOrder->getStripeChargeId();
  291.             }
  292.             $order_edit_url $this->container->get('router')->generate('admin_order_edit', array('id' => $OrderId), UrlGeneratorInterface::ABSOLUTE_URL);
  293.             $StripeOrdersMapping[] = (object)[ 
  294.                 'order_edit_url' => $order_edit_url
  295.                 'charge_id' => $stripeOrder->getStripeChargeId(), 
  296.                 'dashboard_url' => $dashboard_url,
  297.                 'Order'     =>  $Order,
  298.             ];
  299.         }
  300.         $event->setParameter('StripeOrdersMapping'$StripeOrdersMapping);
  301. //        $event->setParameter('StripeChargeDashboardLink',$this->getStripeChargeDashboardLink());
  302.         $asset 'StripePaymentGateway42/Resource/assets/js/admin/order_index.js.twig';
  303.         $event->addAsset($asset);
  304.     }
  305.     /**
  306.      * @param TemplateEvent $event
  307.      */
  308.     public function onAdminOrderEditTwig(TemplateEvent $event)
  309.     {
  310.         // 表示対象の受注情報を取得
  311.         $Order $event->getParameter('Order');
  312.         if (!$Order)
  313.         {
  314.             return;
  315.         }
  316.         $StripeConfig $this->stripeConfigRepository->getConfigByOrder($Order);
  317.         // EC-CUBE支払方法の取得
  318.         $Payment $Order->getPayment();
  319.         if (!$Payment)
  320.         {
  321.             return;
  322.         }
  323.         if ($Order->getPayment()->getMethodClass() === StripeCreditCard::class) {
  324.             $StripeOrder $this->stripeOrderRepository->findOneBy(array('Order'=>$Order));
  325.             if (!$StripeOrder)
  326.             {
  327.                 return;
  328.             }
  329.             if($StripeOrder->getIsChargeRefunded()==&& $StripeOrder->getSelectedRefundOption()==&& $StripeOrder->getRefundedAmount()==0) {
  330.                 $StripeOrder->setSelectedRefundOption(1);
  331.                 $StripeOrder->setRefundedAmount($Order->getPaymentTotal());
  332.                 $this->entityManager->persist($StripeOrder);
  333.                 $this->entityManager->flush($StripeOrder);
  334.             }
  335. //            $StripeConfig = $this->stripeConfigRepository->get();
  336.             $publishableKey=$StripeConfig->publishable_key;
  337.             if(strpos($publishableKey'live') !== false) {
  338.                 $isLive true;
  339.             } else {
  340.                 $isLive false;
  341.             }
  342.             $event->setParameter('StripeConfig'$StripeConfig);
  343.             $event->setParameter('StripeOrder'$StripeOrder);
  344.             $event->setParameter('StripeChargeDashboardLink',$this->getStripeChargeDashboardLink($isLive));
  345.             $event->addSnippet('@StripePaymentGateway42/admin/Order/edit.twig');
  346.         }
  347.     }
  348.     private function getScriptDiskPath() {
  349.         return dirname(__FILE__).'/Resource/assets/js/stripe_' $this->locale '.js.twig';
  350.     }
  351.     private function makeScript() {
  352.         return;
  353.         $buff file_get_contents(dirname(__FILE__) . '/Resource/assets/js/stripe_js.twig');
  354.         $out_path $this->getScriptDiskPath();
  355.         $m = array();
  356.         preg_match_all('/\{\{ (\w+) \}\}/'$buff$m);
  357.         for ($i 0$i sizeof($m[0]); $i++) {
  358.             //$buff = str_replace($m[0][$i], self::getLocalizedString($m[1][$i], $this->locale), $buff);
  359.             if($m[1][$i]=='locale'){
  360.                 $buff str_replace($m[0][$i], $this->locale$buff);
  361.             }
  362.         }
  363.         file_put_contents($out_path$buff);
  364.     }
  365.     private function getStripeChargeDashboardLink($isLive){
  366.             if($isLive){
  367.                 $chargeDashboardLink='https://dashboard.stripe.com/payments/';
  368.             } else {
  369.                 $chargeDashboardLink='https://dashboard.stripe.com/test/payments/';
  370.         }
  371.         return $chargeDashboardLink;
  372.     }
  373.     public static function getLocalizedString($id$locale) {
  374.         if (! isset(self::$i18n[$locale])) {
  375.             $tmp_loader = new \Symfony\Component\Translation\Loader\YamlFileLoader();
  376.             $catalogue $tmp_loader->load(dirname(__FILE__) . "/Resource/locale/messages.$locale.yml"'ja''stripe');
  377.             self::$i18n[$locale] = $catalogue->all('stripe');
  378.         }
  379.         if (isset(self::$i18n[$locale][$id])) {
  380.             return self::$i18n[$locale][$id];
  381.         }
  382.         return '--';
  383.     }
  384.     private function isEligiblePaymentMethod(Payment $Payment,$total){
  385.         $min $Payment->getRuleMin();
  386.         $max $Payment->getRuleMax();
  387.         if (null !== $min && $total $min) {
  388.             return false;
  389.         }
  390.         if (null !== $max && $total $max) {
  391.             return false;
  392.         }
  393.         return true;
  394.     }
  395.     
  396. }