<?php
namespace Plugin\StripeRec42\Controller;
if( \file_exists(dirname(__FILE__).'/../../StripePaymentGateway42/vendor/stripe/stripe-php/init.php')) {
include_once(dirname(__FILE__).'/../../StripePaymentGateway42/vendor/stripe/stripe-php/init.php');
}
use Plugin\StripeRec42\Service\CouponService;
use Plugin\StripeRec42\Service\PointBundleService;
use Plugin\StripeRec42\Service\RecurringService;
use Plugin\StripeRec42\Service\UtilService;
use Stripe\Webhook;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Eccube\Controller\ShoppingController;
use Psr\Container\ContainerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Eccube\Controller\AbstractController;
use Eccube\Service\CartService;
use Eccube\Service\MailService;
use Eccube\Service\OrderHelper;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Order;
use Eccube\Entity\Customer;
use Eccube\Form\Type\Shopping\OrderType;
use Eccube\Repository\OrderRepository;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Eccube\Common\EccubeConfig;
use Eccube\Entity\Master\OrderStatus;
use Eccube\Entity\TradeLaw;
use Plugin\StripePaymentGateway42\Repository\StripeConfigRepository;
use Plugin\StripePaymentGateway42\StripeClient;
use Plugin\StripePaymentGateway42\Entity\StripeConfig;
use Plugin\StripePaymentGateway42\Entity\StripeOrder;
use Plugin\StripePaymentGateway42\Entity\StripeLog;
use Plugin\StripePaymentGateway42\Entity\StripeCustomer;
use Plugin\StripeRec42\Service\ConfigService;
use Plugin\StripeRec42\Entity\StripeRecOrder;
use Plugin\StripeRec42\Repository\StripeRecOrderRepository;
use Plugin\StripeRec42\Service\MailExService;
use Stripe\PaymentMethod;
use Stripe\PaymentIntent;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\TradeLawRepository;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Doctrine\ORM\EntityManagerInterface;
use Eccube\Common\Constant;
use Symfony\Component\DependencyInjection\ContainerInterface as OldContainerInterface;
use Plugin\StripeRec42\Service\Method\StripeRecurringNagMethod;
//カスタマイズ開始
use Customize\Controller\CustomizeShoppingController;
use Plugin\StripePaymentGateway42\Service\Method\StripeCreditCard;
use Plugin\StripePaymentGateway42\Service\Method\StripeKonbini;
use Plugin\PayPalCheckout42\Service\Method\CreditCard;
use Eccube\Service\Payment\Method\Cash;
//class ShoppingExController extends ShoppingController
class ShoppingExController extends CustomizeShoppingController
//カスタマイズ終了
{
private $stripe_config;
protected $util_service;
protected $session;
protected $stripeCustomerRepository;
protected $eccubeConfig;
protected $config_service;
protected $rec_service;
protected $coupon_service;
protected $pb_service;
protected $stripeRecurringPaymentMethod;
protected $locale;
public function __construct(
ContainerInterface $serviceContainer,
UtilService $util_service,
EntityManagerInterface $entityManager,
ConfigService $config_service,
RecurringService $rec_service,
CouponService $coupon_service,
PointBundleService $pb_service,
StripeRecurringNagMethod $stripeRecurringNagMethod,
CartService $cartService,
MailService $mailService,
OrderRepository $orderRepository,
OrderHelper $orderHelper,
TradeLawRepository $tradeLawRepository,
RateLimiterFactory $shoppingConfirmIpLimiter,
RateLimiterFactory $shoppingConfirmCustomerLimiter,
RateLimiterFactory $shoppingCheckoutIpLimiter,
RateLimiterFactory $shoppingCheckoutCustomerLimiter,
BaseInfoRepository $baseInfoRepository,
?ContainerInterface $oldContainer=null,
//カスタマイズ開始
StripeCreditCard $stripeCreditCard, // ←★追加
StripeKonbini $stripeKonbini, // ←★追加
CreditCard $paypalCreditCard,
Cash $cashPayment,
//カスタマイズ終了
) {
$this->util_service = $util_service;
$this->entityManager = $entityManager;
$this->stripeCustomerRepository = $this->entityManager->getRepository(StripeCustomer::class);
$this->config_service = $config_service;
$this->rec_service = $rec_service;
$this->coupon_service = $coupon_service;
$this->pb_service = $pb_service;
$this->stripeRecurringPaymentMethod = $stripeRecurringNagMethod;
$this->locale = env('ECCUBE_LOCALE', 'ja');
if(version_compare(Constant::VERSION,'4.3.0','>=')) {
parent::__construct(
$cartService,
$mailService,
$orderRepository,
$orderHelper,
$serviceContainer,
$tradeLawRepository,
$shoppingConfirmIpLimiter,
$shoppingConfirmCustomerLimiter,
$shoppingCheckoutIpLimiter,
$shoppingCheckoutCustomerLimiter,
$baseInfoRepository,
//カスタマイズ開始
$stripeCreditCard, // ←★追加
$stripeKonbini, // ←★追加
$paypalCreditCard,
$cashPayment,
//カスタマイズ終了
);
} else {
parent::__construct(
$cartService,
$mailService,
$orderRepository,
$orderHelper,
$oldContainer->get('service_container'),
$tradeLawRepository,
$shoppingConfirmIpLimiter,
$shoppingConfirmCustomerLimiter,
$shoppingCheckoutIpLimiter,
$shoppingCheckoutCustomerLimiter,
$baseInfoRepository,
//カスタマイズ開始
$stripeCreditCard, // ←★追加
$stripeKonbini, // ←★追加
$paypalCreditCard,
$cashPayment,
//カスタマイズ終了
);
}
}
/**
* @Route("/plugin/StripeRec42/presubscribe", name="plugin_striperec_presubscripe")
*/
public function presubscribe(Request $request)
{
// $StripeConfig = $this->stripeConfigRepository->get();
$preOrderId = $this->cartService->getPreOrderId();
/** @var Order $Order */
$Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
if (!$Order) {
return $this->json(['error' => 'true', 'message' => trans('stripe_payment_gateway.admin.order.invalid_request')]);
}
$StripeConfig = $this->entityManager->getRepository(StripeConfig::class)->getConfigByOrder($Order);
$stripeClient = new StripeClient($StripeConfig->secret_key);
$paymentMethodId = $request->get('payment_method_id');
$stripeCustomerId = $this->procStripeCustomer($stripeClient, $Order, true);
if(is_array($stripeCustomerId)) { // エラー
return $this->json($stripeCustomerId);
}
if($Order->hasStripePriceId()){
$this->session->getFlashBag()->set("stripe_customer_id", $stripeCustomerId);
$this->session->getFlashBag()->set("payment_method_id", $paymentMethodId);
return $this->json(["success" => true]);
}else {
return $this->json(["error" => "Not Recurring Product"]);
}
}
/**
* @Route("/plugin/StripeRec42/create_subscription_intent", name="plugin_striperec_create_subscription_intent")
*/
public function createSubscriptionIntent(Request $request)
{
$preOrderId = $this->cartService->getPreOrderId();
/** @var Order $Order */
$Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
if (!$Order) {
return $this->json([
'error' => true,
'message' => trans('stripe_payment_gateway.admin.order.invalid_request'),
]);
}
if (!$Order->hasStripePriceId()) {
return $this->json([
'error' => true,
'message' => 'Not Recurring Product',
]);
}
$StripeConfig = $this->entityManager
->getRepository(StripeConfig::class)
->getConfigByOrder($Order);
\Stripe\Stripe::setApiKey($StripeConfig->secret_key);
$paymentMethodId = $request->request->get('payment_method_id');
if (empty($paymentMethodId)) {
return $this->json([
'error' => true,
'message' => 'payment_method_id is required',
]);
}
$stripeClient = new StripeClient($StripeConfig->secret_key);
$stripeCustomerId = $this->procStripeCustomer($stripeClient, $Order, true);
if (is_array($stripeCustomerId)) {
return $this->json($stripeCustomerId);
}
try {
// PaymentMethod を Customer に紐付け
$paymentMethod = \Stripe\PaymentMethod::retrieve($paymentMethodId);
$paymentMethod->attach([
'customer' => $stripeCustomerId,
]);
// Customer のデフォルト支払い方法を更新
\Stripe\Customer::update($stripeCustomerId, [
'invoice_settings' => [
'default_payment_method' => $paymentMethodId,
],
]);
// subscription items 作成
$orderItems = $Order->getProductOrderItems();
$subscriptionItemsPre = [];
$subscriptionItems = [];
foreach ($orderItems as $orderItem) {
$pc = $orderItem->getProductClass();
if (empty($pc) || !$pc->isRegistered()) {
return $this->json([
'error' => true,
'message' => 'Recurring product is invalid',
]);
}
if (empty($subscriptionItemsPre[$pc->getStripePriceId()])) {
$subscriptionItemsPre[$pc->getStripePriceId()] = [
'price' => $pc->getStripePriceId(),
'quantity' => $orderItem->getQuantity(),
];
} else {
$subscriptionItemsPre[$pc->getStripePriceId()]['quantity'] += $orderItem->getQuantity();
}
}
foreach ($subscriptionItemsPre as $item) {
$subscriptionItems[] = $item;
}
// クーポン対応
$couponId = $request->request->get('coupon_id');
$subscriptionData = [
'customer' => $stripeCustomerId,
'items' => $subscriptionItems,
'default_payment_method' => $paymentMethodId,
'payment_behavior' => 'default_incomplete',
'payment_settings' => [
'save_default_payment_method' => 'on_subscription',
],
'expand' => ['latest_invoice.payment_intent'],
];
if (!empty($couponId)) {
$subscriptionData['coupon'] = $couponId;
}
$subscription = \Stripe\Subscription::create($subscriptionData);
$stripeOrder = $this->entityManager->getRepository(StripeRecOrder::class)->findOneBy([
'subscription_id' => $subscription->id,
'stripe_customer_id' => $stripeCustomerId,
]);
if (empty($stripeOrder)) {
$stripeOrder = new StripeRecOrder();
}
$stripeOrder->copyFrom($subscription);
$stripeOrder->setOrder($Order);
$stripeOrder->setStripeCustomerId($stripeCustomerId);
$stripeOrder->setCustomer($Order->getCustomer());
$stripeOrder->setSubscriptionId($subscription->id);
if (empty($stripeOrder->getRecStatus())) {
$stripeOrder->setRecStatus(StripeRecOrder::REC_STATUS_SCHEDULED);
}
if (empty($stripeOrder->getPaidStatus())) {
$stripeOrder->setPaidStatus(StripeRecOrder::STATUS_PAY_UNDEFINED);
}
if (empty($stripeOrder->getStartDate())) {
$stripeOrder->setStartDate(new \DateTime());
}
$this->entityManager->persist($stripeOrder);
$Order->setRecOrder($stripeOrder);
$this->entityManager->persist($Order);
$this->entityManager->flush();
log_info('[REC_DEBUG][PRECREATE_REC_ORDER] rec_order_id=' . $stripeOrder->getId());
log_info('[REC_DEBUG][PRECREATE_REC_ORDER] order_id=' . $Order->getId());
log_info('[REC_DEBUG][PRECREATE_REC_ORDER] subscription_id=' . $subscription->id);
$paymentIntent = null;
if (
isset($subscription->latest_invoice) &&
isset($subscription->latest_invoice->payment_intent)
) {
$paymentIntent = $subscription->latest_invoice->payment_intent;
}
log_info('[REC_DEBUG][CREATE_SUB_INTENT] subscription_id=' . $subscription->id);
log_info('[REC_DEBUG][CREATE_SUB_INTENT] customer_id=' . $stripeCustomerId);
log_info('[REC_DEBUG][CREATE_SUB_INTENT] payment_intent_status=' . ($paymentIntent ? $paymentIntent->status : 'NULL'));
log_info('[REC_DEBUG][CREATE_SUB_INTENT] payment_intent_id=' . ($paymentIntent ? $paymentIntent->id : 'NULL'));
if (!$paymentIntent) {
return $this->json([
'error' => true,
'message' => trans('stripe_payment_gateway.front.unexpected_error'),
]);
}
// 後続 checkout 用に session / flash へ保存
$this->session->getFlashBag()->set('stripe_customer_id', $stripeCustomerId);
$this->session->getFlashBag()->set('payment_method_id', $paymentMethodId);
$this->session->getFlashBag()->set('precreated_subscription_id', $subscription->id);
// coupon も checkout 時に使えるよう保存
if (!empty($couponId)) {
$this->session->set('stripe_rec_coupon_id', $couponId);
} else {
$this->session->remove('stripe_rec_coupon_id');
}
switch ($paymentIntent->status) {
case 'requires_confirmation':
case 'requires_action':
case 'requires_source_action':
return $this->json([
'action' => 'requires_action',
'payment_intent_id' => $paymentIntent->id,
'client_secret' => $paymentIntent->client_secret,
'subscription_id' => $subscription->id,
]);
case 'succeeded':
case 'processing':
case 'requires_capture':
return $this->json([
'action' => 'complete',
'payment_intent_id' => $paymentIntent->id,
'subscription_id' => $subscription->id,
]);
case 'requires_payment_method':
case 'requires_source':
return $this->json([
'error' => true,
'message' => StripeClient::getErrorMessageFromCode('invalid_number', $this->locale),
]);
default:
return $this->json([
'error' => true,
'message' => 'Unexpected subscription payment intent status: '.$paymentIntent->status,
]);
}
} catch (\Exception $e) {
log_error('[StripeRec createSubscriptionIntent] '.$e->getMessage());
return $this->json([
'error' => true,
'message' => trans('stripe_payment_gateway.front.unexpected_error'),
]);
}
}
/**
* @Route("/plugin/stripe_rec/success", name="plugin_stripe_rec_success")
*/
public function success(Request $request){
$this->cartService->clear();
return $this->redirectToRoute("shopping_complete");
}
/**
* @Route("/plugin/stripe_rec/extra_payemnt/{id}/{stamp}", name="plugin_stripe_rec_extra_pay")
* @Template("@StripeRec42/default/Shopping/checkout_recurring_extra.twig")
*/
public function extraPay(Request $request, $id, $stamp,
StripeRecOrderRepository $recOrderRepository,
StripeConfigRepository $stripeConfigRepository,
MailExService $mail_service)
{
$recOrder = $recOrderRepository->find($id);
if (!$recOrder) {
throw new NotFoundHttpException();
}
if ($recOrder->getManualLinkStamp() != $stamp) {
throw new NotFoundHttpException();
}
$stripeConfig = $stripeConfigRepository->getConfigByOrder($recOrder->getOrder());
$already = $this->orderRepository->findOneBy(['recOrder' => $recOrder, 'manual_link_stamp' => $stamp]);
if ($already) {
return [
'amount' => 0,
'recOrder' => $recOrder,
'stripeConfig'=> $stripeConfig,
'already_paid'=> true
];
}
$details = $this->rec_service->getPriceDetail($recOrder);
extract($details);
if ($recOrder->getPaymentCount() == 0) {
// 'bundle_order_items', 'initial_amount', 'recurring_amount', 'initial_discount', 'recurring_discount'
$amount = $initial_amount - $initial_discount;
} else {
$amount = $recurring_amount - $recurring_discount;
}
$stripeClient = new StripeClient($stripeConfig->secret_key);
if ($request->getMethod() === "POST") {
$payment_intent_id = $request->request->get('payment_intent_id');
if (empty($payment_intent_id)) {
throw new NotFoundHttpException();
}
$is_auth_capture = $stripeConfig->is_auth_and_capture_on;
log_info("----extra_pay---");
if ($is_auth_capture) {//Capture if on
log_info("capturing payment, payment_intent_id : $payment_intent_id");
$payment_intent = $stripeClient->capturePaymentIntent($payment_intent_id, $amount, $recOrder->getOrder()->getCurrencyCode());
log_info("captured payment, payment_intent_id : $payment_intent_id");
} else {
$payment_intent = $stripeClient->retrievePaymentIntent($payment_intent_id);
}
if (is_array($payment_intent) && isset($payment_intent['error'])) {
$errorMessage = StripeClient::getErrorMessageFromCode($payment_intent['error'], $this->locale);
return $this->json(['error' => $errorMessage]);
}
if ($is_auth_capture) {
$status_id = OrderStatus::PAID;
} else {
$status_id = OrderStatus::NEW;
}
$NewOrder = $this->rec_service->createNewOrder($recOrder, $status_id);
$NewOrder->setManualLinkStamp($stamp);
$this->entityManager->persist($NewOrder);
$recOrder->setLastChargeId($payment_intent->charges->data[0]->id);
$recOrder->setPaidStatus(StripeRecOrder::STATUS_PAID);
$recOrder->setLastPaymentDate(new \DateTime());
$this->entityManager->persist($recOrder);
$this->entityManager->flush();
$recOrder->setCurrentPaymentTotal($amount);
$mail_service->sendPaidMail($recOrder);
return $this->json(['success' => true, 'order_id' => $NewOrder->getId()]);
}
return compact('amount', 'recOrder', 'stripeConfig');
}
/**
* @Route("/plugin/stripe_rec/extra_payment/intent/{id}", name="plugin_stripe_rec_extra_pay_intent")
*/
public function extraPayIntent(Request $request, $id, StripeConfigRepository $stripeConfigRepository)
{
$rec_order = $this->entityManager->getRepository(StripeRecOrder::class)->find($id);
if (!$rec_order) {
throw new NotFoundHttpException();
}
$Order = $rec_order->getOrder();
$StripeConfig = $stripeConfigRepository->getConfigByOrder($Order);
$stripeClient = new StripeClient($StripeConfig->secret_key);
$paymentMethodId = $request->request->get('payment_method_id');
$isSaveCardOn = $request->request->get('is_save_on') === "true" ? true : false;
$stripeCustomerId = $this->procStripeCustomer($stripeClient, $Order, $isSaveCardOn);
if (is_array($stripeCustomerId)) {
return $this->json($stripeCustomerId);
}
$details = $this->rec_service->getPriceDetail($rec_order);
extract($details);
if ($rec_order->getPaymentCount() == 0) {
// 'bundle_order_items', 'initial_amount', 'recurring_amount', 'initial_discount', 'recurring_discount'
$amount = $initial_amount - $initial_discount;
} else {
$amount = $recurring_amount - $recurring_discount;
}
$paymentIntent = $stripeClient->createPaymentIntentWithCustomer(
$amount,
$paymentMethodId,
$Order->getId(),
$isSaveCardOn,
$stripeCustomerId,
$Order->getCurrencyCode());
return $this->json($this->genPaymentResponse($paymentIntent));
}
/**
* @Route("/plugin/stripe_rec/cancel", name="plugin_stripe_rec_cancel")
*/
public function cancel(Request $request){
$preOrderId = $this->cartService->getPreOrderId();
$order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
if(empty($order)){
return $this->redirectToRoute("shopping");
}
if(!$order->isRecurring()){
return $this->redirectToRoute("shopping");
}
$rec_order = $order->getRecOrder();
$rec_items = $rec_order->getOrderItems();
foreach($rec_items as $rec_item){
$this->entityManager->remove($rec_item);
$this->entityManager->flush();
$this->entityManager->commit();
}
$this->entityManager->remove($rec_order);
$this->entityManager->flush();
$this->entityManager->commit();
return $this->redirectToRoute("shopping");
}
/**
* @Route("/plugin/stripe_rec/checkout_page", name="plugin_striperec_checkout_page")
* @Template("@StripeRec42/default/Shopping/checkout.twig")
*/
public function credit_payment(Request $request)
{
// ログイン状態のチェック.
if ($this->orderHelper->isLoginRequired()) {
log_info('[注文処理] 未ログインもしくはRememberMeログインのため, ログイン画面に遷移します.');
return $this->redirectToRoute('shopping_login');
}
// 受注の存在チェック
$preOrderId = $this->cartService->getPreOrderId();
$Order = $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
if (!$Order) {
log_info('[注文処理] 購入処理中の受注が存在しません.', [$preOrderId]);
return $this->redirectToRoute('shopping_error');
}
$StripeConfig = $this->entityManager->getRepository(StripeConfig::class)->getConfigByOrder($Order);
$Customer = $Order->getCustomer();
// フォームの生成.
$form = $this->createForm(OrderType::class, $Order,[
'skip_add_form' => true,
]);
$form->handleRequest($request);
$checkout_ga_enable = $StripeConfig->checkout_ga_enable;
$rec_config = $this->config_service->getConfig();
$coupon_enable = $rec_config[ConfigService::COUPON_ENABLE];
if ($form->isSubmitted() && $form->isValid()) {
return [
'stripeConfig' => $StripeConfig,
'Order' => $Order,
'checkout_ga_enable' => $checkout_ga_enable,
'coupon_enable' => $coupon_enable,
];
}
return $this->redirectToRoute('shopping');
}
/**
* @Route("/plugin/stripe_rec/check_coupon", name="plugin_striperec_coupon_check")
*/
public function checkCoupon(Request $request){
$coupon_id = $request->request->get('coupon_id');
$res = $this->coupon_service->retrieveCoupon($coupon_id);
if(empty($res)){
return $this->json([
'error' => true,
'message' => $this->coupon_service->getError()
]);
}
if(empty($res->valid)){
return $this->json([
'error' => true,
'message' => trans("stripe_recurring.coupon.error.expired_or_invalid")
]);
}
$Order = $this->getOrder();
$bundle_include_arr = $this->session->get('bundle_include_arr');
$bundles = $this->pb_service->getBundleProducts($Order, $bundle_include_arr);
$price_sum = $this->pb_service->getPriceSum($Order);
extract($price_sum);
if($bundles){
$bundle_order_items = $bundles['order_items'];
$initial_amount += $bundles['price'];
}else{
$bundle_order_items = null;
}
$initial_discount = $this->coupon_service->couponDiscountAmount($initial_amount, $res);
$recurring_discount = $this->coupon_service->couponDiscountAmount($recurring_amount, $res);
return $this->json([
'success' => true,
'initial_amount' => $initial_amount,
'recurring_amount' => $recurring_amount,
'initial_discount' => $initial_discount,
'recurring_discount'=> $recurring_discount,
]);
}
/**
* @Route("/plugin/striperec/checkout", name="plugin_striperec_checkout")
*/
public function checkout(Request $request){
$Order = $this->getOrder();
if (!$Order) {
$this->addError(trans('stripe_payment_gateway.admin.order.invalid_request'));
return $this->redirectToRoute('shopping_error');
}
// EOC validation checking
try {
$response = $this->executePurchaseFlow($Order);
$this->entityManager->flush();
if ($response) {
return $response;
}
log_info('[注文処理] PaymentMethodを取得します.', [$Order->getPayment()->getMethodClass()]);
$paymentMethod = $this->createPaymentMethod($Order, null);
/*
* 決済実行(前処理)
*/
log_info('[注文処理] PaymentMethod::applyを実行します.');
if ($response = $this->executeApply($paymentMethod)) {
return $response;
}
/*
* 決済実行
*
* PaymentMethod::checkoutでは決済処理が行われ, 正常に処理出来た場合はPurchaseFlow::commitがコールされます.
*/
log_info('[注文処理] PaymentMethod::checkoutを実行します.');
if ($response = $this->executeCheckout($paymentMethod)) {
return $response;
}
$this->entityManager->flush();
log_info('[注文処理] 注文処理が完了しました.', [$Order->getId()]);
}catch (ShoppingException $e) {
log_error('[注文処理] 購入エラーが発生しました.', [$e->getMessage()]);
$this->entityManager->rollback();
$this->addError($e->getMessage());
return $this->redirectToRoute('shopping_error');
} catch (\Exception $e) {
log_error('[注文処理] 予期しないエラーが発生しました.', [$e->getMessage()]);
$this->entityManager->rollback();
$this->addError('front.shopping.system_error');
return $this->redirectToRoute('shopping_error');
}
// カート削除
log_info('[注文処理] カートをクリアします.', [$Order->getId()]);
$this->cartService->clear();
// 受注IDをセッションにセット
$this->session->set(OrderHelper::SESSION_ORDER_ID, $Order->getId());
// メール送信
log_info('[注文処理] 注文メールの送信を行います.', [$Order->getId()]);
$this->mailService->sendOrderMail($Order);
$this->entityManager->flush();
log_info('[注文処理] 注文処理が完了しました. 購入完了画面へ遷移します.', [$Order->getId()]);
return $this->redirectToRoute('shopping_complete');
}
// For original card input recurring
private function procStripeCustomer(StripeClient $stripeClient, $Order, $isSaveCardOn) {
$Customer = $Order->getCustomer();
$isEcCustomer=false;
$isStripeCustomer=false;
$StripeCustomer = false;
$stripeCustomerId = false;
if($Customer instanceof Customer ){
$isEcCustomer=true;
$StripeCustomer=$this->stripeCustomerRepository->findOneBy(array('Customer'=>$Customer));
if($StripeCustomer instanceof StripeCustomer){
$stripLibCustomer = $stripeClient->retrieveCustomer($StripeCustomer->getStripeCustomerId());
if(is_array($stripLibCustomer) || isset($stripLibCustomer['error'])) {
if(isset($stripLibCustomer['error']['code']) && $stripLibCustomer['error']['code'] == 'resource_missing') {
$isStripeCustomer = false;
}
} else {
$isStripeCustomer=true;
}
}
}
if($isEcCustomer) {//Create/Update customer
if($isSaveCardOn) {
//BOC check if is StripeCustomer then update else create one
if($isStripeCustomer) {
$stripeCustomerId=$StripeCustomer->getStripeCustomerId();
//BOC save is save card
$StripeCustomer->setIsSaveCardOn($isSaveCardOn);
$this->entityManager->persist($StripeCustomer);
$this->entityManager->flush($StripeCustomer);
//EOC save is save card
$updateCustomerStatus = $stripeClient->updateCustomerV2($stripeCustomerId,$Customer->getEmail());
if (is_array($updateCustomerStatus) && isset($updateCustomerStatus['error'])) {//In case of update fail
$errorMessage=StripeClient::getErrorMessageFromCode($updateCustomerStatus['error'], $this->locale);
return ['error' => true, 'message' => $errorMessage];
}
} else {
$stripeCustomerId=$stripeClient->createCustomerV2($Customer->getEmail(),$Customer->getId());
if (is_array($stripeCustomerId) && isset($stripeCustomerId['error'])) {//In case of fail
$errorMessage=StripeClient::getErrorMessageFromCode($stripeCustomerId['error'], $this->locale);
return ['error' => true, 'message' => $errorMessage];
} else {
if(!$StripeCustomer) {
$StripeCustomer = new StripeCustomer();
$StripeCustomer->setCustomer($Customer);
}
$StripeCustomer->setStripeCustomerId($stripeCustomerId);
$StripeCustomer->setIsSaveCardOn($isSaveCardOn);
$StripeCustomer->setCreatedAt(new \DateTime());
$this->entityManager->persist($StripeCustomer);
$this->entityManager->flush($StripeCustomer);
}
}
//EOC check if is StripeCustomer then update else create one
return $stripeCustomerId;
}
}
//Create temp customer
$stripeCustomerId=$stripeClient->createCustomerV2($Order->getEmail(),0,$Order->getId());
if (is_array($stripeCustomerId) && isset($stripeCustomerId['error'])) {//In case of fail
$errorMessage=StripeClient::getErrorMessageFromCode($stripeCustomerId['error'], $this->locale);
return ['error' => true, 'message' => $errorMessage];
}
return $stripeCustomerId;
}
private function getErrorMessages(\Symfony\Component\Form\Form $form) {
$errors = array();
foreach ($form->getErrors() as $key => $error) {
if ($form->isRoot()) {
$errors['#'][] = $error->getMessage();
} else {
$errors[] = $error->getMessage();
}
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
return $errors;
}
private function getOrder(){
// BOC validation checking
$preOrderId = $this->cartService->getPreOrderId();
/** @var Order $Order */
return $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
}
/**
* PaymentMethodをコンテナから取得する.
*
* @param Order $Order
* @param FormInterface $form
*
* @return PaymentMethodInterface
*/
private function createPaymentMethod(Order $Order)
{
$PaymentMethod = $this->serviceContainer->get($Order->getPayment()->getMethodClass());
//$PaymentMethod = $this->stripeRecurringPaymentMethod;
$PaymentMethod->setOrder($Order);
return $PaymentMethod;
}
private function genPaymentResponse($intent) {
if($intent instanceof PaymentIntent ) {
log_info("genPaymentResponse: " . $intent->status);
switch($intent->status) {
case 'requires_action':
case 'requires_source_action':
return [
'action'=> 'requires_action',
'payment_intent_id'=> $intent->id,
'client_secret'=> $intent->client_secret
];
case 'requires_payment_method':
case 'requires_source':
return [
'error' => true,
'message' => StripeClient::getErrorMessageFromCode('invalid_number', $this->locale)
];
case 'requires_capture':
return [
'action' => 'requires_capture',
'payment_intent_id' => $intent->id
];
default:
return ['error' => true, 'message' => trans('stripe_payment_gateway.front.unexpected_error')];
// return ['error' => true, 'message' => trans('stripe_payment_gateway.front.unexpected_error')];
}
}
if(isset($intent['error'])) {
$errorMessage=StripeClient::getErrorMessageFromCode($intent['error'], $this->locale);
} else {
$errorMessage = trans('stripe_payment_gateway.front.unexpected_error');
}
return ['error' => true, 'message' => $errorMessage];
}
}