You are here

public function CheckoutController::onApprove in Commerce PayPal 8

React to the PayPal checkout "onApprove" JS SDK callback.

Parameters

\Drupal\Core\Routing\RouteMatchInterface $route_match: The route match.

\Symfony\Component\HttpFoundation\Request $request: The request.

Return value

\Symfony\Component\HttpFoundation\Response A response.

1 string reference to 'CheckoutController::onApprove'
commerce_paypal.routing.yml in ./commerce_paypal.routing.yml
commerce_paypal.routing.yml

File

src/Controller/CheckoutController.php, line 148

Class

CheckoutController
PayPal checkout controller.

Namespace

Drupal\commerce_paypal\Controller

Code

public function onApprove(RouteMatchInterface $route_match, Request $request) {

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $route_match
    ->getParameter('commerce_order');

  /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
  $payment_gateway = $route_match
    ->getParameter('commerce_payment_gateway');
  $payment_gateway_plugin = $payment_gateway
    ->getPlugin();
  if (!$payment_gateway_plugin instanceof CheckoutInterface) {
    throw new AccessException('Unsupported payment gateway provided.');
  }
  try {

    // Note that we're using a custom route instead of the payment return
    // one since the payment return callback cannot be called from the cart
    // page.
    $payment_gateway_plugin
      ->onReturn($order, $request);
    $step_id = $order
      ->get('checkout_step')->value;

    // Redirect to the next checkout step if the current checkout step is
    // known, which isn't the case when in the "shortcut" flow.
    if (!empty($step_id)) {

      /** @var \Drupal\commerce_checkout\Entity\CheckoutFlowInterface $checkout_flow */
      $checkout_flow = $order
        ->get('checkout_flow')->entity;
      $checkout_flow_plugin = $checkout_flow
        ->getPlugin();
      $step_id = $checkout_flow_plugin
        ->getNextStepId($step_id);
      $order
        ->set('checkout_step', $step_id);
    }
    $order
      ->save();
    $redirect_url = Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $order
        ->id(),
      'step' => $step_id,
    ])
      ->toString();
    return new JsonResponse([
      'redirectUrl' => $redirect_url,
    ]);
  } catch (PaymentGatewayException $e) {

    // When the payment fails, we don't instruct the JS to redirect, the page
    // will be reloaded to show errors.
    $this->logger
      ->error($e
      ->getMessage());
    $this->messenger
      ->addError(t('Payment failed at the payment server. Please review your information and try again.'));
    return new JsonResponse();
  }
}