CheckoutController.php in Commerce PayPal 8
File
src/Controller/CheckoutController.php
View source
<?php
namespace Drupal\commerce_paypal\Controller;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_payment\Entity\PaymentGatewayInterface;
use Drupal\commerce_payment\Exception\PaymentGatewayException;
use Drupal\commerce_paypal\CheckoutSdkFactoryInterface;
use Drupal\commerce_paypal\Plugin\Commerce\PaymentGateway\CheckoutInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use GuzzleHttp\Exception\BadResponseException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckoutController extends ControllerBase {
protected $checkoutSdkFactory;
protected $entityTypeManager;
protected $logger;
protected $messenger;
public function __construct(CheckoutSdkFactoryInterface $checkout_sdk_factory, EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger, MessengerInterface $messenger) {
$this->checkoutSdkFactory = $checkout_sdk_factory;
$this->entityTypeManager = $entity_type_manager;
$this->logger = $logger;
$this->messenger = $messenger;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('commerce_paypal.checkout_sdk_factory'), $container
->get('entity_type.manager'), $container
->get('logger.channel.commerce_paypal'), $container
->get('messenger'));
}
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());
$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);
}
}
public function onApprove(RouteMatchInterface $route_match, Request $request) {
$order = $route_match
->getParameter('commerce_order');
$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 {
$payment_gateway_plugin
->onReturn($order, $request);
$step_id = $order
->get('checkout_step')->value;
if (!empty($step_id)) {
$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) {
$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();
}
}
protected function extractAddress(OrderInterface $order, Request $request) {
$body = Json::decode($request
->getContent());
if (!empty($body['profileCopy'])) {
$profiles = $order
->collectProfiles();
if (isset($profiles['shipping']) && !$profiles['shipping']
->get('address')
->isEmpty()) {
return $profiles['shipping']
->get('address')
->first();
}
}
$profile_storage = $this->entityTypeManager
->getStorage('profile');
if (!empty($body['profile'])) {
if ($body['profile'] === '_original') {
$profile = $profile_storage
->loadByUser($order
->getCustomer(), 'customer');
}
else {
$profile = $profile_storage
->load($body['profile']);
}
if ($profile && $profile
->access('view') && !$profile
->get('address')
->isEmpty()) {
return $profile
->get('address')
->first();
}
}
elseif (!empty($body['address'])) {
$profile = $profile_storage
->create([
'type' => 'customer',
'address' => $body['address'],
]);
return $profile
->get('address')
->first();
}
return NULL;
}
}