diff --git a/src/Exception/PayPalWebhookAlreadyRegisteredException.php b/src/Exception/PayPalWebhookAlreadyRegisteredException.php new file mode 100644 index 00000000..84c5fce0 --- /dev/null +++ b/src/Exception/PayPalWebhookAlreadyRegisteredException.php @@ -0,0 +1,13 @@ +sellerWebhookRegistrar->register($paymentMethod); } catch (PayPalWebhookUrlNotValidException $exception) { $paymentMethod->setEnabled(false); + } catch (PayPalWebhookAlreadyRegisteredException $exception) { + $paymentMethod->setEnabled(true); } return $paymentMethod; diff --git a/src/Registrar/SellerWebhookRegistrar.php b/src/Registrar/SellerWebhookRegistrar.php index 95c996ac..0a1c8d23 100644 --- a/src/Registrar/SellerWebhookRegistrar.php +++ b/src/Registrar/SellerWebhookRegistrar.php @@ -13,10 +13,13 @@ namespace Sylius\PayPalPlugin\Registrar; +use GuzzleHttp\Exception\ClientException; use Payum\Core\Model\GatewayConfigInterface; +use Psr\Http\Message\ResponseInterface; use Sylius\Component\Core\Model\PaymentMethodInterface; use Sylius\PayPalPlugin\Api\AuthorizeClientApiInterface; use Sylius\PayPalPlugin\Api\WebhookApiInterface; +use Sylius\PayPalPlugin\Exception\PayPalWebhookAlreadyRegisteredException; use Sylius\PayPalPlugin\Exception\PayPalWebhookUrlNotValidException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -49,7 +52,19 @@ public function register(PaymentMethodInterface $paymentMethod): void $token = $this->authorizeClientApi->authorize((string) $config['client_id'], (string) $config['client_secret']); $webhookUrl = $this->urlGenerator->generate('sylius_paypal_plugin_webhook_refund_order', [], UrlGeneratorInterface::ABSOLUTE_URL); - $response = $this->webhookApi->register($token, $webhookUrl); + + try { + $response = $this->webhookApi->register($token, $webhookUrl); + } catch (ClientException $exception) { + /** @var ResponseInterface $exceptionResponse */ + $exceptionResponse = $exception->getResponse(); + /** @var array $exceptionMessage */ + $exceptionMessage = json_decode($exceptionResponse->getBody()->getContents(), true); + + if ($exceptionMessage['name'] === 'WEBHOOK_URL_ALREADY_EXISTS') { + throw new PayPalWebhookAlreadyRegisteredException(); + } + } if (isset($response['name']) && $response['name'] === 'VALIDATION_ERROR') { throw new PayPalWebhookUrlNotValidException();