Redirect.php in PayPal for Payment 2.0.x
File
src/Controller/Redirect.php
View source
<?php
namespace Drupal\paypal_payment\Controller;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\payment\Entity\PaymentInterface;
use Drupal\paypal_payment\Plugin\Payment\Method\PayPalBasic;
use Exception;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Rest\ApiContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Redirect extends ControllerBase {
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('request_stack')
->getCurrentRequest());
}
public function access(PaymentInterface $payment) : AccessResult {
return AccessResult::allowedIf($this
->verify($payment));
}
private function verify(PaymentInterface $payment) {
$payment_method = $payment
->getPaymentMethod();
return $payment
->getOwnerId() === $this
->currentUser()
->id() && $this->request
->get('paymentId') === $payment_method
->getPaymentId();
}
public function execute(PaymentInterface $payment) : Response {
$paymentId = $this->request
->get('paymentId');
$payerID = $this->request
->get('PayerID');
$payment_method = $payment
->getPaymentMethod();
$api_context = $payment_method
->getApiContext($payment_method::PAYPAL_CONTEXT_TYPE_REDIRECT);
$p = Payment::get($paymentId, $api_context);
$execution = new PaymentExecution();
$execution
->setPayerId($payerID);
try {
$p
->execute($execution, $api_context);
$payment_method
->doCapturePayment();
} catch (Exception $ex) {
}
return $this
->getResponse($payment);
}
public function cancel(PaymentInterface $payment) : Response {
return $this
->getResponse($payment);
}
private function getResponse(PaymentInterface $payment) : Response {
$response = $payment
->getPaymentType()
->getResumeContextResponse();
return $response
->getResponse();
}
}