View source
<?php
namespace Drupal\commerce_paypal;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class IPNHandler implements IPNHandlerInterface {
protected $entityTypeManager;
protected $logger;
protected $httpClient;
public function __construct(EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger, ClientInterface $client) {
$this->entityTypeManager = $entity_type_manager;
$this->logger = $logger;
$this->httpClient = $client;
}
public function process(Request $request) {
$ipn_data = $this
->getRequestDataArray($request
->getContent());
if (empty($ipn_data)) {
$this->logger
->warning('IPN URL accessed with no POST data submitted.');
throw new BadRequestHttpException('IPN URL accessed with no POST data submitted.');
}
$url = $this
->getIpnValidationUrl($ipn_data);
$validate_ipn = 'cmd=_notify-validate&' . $request
->getContent();
try {
$request = $this->httpClient
->post($url, [
'body' => $validate_ipn,
])
->getBody();
$paypal_response = $this
->getRequestDataArray($request
->getContents());
} catch (ClientException $exception) {
}
if (!isset($paypal_response) || isset($paypal_response['INVALID'])) {
$this->logger
->alert('Invalid IPN received and ignored.');
throw new BadRequestHttpException('Invalid IPN received and ignored.');
}
return $ipn_data;
}
protected function getRequestDataArray($request_content) {
parse_str(html_entity_decode($request_content), $ipn_data);
return $ipn_data;
}
protected function getIpnValidationUrl(array $ipn_data) {
if (!empty($ipn_data['test_ipn']) && $ipn_data['test_ipn'] == 1) {
return 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
}
else {
return 'https://ipnpb.paypal.com/cgi-bin/webscr';
}
}
}