You are here

public function CheckoutController::onCreate in Commerce PayPal 8

Create/update the order in PayPal.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $commerce_order: The order.

\Drupal\commerce_payment\Entity\PaymentGatewayInterface $commerce_payment_gateway: The payment gateway.

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

Return value

\Symfony\Component\HttpFoundation\Response A response.

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

File

src/Controller/CheckoutController.php, line 101

Class

CheckoutController
PayPal checkout controller.

Namespace

Drupal\commerce_paypal\Controller

Code

public function onCreate(OrderInterface $commerce_order, PaymentGatewayInterface $commerce_payment_gateway, Request $request) {
  if (!$commerce_payment_gateway
    ->getPlugin() instanceof CheckoutInterface) {
    throw new AccessException('Invalid payment gateway provided.');
  }
  $config = $commerce_payment_gateway
    ->getPluginConfiguration();
  $sdk = $this->checkoutSdkFactory
    ->get($config);
  try {
    $address = NULL;
    $body = [];
    if ($request
      ->getContent()) {
      $body = Json::decode($request
        ->getContent());

      // Check if a billing profile or an address was sent.
      // When this route is called in the context of the Custom card fields, the
      // form is not yet submitted which means the billing profile is not yet
      // associated with the order, so we extract it from the DOM and pass it
      // to the controller.
      // If we don't do that, then the "payer" will be considered as anonymous
      // by PayPal.
      $address = $this
        ->extractAddress($commerce_order, $request);
    }
    $commerce_order
      ->set('payment_gateway', $commerce_payment_gateway);
    $commerce_order
      ->setData('paypal_checkout_flow', $body['flow'] ?? 'mark');
    $response = $sdk
      ->createOrder($commerce_order, $address);
    $paypal_order = Json::decode($response
      ->getBody()
      ->getContents());
    $commerce_order
      ->setData('paypal_order_id', $paypal_order['id']);
    $commerce_order
      ->setRefreshState(OrderInterface::REFRESH_SKIP);
    $commerce_order
      ->save();
    return new JsonResponse([
      'id' => $paypal_order['id'],
    ]);
  } catch (BadResponseException $exception) {
    $this->logger
      ->error($exception
      ->getResponse()
      ->getBody()
      ->getContents());
    return new Response('', Response::HTTP_BAD_REQUEST);
  }
}