diff -u b/modules/payment/src/Controller/PaymentCheckoutController.php b/modules/payment/src/Controller/PaymentCheckoutController.php --- b/modules/payment/src/Controller/PaymentCheckoutController.php +++ b/modules/payment/src/Controller/PaymentCheckoutController.php @@ -7,9 +7,10 @@ use Drupal\commerce_order\Entity\OrderInterface; use Drupal\commerce_payment\Exception\PaymentGatewayException; use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\OffsitePaymentGatewayInterface; -use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsCreatingOffsitePaymentMethodsWithPurchaseInterface; +use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsCreatingOffsitePaymentMethodsOnCheckoutInterface; use Drupal\Core\Access\AccessException; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; +use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Messenger\MessengerInterface; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Url; @@ -45,4 +46,11 @@ /** + * The entity type manager. + * + * @var \Drupal\Core\Entity\EntityTypeManagerInterface + */ + protected $entityTypeManager; + + /** * Constructs a new PaymentCheckoutController object. * @@ -52,11 +60,14 @@ * The messenger. * @param \Psr\Log\LoggerInterface $logger * The logger. + * @param \Drupal\Core\Entity\EntityTypeManagerInterface + * The entity type manager. */ - public function __construct(CheckoutOrderManagerInterface $checkout_order_manager, MessengerInterface $messenger, LoggerInterface $logger) { + public function __construct(CheckoutOrderManagerInterface $checkout_order_manager, MessengerInterface $messenger, LoggerInterface $logger, EntityTypeManagerInterface $entity_type_manager) { $this->checkoutOrderManager = $checkout_order_manager; $this->messenger = $messenger; $this->logger = $logger; + $this->entityTypeManager = $entity_type_manager; } /** @@ -66,7 +77,8 @@ return new static( $container->get('commerce_checkout.checkout_order_manager'), $container->get('messenger'), - $container->get('logger.channel.commerce_payment') + $container->get('logger.channel.commerce_payment'), + $container->get('entity_type.manager') ); } @@ -95,9 +107,9 @@ $checkout_flow = $order->get('checkout_flow')->entity; $checkout_flow_plugin = $checkout_flow->getPlugin(); - if ($payment_gateway_plugin instanceof SupportsCreatingOffsitePaymentMethodsWithPurchaseInterface) { + if ($payment_gateway_plugin instanceof SupportsCreatingOffsitePaymentMethodsOnCheckoutInterface) { try { - $payment_method_storage = \Drupal::entityTypeManager()->getStorage('commerce_payment_method'); + $payment_method_storage = $this->entityTypeManager->getStorage('commerce_payment_method'); /** @var \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method */ $payment_method = $payment_method_storage->create([ // Payment method type may depend on the request payload. We create @@ -119,11 +131,11 @@ $order->set('payment_method', $payment_method); $order->save(); } - catch (\Exception $e) { + catch (PaymentGatewayException $e) { // If creating payment method failed we allow onReturn to handle - // creating Payment, which is required to fulfill the payment. - // This exception is muted and logged. - \Drupal::logger('commerce_payment')->error($e->getMessage()); + // creating Payment, which is required to fulfill the payment. This + // exception is muted and logged. + $this->logger->error($e->getMessage()); } } diff -u b/modules/payment/src/PaymentOptionsBuilder.php b/modules/payment/src/PaymentOptionsBuilder.php --- b/modules/payment/src/PaymentOptionsBuilder.php +++ b/modules/payment/src/PaymentOptionsBuilder.php @@ -50,7 +50,7 @@ }); /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface[] $payment_gateways_with_payment_methods */ - $payment_gateways_supports_creating_payment_methods = array_filter($payment_gateways, function ($payment_gateway) { + $payment_gateways_supporting_creating_payment_methods = array_filter($payment_gateways, function ($payment_gateway) { /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */ return $payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface; }); @@ -99,7 +99,7 @@ // 3) Add options to create new stored payment methods of supported types. $payment_method_type_counts = []; // Count how many new payment method options will be built per gateway. - foreach ($payment_gateways_supports_creating_payment_methods as $payment_gateway) { + foreach ($payment_gateways_supporting_creating_payment_methods as $payment_gateway) { $payment_method_types = $payment_gateway->getPlugin()->getPaymentMethodTypes(); foreach ($payment_method_types as $payment_method_type_id => $payment_method_type) { @@ -112,7 +112,7 @@ } } - foreach ($payment_gateways_supports_creating_payment_methods as $payment_gateway) { + foreach ($payment_gateways_supporting_creating_payment_methods as $payment_gateway) { $payment_gateway_plugin = $payment_gateway->getPlugin(); $payment_method_types = $payment_gateway_plugin->getPaymentMethodTypes(); @@ -139,7 +139,7 @@ // 4) Add options for the remaining gateways (off-site, manual, etc). /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface[] $other_payment_gateways */ - $other_payment_gateways = array_diff_key($payment_gateways, $payment_gateways_supports_creating_payment_methods); + $other_payment_gateways = array_diff_key($payment_gateways, $payment_gateways_supporting_creating_payment_methods); foreach ($other_payment_gateways as $payment_gateway) { $payment_gateway_id = $payment_gateway->id(); $options[$payment_gateway_id] = new PaymentOption([ diff -u b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php --- b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php +++ b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php @@ -207,10 +207,11 @@ $default_payment_gateway_id = $default_option->getPaymentGatewayId(); $payment_gateway = $payment_gateways[$default_payment_gateway_id]; - if ($payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface) { + $payment_gateway_plugin = $payment_gateway->getPlugin(); + if ($payment_gateway_plugin instanceof SupportsStoredPaymentMethodsInterface) { $pane_form = $this->buildPaymentMethodForm($pane_form, $form_state, $default_option); } - elseif ($payment_gateway->getPlugin()->collectsBillingInformation()) { + elseif ($payment_gateway_plugin->collectsBillingInformation()) { $pane_form = $this->buildBillingProfileForm($pane_form, $form_state); } reverted: --- b/modules/payment/src/Plugin/Commerce/PaymentGateway/SupportsCreatingOffsitePaymentMethodsWithPurchaseInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -currentRequest->request->get('return'); + $query = [ + 'remote_payment_method_id' => 'pm-32768342', + 'cardexpdate' => $month . '28', + ]; + return new TrustedRedirectResponse($return . '?' . $this->buildQuery($query)); + } + else { + $cancel = $this->currentRequest->request->get('cancel'); + return new TrustedRedirectResponse($cancel); + } + } + + /** * Callback method which reacts to GET from a 302 redirect. * @@ -82,14 +102,14 @@ * Query string. */ protected function buildQuery(array $query = []) { - $query = [ + $query = $query + [ 'cardnomask' => 'xxxxxxxxxxxx1111', 'cardprefix' => '4111', - 'cardexpdate' => '1220', + 'cardexpdate' => '1228', 'txn_id' => '12345678', 'payment_status' => 'OK', 'customtext' => 'Srećno', - ] + $query; + ]; return http_build_query($query); } reverted: --- b/modules/payment_example/src/Plugin/Commerce/PaymentGateway/StoredOffsiteRedirectWithPurchase.php +++ /dev/null @@ -1,72 +0,0 @@ -card_type = CreditCard::detectType($request->query->get('cardprefix'))->getId(); - $paymentMethod->card_number = substr($request->query->get('cardnomask'), -4); - $paymentMethod->card_exp_month = substr($request->query->get('cardexpdate'), 0, 2); - $paymentMethod->card_exp_year = substr($request->query->get('cardexpdate'), -2); - - $paymentMethod->setRemoteId($request->query->get('txn_id')); - $expires = CreditCard::calculateExpirationTimestamp($paymentMethod->card_exp_month->value, $paymentMethod->card_exp_year->value); - $paymentMethod->setExpiresTime($expires); - $paymentMethod->save(); - } - - /** - * {@inheritdoc} - */ - public function deletePaymentMethod(PaymentMethodInterface $payment_method) { - $payment_method->delete(); - } - - /** - * {@inheritdoc} - */ - public function createPayment(PaymentInterface $payment, $capture = TRUE) { - $this->assertPaymentState($payment, ['new']); - $payment_method = $payment->getPaymentMethod(); - $this->assertPaymentMethod($payment_method); - - // Perform the create payment request here, throw an exception if it fails. - // See \Drupal\commerce_payment\Exception for the available exceptions. - // Remember to take into account $capture when performing the request. - $payment_method_token = $payment_method->getRemoteId(); - $next_state = $capture ? 'completed' : 'authorization'; - $payment->setState($next_state); - $payment->setRemoteId($payment_method_token); - $payment->save(); - } - -} only in patch2: unchanged: --- a/modules/payment/commerce_payment.routing.yml +++ b/modules/payment/commerce_payment.routing.yml @@ -101,3 +101,29 @@ commerce_payment.notify: parameters: commerce_payment_gateway: type: entity:commerce_payment_gateway + +commerce_payment.offsite_payment_method.return: + path: '/user/{user}/payment-methods/{payment_gateway}/return' + defaults: + _controller: '\Drupal\commerce_payment\Controller\OffsitePaymentMethodUserPageController::returnPage' + requirements: + _custom_access: '\Drupal\commerce_payment\Controller\OffsitePaymentMethodUserPageController::checkAccess' + options: + parameters: + user: + type: entity:user + payment_gateway: + type: entity:commerce_payment_gateway + +commerce_payment.offsite_payment_method.cancel: + path: '/user/{user}/payment-methods/{payment_gateway}/cancel' + defaults: + _controller: '\Drupal\commerce_payment\Controller\OffsitePaymentMethodUserPageController::cancelPage' + requirements: + _custom_access: '\Drupal\commerce_payment\Controller\OffsitePaymentMethodUserPageController::checkAccess' + options: + parameters: + user: + type: entity:user + payment_gateway: + type: entity:commerce_payment_gateway only in patch2: unchanged: --- a/modules/payment/js/offsite-redirect.js +++ b/modules/payment/js/offsite-redirect.js @@ -16,7 +16,7 @@ */ Drupal.behaviors.commercePaymentRedirect = { attach: function (context) { - $('.payment-redirect-form', context).submit(); + $('.payment-redirect-me', context).submit(); } }; only in patch2: unchanged: --- /dev/null +++ b/modules/payment/src/Controller/OffsitePaymentMethodUserPageController.php @@ -0,0 +1,149 @@ +logger = $logger; + $this->entityTypeManager = $entity_type_manager; + $this->stringTranslation = $translation; + $this->currentUser = $current_user; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('logger.channel.commerce_payment'), + $container->get('entity_type.manager'), + $container->get('string_translation'), + $container->get('current_user') + ); + } + + /** + * Provides the "return" offsite payment method page. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * @param \Drupal\Core\Routing\RouteMatchInterface $route_match + * The route match. + */ + public function returnPage(Request $request, RouteMatchInterface $route_match) { + /** @var \Drupal\Core\Session\AccountInterface $account */ + $account = $route_match->getParameter('user'); + /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */ + $payment_gateway = $route_match->getParameter('payment_gateway'); + /** @var \Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsCreatingOffsitePaymentMethodsOnUserPageInterface $payment_gateway_plugin */ + $payment_gateway_plugin = $payment_gateway->getPlugin(); + if (!$payment_gateway_plugin instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface) { + throw new AccessException('The payment gateway for the order does not implement ' . SupportsCreatingOffsitePaymentMethodsOnUserPageInterface::class); + } + try { + $payment_method_storage = $this->entityTypeManager->getStorage('commerce_payment_method'); + /** @var \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method */ + $payment_method = $payment_method_storage->create([ + // Payment method type may depend on the request payload. We create + // payment method stub based on default payment method type available + // for payment gateway plugin but module developers can swap it + // with custom payment method. Keep in mind that $payment_method is + // passed by reference and code below relies on that reference to add + // payment method to the order. + 'type' => $payment_gateway_plugin->getDefaultPaymentMethodType()->getPluginId(), + 'payment_gateway' => $payment_gateway, + 'uid' => $account->id(), + 'payment_gateway_mode' => $payment_gateway_plugin->getMode(), + ]); + // In case payment gateway supports payment method. + $payment_gateway_plugin->onReturnOffsitePaymentMethodOnUserPage($payment_method, $request); + return new RedirectResponse(Url::fromRoute('entity.commerce_payment_method.collection', ['user' => $account->id()])->toString()); + } + catch (PaymentGatewayException $e) { + // If creating payment method failed we allow onReturn to handle + // creating Payment, which is required to fulfill the payment. This + // exception is muted and logged. + $this->logger->error($e->getMessage()); + } + } + + /** + * Provides the "cancel" offsite payment method page. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * The request. + * @param \Drupal\Core\Routing\RouteMatchInterface $route_match + * The route match. + */ + public function cancelPage(Request $request, RouteMatchInterface $route_match) { + /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */ + $payment_gateway = $route_match->getParameter('payment_gateway'); + $payment_gateway_plugin = $payment_gateway->getPlugin(); + if (!$payment_gateway_plugin instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface) { + throw new AccessException('The payment gateway for the order does not implement ' . SupportsCreatingOffsitePaymentMethodsOnUserPageInterface::class); + } + $payment_gateway_plugin->onCancelOffsitePaymentMethodOnUserPage($request); + /** @var \Drupal\Core\Session\AccountInterface $account */ + $account = $route_match->getParameter('user'); + return new RedirectResponse(Url::fromRoute('entity.commerce_payment_method.collection', ['user' => $account->id()])->toString()); + } + + /** + * Access callback for the offsite payment method endpoints. + */ + public function checkAccess(RouteMatchInterface $route_match) { + $account = $route_match->getParameter('user'); + return AccessResult::allowedIf($this->currentUser->hasPermission('manage own commerce_payment_method') && $account->id() == $this->currentUser->id()); + } + +} only in patch2: unchanged: --- a/modules/payment/src/Form/PaymentMethodAddForm.php +++ b/modules/payment/src/Form/PaymentMethodAddForm.php @@ -3,11 +3,13 @@ namespace Drupal\commerce_payment\Form; use Drupal\commerce\InlineFormManager; +use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsCreatingOffsitePaymentMethodsOnUserPageInterface; use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsStoredPaymentMethodsInterface; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Url; use Drupal\user\UserInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; @@ -71,7 +73,7 @@ class PaymentMethodAddForm extends FormBase implements ContainerInjectionInterfa $payment_gateway_storage = $this->entityTypeManager->getStorage('commerce_payment_gateway'); $payment_gateway = $payment_gateway_storage->loadForUser($user); // @todo Move this check to the access handler. - if (!$payment_gateway || !($payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface)) { + if (!$payment_gateway || (!($payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface) && !($payment_gateway->getPlugin() instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface))) { throw new AccessDeniedHttpException(); } $form_state->set('payment_gateway', $payment_gateway); @@ -152,6 +154,8 @@ class PaymentMethodAddForm extends FormBase implements ContainerInjectionInterfa 'payment_gateway' => $form_state->get('payment_gateway'), 'uid' => $form_state->getBuildInfo()['args'][0]->id(), ]); + /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */ + $payment_gateway = $form_state->get('payment_gateway'); $inline_form = $this->inlineFormManager->createInstance('payment_gateway_form', [ 'operation' => 'add-payment-method', ], $payment_method); @@ -160,7 +164,12 @@ class PaymentMethodAddForm extends FormBase implements ContainerInjectionInterfa '#parents' => ['payment_method'], '#inline_form' => $inline_form, ]; + if ($payment_gateway && $payment_gateway->getPlugin() instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface) { + $form['payment_method']['#return_url'] = $this->buildReturnUrl($form_state->getBuildInfo()['args'][0]->id(), $payment_gateway->id())->toString(); + $form['payment_method']['#cancel_url'] = $this->buildCancelUrl($form_state->getBuildInfo()['args'][0]->id(), $payment_gateway->id())->toString(); + } $form['payment_method'] = $inline_form->buildInlineForm($form['payment_method'], $form_state); + $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save'), @@ -170,6 +179,42 @@ class PaymentMethodAddForm extends FormBase implements ContainerInjectionInterfa return $form; } + /** + * Builds the URL to the "return" page. + * + * @param int $uid + * The user id the payment method is being added for. + * @param string $gateway_id + * The payment gateway id of the payment gateway + * + * @return \Drupal\Core\Url + * The "return" page URL. + */ + protected function buildReturnUrl(int $uid, string $gateway_id) { + return Url::fromRoute('commerce_payment.offsite_payment_method.return', [ + 'user' => $uid, + 'payment_gateway' => $gateway_id, + ], ['absolute' => TRUE]); + } + + /** + * Builds the URL to the "cancel" page. + * + * @param int $uid + * The user id the payment method is being added for. + * @param string $gateway_id + * The payment gateway id of the payment gateway. + * + * @return \Drupal\Core\Url + * The "cancel" page URL. + */ + protected function buildCancelUrl(int $uid, string $gateway_id) { + return Url::fromRoute('commerce_payment.offsite_payment_method.cancel', [ + 'user' => $uid, + 'payment_gateway' => $gateway_id, + ], ['absolute' => TRUE]); + } + /** * {@inheritdoc} */ only in patch2: unchanged: --- a/modules/payment/src/PaymentGatewayStorage.php +++ b/modules/payment/src/PaymentGatewayStorage.php @@ -5,6 +5,7 @@ namespace Drupal\commerce_payment; use Drupal\commerce_order\Entity\OrderInterface; use Drupal\commerce_payment\Event\FilterPaymentGatewaysEvent; use Drupal\commerce_payment\Event\PaymentEvents; +use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsCreatingOffsitePaymentMethodsOnUserPageInterface; use Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\SupportsStoredPaymentMethodsInterface; use Drupal\Component\Uuid\UuidInterface; use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface; @@ -70,7 +71,7 @@ class PaymentGatewayStorage extends ConfigEntityStorage implements PaymentGatewa public function loadForUser(UserInterface $account) { $payment_gateways = $this->loadByProperties(['status' => TRUE]); $payment_gateways = array_filter($payment_gateways, function ($payment_gateway) { - return $payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface; + return $payment_gateway->getPlugin() instanceof SupportsStoredPaymentMethodsInterface || $payment_gateway->getPlugin() instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface; }); // @todo Implement resolving logic. $payment_gateway = reset($payment_gateways); only in patch2: unchanged: --- /dev/null +++ b/modules/payment/src/Plugin/Commerce/PaymentGateway/SupportsCreatingOffsitePaymentMethodsOnCheckoutInterface.php @@ -0,0 +1,29 @@ +createPaymentMethod($payment_method, $values['payment_details']); + if ($payment_gateway_plugin instanceof SupportsStoredPaymentMethodsInterface) { + $payment_gateway_plugin->createPaymentMethod($payment_method, $values['payment_details']); + } + elseif ($payment_gateway_plugin instanceof SupportsCreatingOffsitePaymentMethodsOnUserPageInterface) { + $payment_gateway_plugin->createPaymentMethodOnUserPage($payment_method, $values['payment_details']); + } } catch (DeclineException $e) { $this->logger->warning($e->getMessage()); only in patch2: unchanged: --- /dev/null +++ b/modules/payment/src/PluginForm/PaymentMethodOffsiteAddForm.php @@ -0,0 +1,113 @@ + $value) { + $form[$key] = [ + '#type' => 'hidden', + '#value' => $value, + // Ensure the correct keys by sending values from the form root. + '#parents' => [$key], + ]; + } + // The key is prefixed with 'commerce_' to prevent conflicts with $data. + $form['commerce_message'] = [ + '#markup' => '
' . t('Please wait while you are redirected to the payment server. If nothing happens within 10 seconds, please click on the button below.') . '
', + '#weight' => -10, + ]; + } + else { + $redirect_url = Url::fromUri($redirect_url, ['absolute' => TRUE, 'query' => $data])->toString(); + throw new NeedsRedirectException($redirect_url); + } + + return $form; + } + + /** + * Prepares the complete form for a POST redirect. + * + * Sets the form #action, adds a class for the JS to target. + * Workaround for buildConfigurationForm() not receiving $complete_form. + * + * @param array $form + * The plugin form. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current state of the form. + * @param array $complete_form + * The complete form structure. + * + * @return array + * The processed form element. + */ + public static function processRedirectForm(array $form, FormStateInterface $form_state, array &$complete_form) { + $complete_form['#action'] = $form['#redirect_url']; + $complete_form['#attributes']['class'][] = 'payment-redirect-form'; + // The form actions are hidden by default, but needed in this case. + $complete_form['actions']['#access'] = TRUE; + foreach (Element::children($complete_form['actions']) as $element_name) { + $complete_form['actions'][$element_name]['#access'] = TRUE; + } + + return $form; + } + + /** + * {@inheritdoc} + */ + public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { + // Nothing. Off-site payment gateways do not submit forms to Drupal. + } + +} only in patch2: unchanged: --- a/modules/payment/src/PluginForm/PaymentOffsiteForm.php +++ b/modules/payment/src/PluginForm/PaymentOffsiteForm.php @@ -60,6 +60,7 @@ abstract class PaymentOffsiteForm extends PaymentGatewayFormBase { protected function buildRedirectForm(array $form, FormStateInterface $form_state, $redirect_url, array $data, $redirect_method = self::REDIRECT_GET) { if ($redirect_method == self::REDIRECT_POST) { $form['#attached']['library'][] = 'commerce_payment/offsite_redirect'; + $form['#attributes']['class'][] = 'payment-redirect-me'; $form['#process'][] = [get_class($this), 'processRedirectForm']; $form['#redirect_url'] = $redirect_url; only in patch2: unchanged: --- a/modules/payment_example/commerce_payment_example.routing.yml +++ b/modules/payment_example/commerce_payment_example.routing.yml @@ -6,6 +6,7 @@ commerce_payment_example.dummy_redirect_post: no_cache: TRUE requirements: _access: 'TRUE' + commerce_payment_example.dummy_redirect_302: path: 'commerce_payment_example/dummy_redirect_302' defaults: @@ -14,3 +15,12 @@ commerce_payment_example.dummy_redirect_302: no_cache: TRUE requirements: _access: 'TRUE' + +commerce_payment_example.dummy_redirect_payment_method_post: + path: 'commerce_payment_example/dummy_redirect_payment_method_post' + defaults: + _controller: '\Drupal\commerce_payment_example\Controller\DummyRedirectController::postPaymentMethod' + options: + no_cache: TRUE + requirements: + _access: 'TRUE' only in patch2: unchanged: --- /dev/null +++ b/modules/payment_example/src/Plugin/Commerce/PaymentGateway/StoredOffsiteRedirect.php @@ -0,0 +1,192 @@ +messenger = $messenger; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('entity_type.manager'), + $container->get('plugin.manager.commerce_payment_type'), + $container->get('plugin.manager.commerce_payment_method_type'), + $container->get('datetime.time'), + $container->get('messenger') + ); + } + + /** + * {@inheritdoc} + */ + public function createPaymentMethod(PaymentMethodInterface $payment_method, OrderInterface $order, Request $request) { + $payment_method->card_type = CreditCard::detectType($request->query->get('cardprefix'))->getId(); + $payment_method->card_number = substr($request->query->get('cardnomask'), -4); + $payment_method->card_exp_month = substr($request->query->get('cardexpdate'), 0, 2); + $payment_method->card_exp_year = substr($request->query->get('cardexpdate'), -2); + + $payment_method->setRemoteId($request->query->get('txn_id')); + $expires = CreditCard::calculateExpirationTimestamp($payment_method->card_exp_month->value, $payment_method->card_exp_year->value); + $payment_method->setExpiresTime($expires); + $payment_method->save(); + } + + /** + * {@inheritdoc} + */ + public function deletePaymentMethod(PaymentMethodInterface $payment_method) { + $payment_method->delete(); + } + + /** + * {@inheritdoc} + */ + public function createPayment(PaymentInterface $payment, $capture = TRUE) { + $this->assertPaymentState($payment, ['new']); + $payment_method = $payment->getPaymentMethod(); + $this->assertPaymentMethod($payment_method); + + // Perform the create payment request here, throw an exception if it fails. + // See \Drupal\commerce_payment\Exception for the available exceptions. + // Remember to take into account $capture when performing the request. + $payment_method_token = $payment_method->getRemoteId(); + $next_state = $capture ? 'completed' : 'authorization'; + $payment->setState($next_state); + $payment->setRemoteId($payment_method_token); + $payment->save(); + } + + /** + * {@inheritdoc} + */ + public function onReturnOffsitePaymentMethodOnUserPage(PaymentMethodInterface $payment_method, Request $request) { + // This is the exact copy of + // Drupal\commerce_payment_example\Plugin\Commerce\PaymentGateway\Onsite::createPaymentMethodOnUserPage(). + $required_keys = [ + // The expected keys are payment gateway specific and usually match + // the PaymentMethodAddForm form elements. They are expected to be valid. + 'cardprefix', 'cardnomask', 'cardexpdate', + ]; + foreach ($required_keys as $required_key) { + if (empty($request->get($required_key))) { + throw new \InvalidArgumentException(sprintf('$payment_details must contain the %s key.', $required_key)); + } + } + // Add a built in test for testing decline exceptions. + // Note: Since requires_billing_information is FALSE, the payment method + // is not guaranteed to have a billing profile. Confirm tha + // $payment_method->getBillingProfile() is not NULL before trying to use it. + if ($billing_profile = $payment_method->getBillingProfile()) { + /** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $billing_address */ + $billing_address = $billing_profile->get('address')->first(); + if ($billing_address->getPostalCode() == '53141') { + throw new HardDeclineException('The payment method was declined'); + } + } + + // Perform the create request here, throw an exception if it fails. + // See \Drupal\commerce_payment\Exception for the available exceptions. + // You might need to do different API requests based on whether the + // payment method is reusable: $payment_method->isReusable(). + // Non-reusable payment methods usually have an expiration timestamp. + $payment_method->card_type = CreditCard::detectType($request->query->get('cardprefix'))->getId(); + // Only the last 4 numbers are safe to store. + $payment_method->card_number = substr($request->query->get('cardnomask'), -4); + $payment_method->card_exp_month = substr($request->query->get('cardexpdate'), 0, 2); + $payment_method->card_exp_year = substr($request->query->get('cardexpdate'), -2); + $expires = CreditCard::calculateExpirationTimestamp($payment_method->card_exp_month->value, $payment_method->card_exp_year->value); + $payment_method->setExpiresTime($expires); + // The remote ID returned by the request. + $payment_method->setRemoteId($request->query->get('remote_payment_method_id')); + $payment_method->save(); + $this->messenger->addMessage($this->t('A new payment method has been created.')); + } + + /** + * {@inheritdoc} + */ + public function onCancelOffsitePaymentMethodOnUserPage(Request $request) { + $this->messenger->addWarning($this->t('Payment method creation was canceled.')); + + } + + /** + * {@inheritdoc} + */ + public function updatePaymentMethod(PaymentMethodInterface $payment_method) {} + +} only in patch2: unchanged: --- /dev/null +++ b/modules/payment_example/src/PluginForm/StoredOffsiteRedirect/PaymentMethodAddForm.php @@ -0,0 +1,39 @@ +entity; + /** @var \Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\OffsitePaymentGatewayInterface $payment_gateway_plugin */ + $payment_gateway_plugin = $payment_method->getPaymentGateway()->getPlugin(); + $redirect_method = 'post'; + $remove_js = ($redirect_method == 'post_manual'); + $redirect_url = Url::fromRoute('commerce_payment_example.dummy_redirect_payment_method_post')->toString(); + + $data = [ + 'return' => $form['#return_url'], + 'cancel' => $form['#cancel_url'], + ]; + + $form = $this->buildRedirectForm($form, $form_state, $redirect_url, $data, $redirect_method); + if ($remove_js) { + // Disable the javascript that auto-clicks the Submit button. + unset($form['#attached']['library']); + } + + return $form; + } + +}