From 8402ca6b2f041f79e3a2d9dfffcecd3141e89d8b Mon Sep 17 00:00:00 2001 From: Bastien Tafforeau Date: Wed, 3 Jan 2024 09:43:14 +0100 Subject: [PATCH 01/26] Draft for httpclient refactoring --- src/Api/Payment/Client/OldPaymentClient.php | 207 ++++++++++++++++ src/Api/Payment/Client/PaymentClient.php | 185 +------------- .../PaymentClientConfigurationBuilder.php | 89 +++++++ src/Api/Payment/PaymentService.php | 227 ++++++++++++++++++ src/Api/Payment/Service/PaymentService.php | 67 ++++++ src/Api/Payment/Shop.php | 4 +- src/Api/Payment/Webhook.php | 4 +- src/Http/PsrClientAdapter.php | 45 ++++ 8 files changed, 650 insertions(+), 178 deletions(-) create mode 100755 src/Api/Payment/Client/OldPaymentClient.php create mode 100755 src/Api/Payment/Client/PaymentClientConfigurationBuilder.php create mode 100644 src/Api/Payment/PaymentService.php create mode 100755 src/Api/Payment/Service/PaymentService.php create mode 100644 src/Http/PsrClientAdapter.php diff --git a/src/Api/Payment/Client/OldPaymentClient.php b/src/Api/Payment/Client/OldPaymentClient.php new file mode 100755 index 000000000..8a4719df2 --- /dev/null +++ b/src/Api/Payment/Client/OldPaymentClient.php @@ -0,0 +1,207 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; + +use Context; +use GuzzleHttp\Event\Emitter; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Subscriber\Log\Formatter; +use GuzzleHttp\Subscriber\Log\LogSubscriber; +use GuzzleLogMiddleware\LogMiddleware; +use Link; +use Module; +use PrestaShop\Module\PrestashopCheckout\Api\GenericClient; +use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; +use PrestaShop\Module\PrestashopCheckout\Exception\HttpTimeoutException; +use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; +use PrestaShop\Module\PrestashopCheckout\Logger\LoggerConfiguration; +use PrestaShop\Module\PrestashopCheckout\Routing\Router; +use PrestaShop\Module\PrestashopCheckout\ShopContext; +use PrestaShop\Module\PrestashopCheckout\Version\Version; +use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; +use Ps_checkout; +use Psr\Log\LoggerInterface; + +/** + * Construct the client used to make call to maasland + */ +class OldPaymentClient extends GenericClient +{ + /** + * @param Link $link + * @param object|null $client + */ + public function __construct(Link $link, $client = null) + { + parent::__construct(); + + $this->setLink($link); + + // Client can be provided for tests + if (null === $client) { + /** @var Ps_checkout $module */ + $module = Module::getInstanceByName('ps_checkout'); + + /** @var Version $version */ + $version = $module->getService('ps_checkout.module.version'); + + /** @var LoggerConfiguration $loggerConfiguration */ + $loggerConfiguration = $module->getService('ps_checkout.logger.configuration'); + + /** @var LoggerInterface $logger */ + $logger = $module->getService('ps_checkout.logger'); + + /** @var Router $router */ + $router = $module->getService('ps_checkout.prestashop.router'); + + $clientConfiguration = [ + 'base_url' => (new PaymentEnv())->getPaymentApiUrl(), + 'verify' => $this->getVerify(), + 'timeout' => $this->timeout, + 'exceptions' => $this->catchExceptions, + 'headers' => [ + 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) + 'Accept' => 'application/json', + 'Authorization' => 'Bearer ' . $this->token, // Token we get from PsAccounts + 'Shop-Id' => $this->shopUid, // Shop UUID we get from PsAccounts + 'Hook-Url' => $router->getDispatchWebhookLink((int) Context::getContext()->shop->id), + 'Bn-Code' => (new ShopContext())->getBnCode(), + 'Module-Version' => $version->getSemVersion(), // version of the module + 'Prestashop-Version' => _PS_VERSION_, // prestashop version + ], + ]; + + if ( + $loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION') + && class_exists(HandlerStack::class) + && class_exists(LogMiddleware::class) + ) { + $handlerStack = HandlerStack::create(); + $handlerStack->push(new LogMiddleware($logger)); + $clientConfiguration['handler'] = $handlerStack; + } elseif ( + $loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::VERSION') + && class_exists(Emitter::class) + && class_exists(LogSubscriber::class) + && class_exists(Formatter::class) + ) { + $emitter = new Emitter(); + $emitter->attach(new LogSubscriber( + $logger, + Formatter::DEBUG + )); + + $clientConfiguration['emitter'] = $emitter; + } + + $client = (new ClientFactory())->getClient($clientConfiguration); + } + + $this->setClient($client); + } + + /** + * @param array $options + * + * @return array + * + * @throws HttpTimeoutException + */ + protected function post(array $options = []) + { + $delay = isset($options['delay']) ? (int) $options['delay'] : 2; + $retries = isset($options['retries']) ? (int) $options['retries'] : 2; + unset($options['delay'], $options['retries']); + + return $this->postWithRetry($options, $delay, $retries); + } + + /** + * @param array $options + * @param int $delay + * @param int $retries + * + * @return array + * + * @throws HttpTimeoutException + * @throws PsCheckoutException + */ + private function postWithRetry(array $options, $delay = 2, $retries = 2) + { + try { + $response = parent::post($options); + + if ($response['httpCode'] === 401 || false !== strpos($response['exceptionMessage'], 'Unauthorized')) { + throw new PsCheckoutException('Unauthorized', PsCheckoutException::PSCHECKOUT_HTTP_UNAUTHORIZED); + } + + if (false !== $response['status']) { + return $response; + } + + if ( + isset($response['exceptionCode']) + && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION + && false !== strpos($response['exceptionMessage'], 'cURL error 28') + ) { + throw new HttpTimeoutException($response['exceptionMessage'], PsCheckoutException::PSL_TIMEOUT); + } elseif ( + isset($response['exceptionCode']) + && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION + ) { + throw new PsCheckoutException($response['exceptionMessage'], PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION); + } + + if ( + isset($response['body']['message']) + && ($response['body']['message'] === 'Error: ETIMEDOUT' || $response['body']['message'] === 'Error: ESOCKETTIMEDOUT') + ) { + throw new HttpTimeoutException($response['body']['message'], PsCheckoutException::PSL_TIMEOUT); + } + } catch (HttpTimeoutException $exception) { + if ($this->isRouteRetryable() && $retries > 0) { + sleep($delay); + + return $this->postWithRetry($options, $delay, $retries - 1); + } + + throw $exception; + } + + return $response; + } + + /** + * @return bool + */ + private function isRouteRetryable() + { + switch ($this->getRoute()) { + case '/payments/order/capture': + case '/payments/order/refund': + return false; + } + + return true; + } +} diff --git a/src/Api/Payment/Client/PaymentClient.php b/src/Api/Payment/Client/PaymentClient.php index 820448360..6b66b23d2 100755 --- a/src/Api/Payment/Client/PaymentClient.php +++ b/src/Api/Payment/Client/PaymentClient.php @@ -20,188 +20,25 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; -use Context; -use GuzzleHttp\Event\Emitter; -use GuzzleHttp\HandlerStack; -use GuzzleHttp\Subscriber\Log\Formatter; -use GuzzleHttp\Subscriber\Log\LogSubscriber; -use GuzzleLogMiddleware\LogMiddleware; -use Link; -use Module; -use PrestaShop\Module\PrestashopCheckout\Api\GenericClient; -use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; -use PrestaShop\Module\PrestashopCheckout\Exception\HttpTimeoutException; -use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; -use PrestaShop\Module\PrestashopCheckout\Logger\LoggerConfiguration; -use PrestaShop\Module\PrestashopCheckout\Routing\Router; -use PrestaShop\Module\PrestashopCheckout\ShopContext; -use PrestaShop\Module\PrestashopCheckout\Version\Version; -use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; -use Ps_checkout; -use Psr\Log\LoggerInterface; +use PrestaShop\Module\PrestashopCheckout\Http\HttpClientInterface; +use PrestaShop\Module\PrestashopCheckout\Http\PsrClientAdapter; +use Psr\Http\Message\RequestInterface; -/** - * Construct the client used to make call to maasland - */ -class PaymentClient extends GenericClient +class PaymentClient implements HttpClientInterface { - /** - * @param Link $link - * @param object|null $client - */ - public function __construct(Link $link, $client = null) - { - parent::__construct(); - - $this->setLink($link); - - // Client can be provided for tests - if (null === $client) { - /** @var Ps_checkout $module */ - $module = Module::getInstanceByName('ps_checkout'); - - /** @var Version $version */ - $version = $module->getService('ps_checkout.module.version'); - - /** @var LoggerConfiguration $loggerConfiguration */ - $loggerConfiguration = $module->getService('ps_checkout.logger.configuration'); - - /** @var LoggerInterface $logger */ - $logger = $module->getService('ps_checkout.logger'); - - /** @var Router $router */ - $router = $module->getService('ps_checkout.prestashop.router'); - - $clientConfiguration = [ - 'base_url' => (new PaymentEnv())->getPaymentApiUrl(), - 'verify' => $this->getVerify(), - 'timeout' => $this->timeout, - 'exceptions' => $this->catchExceptions, - 'headers' => [ - 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $this->token, // Token we get from PsAccounts - 'Shop-Id' => $this->shopUid, // Shop UUID we get from PsAccounts - 'Hook-Url' => $router->getDispatchWebhookLink((int) Context::getContext()->shop->id), - 'Bn-Code' => (new ShopContext())->getBnCode(), - 'Module-Version' => $version->getSemVersion(), // version of the module - 'Prestashop-Version' => _PS_VERSION_, // prestashop version - ], - ]; - - if ( - $loggerConfiguration->isHttpEnabled() - && defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION') - && class_exists(HandlerStack::class) - && class_exists(LogMiddleware::class) - ) { - $handlerStack = HandlerStack::create(); - $handlerStack->push(new LogMiddleware($logger)); - $clientConfiguration['handler'] = $handlerStack; - } elseif ( - $loggerConfiguration->isHttpEnabled() - && defined('\GuzzleHttp\ClientInterface::VERSION') - && class_exists(Emitter::class) - && class_exists(LogSubscriber::class) - && class_exists(Formatter::class) - ) { - $emitter = new Emitter(); - $emitter->attach(new LogSubscriber( - $logger, - Formatter::DEBUG - )); - - $clientConfiguration['emitter'] = $emitter; - } - - $client = (new ClientFactory())->getClient($clientConfiguration); - } - - $this->setClient($client); - } + /** @var PsrClientAdapter */ + private $client; - /** - * @param array $options - * - * @return array - * - * @throws HttpTimeoutException - */ - protected function post(array $options = []) - { - $delay = isset($options['delay']) ? (int) $options['delay'] : 2; - $retries = isset($options['retries']) ? (int) $options['retries'] : 2; - unset($options['delay'], $options['retries']); - - return $this->postWithRetry($options, $delay, $retries); - } - - /** - * @param array $options - * @param int $delay - * @param int $retries - * - * @return array - * - * @throws HttpTimeoutException - * @throws PsCheckoutException - */ - private function postWithRetry(array $options, $delay = 2, $retries = 2) + public function __construct(PaymentClientConfigurationBuilder $configurationBuilder) { - try { - $response = parent::post($options); - - if ($response['httpCode'] === 401 || false !== strpos($response['exceptionMessage'], 'Unauthorized')) { - throw new PsCheckoutException('Unauthorized', PsCheckoutException::PSCHECKOUT_HTTP_UNAUTHORIZED); - } - - if (false !== $response['status']) { - return $response; - } - - if ( - isset($response['exceptionCode']) - && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION - && false !== strpos($response['exceptionMessage'], 'cURL error 28') - ) { - throw new HttpTimeoutException($response['exceptionMessage'], PsCheckoutException::PSL_TIMEOUT); - } elseif ( - isset($response['exceptionCode']) - && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION - ) { - throw new PsCheckoutException($response['exceptionMessage'], PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION); - } - - if ( - isset($response['body']['message']) - && ($response['body']['message'] === 'Error: ETIMEDOUT' || $response['body']['message'] === 'Error: ESOCKETTIMEDOUT') - ) { - throw new HttpTimeoutException($response['body']['message'], PsCheckoutException::PSL_TIMEOUT); - } - } catch (HttpTimeoutException $exception) { - if ($this->isRouteRetryable() && $retries > 0) { - sleep($delay); - - return $this->postWithRetry($options, $delay, $retries - 1); - } - - throw $exception; - } - - return $response; + $this->client = new PsrClientAdapter($configurationBuilder->build()); } /** - * @return bool + * {@inheritdoc} */ - private function isRouteRetryable() + public function sendRequest(RequestInterface $request) { - switch ($this->getRoute()) { - case '/payments/order/capture': - case '/payments/order/refund': - return false; - } - - return true; + return $this->client->sendRequest($request); } } diff --git a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php b/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php new file mode 100755 index 000000000..b485c8e32 --- /dev/null +++ b/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php @@ -0,0 +1,89 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; + +use PrestaShop\Module\PrestashopCheckout\Configuration\PrestaShopConfiguration; +use PrestaShop\Module\PrestashopCheckout\Environment\Env; +use PrestaShop\Module\PrestashopCheckout\Repository\PsAccountRepository; +use PrestaShop\Module\PrestashopCheckout\Routing\Router; +use PrestaShop\Module\PrestashopCheckout\ShopContext; +use Ps_checkout; + +class PaymentClientConfigurationBuilder +{ + const TIMEOUT = 10; + + /** @var Env */ + private $env; + + /** @var Router */ + private $router; + + /** @var ShopContext */ + private $shopContext; + + /** @var PsAccountRepository */ + private $psAccountRepository; + + /** @var PrestaShopConfiguration */ + private $prestaShopConfiguration; + + /** @var CertFileProvider */ + private $certFileProvider; + + public function __construct( + Env $env, + Router $router, + ShopContext $shopContext, + PsAccountRepository $psAccountRepository, + PrestaShopConfiguration $prestaShopConfiguration, + CertFileProvider $certFileProvider + ) { + $this->env = $env; + $this->router = $router; + $this->shopContext = $shopContext; + $this->psAccountRepository = $psAccountRepository; + $this->prestaShopConfiguration = $prestaShopConfiguration; + $this->certFileProvider = $certFileProvider; + } + + /** + * @return array + */ + public function build() + { + return [ + 'base_url' => $this->env->getPaymentApiUrl(), + 'verify' => $this->certFileProvider->getPath(), + 'timeout' => static::TIMEOUT, + 'headers' => [ + 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) + 'Accept' => 'application/json', + 'Authorization' => 'Bearer ' . $this->psAccountRepository->getIdToken(), // Token we get from PsAccounts + 'Shop-Id' => $this->psAccountRepository->getShopUuid(), // Shop UUID we get from PsAccounts + 'Hook-Url' => $this->router->getDispatchWebhookLink((int) Context::getContext()->shop->id), + 'Bn-Code' => $this->shopContext->getBnCode(), + 'Module-Version' => Ps_checkout::VERSION, // version of the module + 'Prestashop-Version' => _PS_VERSION_, // prestashop version + ], + ]; + } +} diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php new file mode 100644 index 000000000..090e261c3 --- /dev/null +++ b/src/Api/Payment/PaymentService.php @@ -0,0 +1,227 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; + +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception\HttpException; +use Http\Client\Exception\NetworkException; +use Http\Client\Exception\RequestException; +use Http\Client\Exception\TransferException; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use Psr\Http\Message\ResponseInterface; + +class PaymentService +{ + /** + * @var PaymentClient + */ + private $client; + + public function __construct(PaymentClient $client) + { + $this->client = $client; + } + + public function createOrder(array $payload) + { + try { + return $this->sendRequest('POST', '/payments/order/create', [], $payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + if ($response->getStatusCode() === 400) { + // INVALID_REQUEST : + // - INVALID_ARRAY_MAX_ITEMS + // - INVALID_ARRAY_MIN_ITEMS + // - INVALID_COUNTRY_CODE + // - INVALID_PARAMETER_SYNTAX + // - INVALID_STRING_LENGTH + // - INVALID_PARAMETER_VALUE + // - MISSING_REQUIRED_PARAMETER + // - NOT_SUPPORTED + // - PAYPAL_REQUEST_ID_REQUIRED + // - MALFORMED_REQUEST_JSON + } + if ($response->getStatusCode() === 401) { + // NOT_AUTHORIZED + // - PERMISSION_DENIED + // - PERMISSION_DENIED_FOR_DONATION_ITEMS + // - MALFORMED_REQUEST + } + if ($response->getStatusCode() === 422) { + // UNPROCESSABLE_ENTITY + // - AMOUNT_MISMATCH + // - BILLING_ADDRESS_INVALID + // - CANNOT_BE_NEGATIVE + // - CANNOT_BE_ZERO_OR_NEGATIVE + // - CARD_EXPIRED + // - CITY_REQUIRED + // - DECIMAL_PRECISION + // - DONATION_ITEMS_NOT_SUPPORTED + // - DUPLICATE_REFERENCE_ID + // - INVALID_CURRENCY_CODE + // - INVALID_PAYER_ID + // - ITEM_TOTAL_MISMATCH + // - ITEM_TOTAL_REQUIRED + // - MAX_VALUE_EXCEEDED + // - MISSING_PICKUP_ADDRESS + // - MULTI_CURRENCY_ORDER + // - MULTIPLE_ITEM_CATEGORIES + // - MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED + // - MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED + // - PAYEE_ACCOUNT_INVALID + // - PAYEE_ACCOUNT_LOCKED_OR_CLOSED + // - PAYEE_ACCOUNT_RESTRICTED + // - REFERENCE_ID_REQUIRED + // - PAYMENT_SOURCE_CANNOT_BE_USED + // - PAYMENT_SOURCE_DECLINED_BY_PROCESSOR + // - PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED + // - POSTAL_CODE_REQUIRED + // - SHIPPING_ADDRESS_INVALID + // - TAX_TOTAL_MISMATCH + // - TAX_TOTAL_REQUIRED + // - UNSUPPORTED_INTENT + // - UNSUPPORTED_PAYMENT_INSTRUCTION + // - SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT + // - UNSUPPORTED_SHIPPING_TYPE + // - SHIPPING_OPTION_NOT_SELECTED + // - SHIPPING_OPTIONS_NOT_SUPPORTED + // - MULTIPLE_SHIPPING_OPTION_SELECTED + // - PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH + // - CARD_CLOSED + // - ORDER_CANNOT_BE_SAVED + // - SAVE_ORDER_NOT_SUPPORTED + // - PUI_DUPLICATE_ORDER + } + } + } + + public function updateOrder(array $payload) + { + return $this->sendRequest('POST', '/payments/order/update', [], $payload); + } + + /** + * @param array{order_id: string} $data + * + * @return ResponseInterface + */ + public function getOrder(array $data) + { + $payload = [ + 'orderId' => $data['order_id'], + ]; + return $this->sendRequest('POST', '/payments/order/fetch', [], $payload); + } + + /** + * @param array{funding_source: string, order_id: string, merchant_id: string} $data + * + * @return ResponseInterface + */ + public function captureOrder(array $data) + { + $payload = [ + 'mode' => $data['funding_source'], + 'orderId' => (string) $data['order_id'], + 'payee' => [ + 'merchant_id' => $data['merchant_id'], + ], + ]; + return $this->sendRequest('POST', '/payments/order/capture', [], $payload); + } + + public function refundOrder(array $payload) + { + return $this->sendRequest('POST', '/payments/order/refund', [], $payload); + } + + /** + * @param array{merchant_id: string} $data + * + * @return ResponseInterface + */ + public function getIdentityToken(array $data) + { + $payload = [ + 'return_payload' => true, + 'payee' => [ + 'merchant_id' => $data['merchant_id'], + ], + ]; + + try { + return $this->sendRequest('POST', '/payments/order/generate_client_token', [], $payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + if ($response->getStatusCode() === 400) { + // INVALID_REQUEST + } + if ($response->getStatusCode() === 401) { + // NOT_AUTHORIZED + } + if ($response->getStatusCode() === 404) { + // RESOURCE_NOT_FOUND + } + if ($response->getStatusCode() === 422) { + // UNPROCESSABLE_ENTITY + } + } + } + + /** + * @param string $method + * @param string $uri + * @param array $options + * @param array $payload + * + * @return ResponseInterface + * + * @throws NetworkException + * @throws HttpException + * @throws RequestException + * @throws TransferException + */ + private function sendRequest($method, $uri, $options, $payload) + { + try { + return $this->client->sendRequest(new Request($method, $uri, $options, json_encode($payload))); + } catch (NetworkException $exception) { + // Thrown when the request cannot be completed because of network issues. + // No response here + } catch (HttpException $exception) { + // Thrown when a response was received but the request itself failed. + // There a response here + // So this one contains why response failed with Maasland error response + if ($exception->getResponse()->getStatusCode() === 500) { + // Internal Server Error: retry then stop using Maasland for XXX times after X failed retries, requires a circuit breaker + } + if ($exception->getResponse()->getStatusCode() === 503) { + // Service Unavailable: we should stop using Maasland, requires a circuit breaker + } + // response status code 4XX throw exception to be catched on specific method + throw $exception; // Avoid this to be catched next + } catch (RequestException $exception) { + // No response here + } catch (TransferException $exception) { + // others without response + } + } +} diff --git a/src/Api/Payment/Service/PaymentService.php b/src/Api/Payment/Service/PaymentService.php new file mode 100755 index 000000000..b600f3971 --- /dev/null +++ b/src/Api/Payment/Service/PaymentService.php @@ -0,0 +1,67 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Service; + +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; + +class PaymentService +{ + /** @var PaymentClient */ + private $paymentClient; + + /** + * @param PaymentClient $paymentClient + */ + public function __construct(PaymentClient $paymentClient) + { + $this->paymentClient = $paymentClient; + } + + public function createOrder(array $data) + { + // TODO + } + + public function updateOrder(array $data) + { + // TODO + } + + public function getOrder(array $data) + { + // TODO + } + + public function captureOrder(array $data) + { + // TODO + } + + public function refundOrder(array $data) + { + // TODO + } + + public function getIdentityToken(array $data) + { + // TODO + } +} diff --git a/src/Api/Payment/Shop.php b/src/Api/Payment/Shop.php index 0d13aa4be..85e74cb84 100644 --- a/src/Api/Payment/Shop.php +++ b/src/Api/Payment/Shop.php @@ -20,14 +20,14 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\OldPaymentClient; use PrestaShop\Module\PrestashopCheckout\Configuration\PrestaShopConfiguration; use PrestaShop\Module\PrestashopCheckout\ExpressCheckout\ExpressCheckoutConfiguration; /** * Handle request to maasland regarding the shop/merchant status */ -class Shop extends PaymentClient +class Shop extends OldPaymentClient { /** * Used to notify PSL on settings update diff --git a/src/Api/Payment/Webhook.php b/src/Api/Payment/Webhook.php index 5fd511005..16338040c 100644 --- a/src/Api/Payment/Webhook.php +++ b/src/Api/Payment/Webhook.php @@ -20,12 +20,12 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\OldPaymentClient; /** * Handle Webhook requests */ -class Webhook extends PaymentClient +class Webhook extends OldPaymentClient { /** * Tells if the webhook came from the PSL diff --git a/src/Http/PsrClientAdapter.php b/src/Http/PsrClientAdapter.php new file mode 100644 index 000000000..fcef2a437 --- /dev/null +++ b/src/Http/PsrClientAdapter.php @@ -0,0 +1,45 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Http; + +use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; +use Psr\Http\Message\RequestInterface; + +class PsrClientAdapter implements HttpClientInterface +{ + private $client; + + /** + * @param array $configuration + */ + public function __construct(array $configuration) + { + $this->client = (new ClientFactory())->getClient($configuration); + } + + /** + * {@inheritdoc} + */ + public function sendRequest(RequestInterface $request) + { + return $this->client->sendRequest($request); + } +} From 6dd7d1c31e0c13c39eecd156d8832174457818ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20=C5=A0edys?= Date: Tue, 13 Feb 2024 13:01:14 +0200 Subject: [PATCH 02/26] Modified payment client and configuration builder (#1199) * Modified payment client and configuration builder * Changed PayPalClient name * Added builder interface * CS fix --- config/common.yml | 20 ++++++++ ...ntClient.php => PayPalOrderHttpClient.php} | 20 ++------ src/Api/Payment/PaymentService.php | 17 +++++-- src/Api/Payment/Service/PaymentService.php | 8 +-- .../ConfigurationBuilderInterface.php} | 24 ++------- .../PaymentClientConfigurationBuilder.php | 51 +++++++++++-------- src/Http/PsrHttpClientAdapter.php | 2 +- 7 files changed, 77 insertions(+), 65 deletions(-) rename src/Api/Payment/Client/{PaymentClient.php => PayPalOrderHttpClient.php} (66%) rename src/{Http/PsrClientAdapter.php => Builder/Configuration/ConfigurationBuilderInterface.php} (60%) rename src/{Api/Payment/Client => Builder/Configuration}/PaymentClientConfigurationBuilder.php (68%) diff --git a/config/common.yml b/config/common.yml index f94a67ac5..65cfa2487 100644 --- a/config/common.yml +++ b/config/common.yml @@ -703,6 +703,26 @@ services: arguments: - "@ps_checkout.logger" + PrestaShop\Module\PrestashopCheckout\Environment\Env: + class: 'PrestaShop\Module\PrestashopCheckout\Environment\Env' + + PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv: + class: 'PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv' + + PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder: + class: 'PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' + arguments: + - '@PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv' + - '@ps_checkout.prestashop.router' + - '@ps_checkout.context.shop' + - '@ps_checkout.repository.prestashop.account' + - '@ps_checkout.context.prestashop' + + PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient: + class: 'PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient' + arguments: + - '@PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' + ps_checkout.environment.payment: class: 'PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv' public: true diff --git a/src/Api/Payment/Client/PaymentClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php similarity index 66% rename from src/Api/Payment/Client/PaymentClient.php rename to src/Api/Payment/Client/PayPalOrderHttpClient.php index 6b66b23d2..c9860aa3a 100755 --- a/src/Api/Payment/Client/PaymentClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -20,25 +20,13 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; -use PrestaShop\Module\PrestashopCheckout\Http\HttpClientInterface; -use PrestaShop\Module\PrestashopCheckout\Http\PsrClientAdapter; -use Psr\Http\Message\RequestInterface; +use PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder; +use PrestaShop\Module\PrestashopCheckout\Http\PsrHttpClientAdapter; -class PaymentClient implements HttpClientInterface +class PayPalOrderHttpClient extends PsrHttpClientAdapter { - /** @var PsrClientAdapter */ - private $client; - public function __construct(PaymentClientConfigurationBuilder $configurationBuilder) { - $this->client = new PsrClientAdapter($configurationBuilder->build()); - } - - /** - * {@inheritdoc} - */ - public function sendRequest(RequestInterface $request) - { - return $this->client->sendRequest($request); + parent::__construct($configurationBuilder->build()); } } diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 090e261c3..6f79ba9b3 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -25,17 +25,17 @@ use Http\Client\Exception\NetworkException; use Http\Client\Exception\RequestException; use Http\Client\Exception\TransferException; -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; use Psr\Http\Message\ResponseInterface; class PaymentService { /** - * @var PaymentClient + * @var PayPalOrderHttpClient */ private $client; - public function __construct(PaymentClient $client) + public function __construct(PayPalOrderHttpClient $client) { $this->client = $client; } @@ -128,6 +128,7 @@ public function getOrder(array $data) $payload = [ 'orderId' => $data['order_id'], ]; + return $this->sendRequest('POST', '/payments/order/fetch', [], $payload); } @@ -145,6 +146,7 @@ public function captureOrder(array $data) 'merchant_id' => $data['merchant_id'], ], ]; + return $this->sendRequest('POST', '/payments/order/capture', [], $payload); } @@ -183,6 +185,8 @@ public function getIdentityToken(array $data) if ($response->getStatusCode() === 422) { // UNPROCESSABLE_ENTITY } + + return $response; } } @@ -204,6 +208,7 @@ private function sendRequest($method, $uri, $options, $payload) try { return $this->client->sendRequest(new Request($method, $uri, $options, json_encode($payload))); } catch (NetworkException $exception) { + throw $exception; // TODO Replace // Thrown when the request cannot be completed because of network issues. // No response here } catch (HttpException $exception) { @@ -211,16 +216,20 @@ private function sendRequest($method, $uri, $options, $payload) // There a response here // So this one contains why response failed with Maasland error response if ($exception->getResponse()->getStatusCode() === 500) { + throw $exception; // TODO Replace // Internal Server Error: retry then stop using Maasland for XXX times after X failed retries, requires a circuit breaker } if ($exception->getResponse()->getStatusCode() === 503) { + throw $exception; // TODO Replace // Service Unavailable: we should stop using Maasland, requires a circuit breaker } // response status code 4XX throw exception to be catched on specific method throw $exception; // Avoid this to be catched next } catch (RequestException $exception) { - // No response here + throw $exception; // TODO Replace + // No response here } catch (TransferException $exception) { + throw $exception; // TODO Replace // others without response } } diff --git a/src/Api/Payment/Service/PaymentService.php b/src/Api/Payment/Service/PaymentService.php index b600f3971..86fa5407c 100755 --- a/src/Api/Payment/Service/PaymentService.php +++ b/src/Api/Payment/Service/PaymentService.php @@ -20,17 +20,17 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Service; -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; class PaymentService { - /** @var PaymentClient */ + /** @var PayPalOrderHttpClient */ private $paymentClient; /** - * @param PaymentClient $paymentClient + * @param PayPalOrderHttpClient $paymentClient */ - public function __construct(PaymentClient $paymentClient) + public function __construct(PayPalOrderHttpClient $paymentClient) { $this->paymentClient = $paymentClient; } diff --git a/src/Http/PsrClientAdapter.php b/src/Builder/Configuration/ConfigurationBuilderInterface.php similarity index 60% rename from src/Http/PsrClientAdapter.php rename to src/Builder/Configuration/ConfigurationBuilderInterface.php index fcef2a437..b3a0fbc9e 100644 --- a/src/Http/PsrClientAdapter.php +++ b/src/Builder/Configuration/ConfigurationBuilderInterface.php @@ -18,28 +18,12 @@ * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 */ -namespace PrestaShop\Module\PrestashopCheckout\Http; +namespace PrestaShop\Module\PrestashopCheckout\Builder\Configuration; -use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; -use Psr\Http\Message\RequestInterface; - -class PsrClientAdapter implements HttpClientInterface +interface ConfigurationBuilderInterface { - private $client; - - /** - * @param array $configuration - */ - public function __construct(array $configuration) - { - $this->client = (new ClientFactory())->getClient($configuration); - } - /** - * {@inheritdoc} + * @return array */ - public function sendRequest(RequestInterface $request) - { - return $this->client->sendRequest($request); - } + public function build(); } diff --git a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php b/src/Builder/Configuration/PaymentClientConfigurationBuilder.php similarity index 68% rename from src/Api/Payment/Client/PaymentClientConfigurationBuilder.php rename to src/Builder/Configuration/PaymentClientConfigurationBuilder.php index b485c8e32..9361274c6 100755 --- a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php +++ b/src/Builder/Configuration/PaymentClientConfigurationBuilder.php @@ -18,21 +18,21 @@ * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 */ -namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; +namespace PrestaShop\Module\PrestashopCheckout\Builder\Configuration; -use PrestaShop\Module\PrestashopCheckout\Configuration\PrestaShopConfiguration; -use PrestaShop\Module\PrestashopCheckout\Environment\Env; +use PrestaShop\Module\PrestashopCheckout\Context\PrestaShopContext; +use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; use PrestaShop\Module\PrestashopCheckout\Repository\PsAccountRepository; use PrestaShop\Module\PrestashopCheckout\Routing\Router; use PrestaShop\Module\PrestashopCheckout\ShopContext; use Ps_checkout; -class PaymentClientConfigurationBuilder +class PaymentClientConfigurationBuilder implements ConfigurationBuilderInterface { const TIMEOUT = 10; - /** @var Env */ - private $env; + /** @var PaymentEnv */ + private $paymentEnv; /** @var Router */ private $router; @@ -43,26 +43,23 @@ class PaymentClientConfigurationBuilder /** @var PsAccountRepository */ private $psAccountRepository; - /** @var PrestaShopConfiguration */ - private $prestaShopConfiguration; - - /** @var CertFileProvider */ - private $certFileProvider; + /** + * @var PrestaShopContext + */ + private $prestaShopContext; public function __construct( - Env $env, + PaymentEnv $paymentEnv, Router $router, ShopContext $shopContext, PsAccountRepository $psAccountRepository, - PrestaShopConfiguration $prestaShopConfiguration, - CertFileProvider $certFileProvider + PrestaShopContext $prestaShopContext ) { - $this->env = $env; + $this->paymentEnv = $paymentEnv; $this->router = $router; $this->shopContext = $shopContext; $this->psAccountRepository = $psAccountRepository; - $this->prestaShopConfiguration = $prestaShopConfiguration; - $this->certFileProvider = $certFileProvider; + $this->prestaShopContext = $prestaShopContext; } /** @@ -71,19 +68,33 @@ public function __construct( public function build() { return [ - 'base_url' => $this->env->getPaymentApiUrl(), - 'verify' => $this->certFileProvider->getPath(), + 'base_url' => $this->paymentEnv->getPaymentApiUrl(), + 'verify' => $this->getVerify(), 'timeout' => static::TIMEOUT, 'headers' => [ 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $this->psAccountRepository->getIdToken(), // Token we get from PsAccounts 'Shop-Id' => $this->psAccountRepository->getShopUuid(), // Shop UUID we get from PsAccounts - 'Hook-Url' => $this->router->getDispatchWebhookLink((int) Context::getContext()->shop->id), + 'Hook-Url' => $this->router->getDispatchWebhookLink($this->prestaShopContext->getShopId()), 'Bn-Code' => $this->shopContext->getBnCode(), 'Module-Version' => Ps_checkout::VERSION, // version of the module 'Prestashop-Version' => _PS_VERSION_, // prestashop version ], ]; } + + /** + * @see https://docs.guzzlephp.org/en/5.3/clients.html#verify + * + * @return true|string + */ + protected function getVerify() + { + if (defined('_PS_CACHE_CA_CERT_FILE_') && file_exists(constant('_PS_CACHE_CA_CERT_FILE_'))) { + return constant('_PS_CACHE_CA_CERT_FILE_'); + } + + return true; + } } diff --git a/src/Http/PsrHttpClientAdapter.php b/src/Http/PsrHttpClientAdapter.php index 513f4b5e7..4a285b2f7 100644 --- a/src/Http/PsrHttpClientAdapter.php +++ b/src/Http/PsrHttpClientAdapter.php @@ -26,7 +26,7 @@ use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; use Psr\Http\Message\RequestInterface; -class PsrHttpClientAdapter implements HttpClientInterface +abstract class PsrHttpClientAdapter implements HttpClientInterface { private $client; From 29aebcc3f6a57d6eb5fce21bd35cfba9140f4bb4 Mon Sep 17 00:00:00 2001 From: Matthias RAIGNE <5262628+Matt75@users.noreply.github.com> Date: Tue, 13 Feb 2024 12:36:28 +0100 Subject: [PATCH 03/26] PAYSHIP-2630 (#1182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Replace client token by user id token * Implement payment method token * Interfaces * PAYSHIP-2631 PayPal Create Order Request DTO * Added correct class import * [PAYSHIP-2637] CreatePayPalOrderResponse DTO (#1189) * Added CreatePayPalOrderResponse DTO * Added DTOs for create order response * CS fix * Added licenses * [PAYSHIP-2632] Order create refactoring (#1183) * Created required classes * Added order create command handler logic * Added paypal order query handler * Moved QueryResult to Query namespace * Added create command and get order query to command bus factory * CS fix * PHPStan fixes * Reverted to old create handler * PHPStan fixes * Fixed regex and wrong customerId type --------- Co-authored-by: Laurynas Co-authored-by: Laurynas Šedys --- config/common.yml | 23 +- controllers/front/create.php | 9 + controllers/front/vault.php | 71 +++ src/Cart/CartInterface.php | 45 ++ src/Cart/CartRepositoryInterface.php | 36 ++ .../SavePayPalOrderStatusCommandHandler.php | 1 + src/Controller/AbstractFrontController.php | 32 +- src/Database/TableManager.php | 14 + src/Handler/CreatePaypalOrderHandler.php | 6 +- .../Customer/PayPalCustomerRepository.php | 88 +++ .../Customer/ValueObject/PayPalCustomerId.php | 74 +++ src/PayPal/OAuth/OAuthService.php | 66 +++ .../Query/GetPayPalGetUserIdTokenQuery.php | 47 ++ .../GetPayPalGetUserIdTokenQueryHandler.php | 62 +++ .../GetPayPalGetUserIdTokenQueryResult.php | 45 ++ .../CreatePayPalOrderCommandHandler.php | 68 +-- ...eatePayPalOrderPayloadBuilderInterface.php | 35 ++ src/PayPal/Order/DTO/AddressDetails.php | 220 ++++++++ src/PayPal/Order/DTO/AddressPortable2.php | 342 ++++++++++++ src/PayPal/Order/DTO/AddressRequest.php | 231 ++++++++ src/PayPal/Order/DTO/Amount.php | 70 +++ src/PayPal/Order/DTO/AmountBreakdown.php | 179 +++++++ src/PayPal/Order/DTO/AmountWithBreakdown.php | 47 ++ .../Order/DTO/ApplePayAttributesRequest.php | 69 +++ src/PayPal/Order/DTO/ApplePayRequest.php | 179 +++++++ .../Order/DTO/ApplicationContextRequest.php | 47 ++ .../Order/DTO/AuthenticationResponse.php | 153 ++++++ .../DTO/AuthorizationWithAdditionalData.php | 439 +++++++++++++++ src/PayPal/Order/DTO/Bancontact.php | 223 ++++++++ src/PayPal/Order/DTO/BancontactRequest.php | 91 ++++ src/PayPal/Order/DTO/BinDetails.php | 161 ++++++ src/PayPal/Order/DTO/Blik.php | 159 ++++++ src/PayPal/Order/DTO/BlikOneClickResponse.php | 65 +++ src/PayPal/Order/DTO/BlikRequest.php | 113 ++++ src/PayPal/Order/DTO/Capture.php | 499 ++++++++++++++++++ .../Order/DTO/CardAttributesRequest.php | 91 ++++ .../Order/DTO/CardAttributesResponse.php | 63 +++ .../DTO/CardExperienceContextRequest.php | 69 +++ src/PayPal/Order/DTO/CardFromRequest.php | 97 ++++ src/PayPal/Order/DTO/CardRequest.php | 157 ++++++ src/PayPal/Order/DTO/CardResponse.php | 343 ++++++++++++ .../DTO/CardStoredCredentialsRequest.php | 113 ++++ .../Order/DTO/CardSupplementaryData.php | 92 ++++ .../DTO/CardSupplementaryDataRequest.php | 69 +++ src/PayPal/Order/DTO/CardVerification.php | 47 ++ src/PayPal/Order/DTO/CobrandedCard.php | 123 +++++ .../Order/DTO/CreatePayPalOrderRequest.php | 135 +++++ .../Order/DTO/CreatePayPalOrderResponse.php | 226 ++++++++ src/PayPal/Order/DTO/Customer.php | 127 +++++ src/PayPal/Order/DTO/CustomerRequest.php | 91 ++++ src/PayPal/Order/DTO/Eps.php | 129 +++++ src/PayPal/Order/DTO/EpsRequest.php | 91 ++++ src/PayPal/Order/DTO/ExchangeRate.php | 129 +++++ .../Order/DTO/ExperienceContextRequest.php | 135 +++++ src/PayPal/Order/DTO/Giropay.php | 129 +++++ src/PayPal/Order/DTO/GiropayRequest.php | 91 ++++ src/PayPal/Order/DTO/GooglePayRequest.php | 113 ++++ src/PayPal/Order/DTO/Ideal.php | 191 +++++++ src/PayPal/Order/DTO/IdealRequest.php | 113 ++++ src/PayPal/Order/DTO/Item.php | 253 +++++++++ src/PayPal/Order/DTO/ItemRequest.php | 179 +++++++ .../Order/DTO/Level2CardProcessingData.php | 94 ++++ .../DTO/Level2CardProcessingDataRequest.php | 69 +++ .../Order/DTO/Level3CardProcessingData.php | 212 ++++++++ .../DTO/Level3CardProcessingDataRequest.php | 157 ++++++ src/PayPal/Order/DTO/LineItem.php | 367 +++++++++++++ src/PayPal/Order/DTO/LineItemRequest.php | 267 ++++++++++ src/PayPal/Order/DTO/LinkDescription.php | 129 +++++ .../Order/DTO/MerchantPayableBreakdown.php | 277 ++++++++++ src/PayPal/Order/DTO/MyBankRequest.php | 91 ++++ src/PayPal/Order/DTO/Mybank.php | 161 ++++++ src/PayPal/Order/DTO/Name.php | 179 +++++++ .../Order/DTO/NetAmountBreakdownItem.php | 123 +++++ .../Order/DTO/NetworkTransactionReference.php | 159 ++++++ src/PayPal/Order/DTO/P24.php | 225 ++++++++ src/PayPal/Order/DTO/P24Request.php | 113 ++++ src/PayPal/Order/DTO/PayPalRequest.php | 245 +++++++++ .../DTO/PayPalWalletAttributesRequest.php | 69 +++ .../DTO/PayPalWalletExperienceContext.php | 201 +++++++ .../PayPalWalletVaultAttributesRequest.php | 179 +++++++ src/PayPal/Order/DTO/Payee.php | 97 ++++ src/PayPal/Order/DTO/PayeeRequest.php | 69 +++ src/PayPal/Order/DTO/Payer.php | 165 ++++++ src/PayPal/Order/DTO/PaymentCollection.php | 129 +++++ src/PayPal/Order/DTO/PaymentInstruction.php | 159 ++++++ src/PayPal/Order/DTO/PaymentSourceRequest.php | 333 ++++++++++++ .../Order/DTO/PaymentSourceResponse.php | 393 ++++++++++++++ .../DTO/PaypalWalletAttributesResponse.php | 94 ++++ src/PayPal/Order/DTO/PaypalWalletResponse.php | 309 +++++++++++ src/PayPal/Order/DTO/Phone.php | 91 ++++ src/PayPal/Order/DTO/PhoneWithType.php | 69 +++ src/PayPal/Order/DTO/PlatformFee.php | 93 ++++ ...iousNetworkTransactionReferenceRequest.php | 113 ++++ src/PayPal/Order/DTO/ProcessorResponse.php | 161 ++++++ src/PayPal/Order/DTO/PurchaseUnit.php | 444 ++++++++++++++++ src/PayPal/Order/DTO/PurchaseUnitRequest.php | 245 +++++++++ src/PayPal/Order/DTO/Reason.php | 65 +++ src/PayPal/Order/DTO/Refund.php | 441 ++++++++++++++++ src/PayPal/Order/DTO/SellerProtection.php | 97 ++++ .../Order/DTO/SellerReceivableBreakdown.php | 245 +++++++++ src/PayPal/Order/DTO/ShippingOption.php | 189 +++++++ .../Order/DTO/ShippingOptionRequest.php | 135 +++++ src/PayPal/Order/DTO/ShippingRequest.php | 113 ++++ .../Order/DTO/ShippingWithTrackingDetails.php | 189 +++++++ src/PayPal/Order/DTO/Sofort.php | 161 ++++++ src/PayPal/Order/DTO/SofortRequest.php | 91 ++++ .../Order/DTO/StoredPaymentSourceRequest.php | 113 ++++ src/PayPal/Order/DTO/SupplementaryData.php | 63 +++ .../Order/DTO/SupplementaryDataRequest.php | 47 ++ src/PayPal/Order/DTO/TaxInfo.php | 69 +++ .../ThreeDSecureAuthenticationResponse.php | 93 ++++ src/PayPal/Order/DTO/TokenRequest.php | 69 +++ src/PayPal/Order/DTO/Tracker.php | 223 ++++++++ src/PayPal/Order/DTO/TrackerItem.php | 187 +++++++ src/PayPal/Order/DTO/Trustly.php | 161 ++++++ .../Order/DTO/VaultAttributesRequest.php | 47 ++ src/PayPal/Order/DTO/VaultResponse.php | 159 ++++++ .../DTO/VenmoExperienceContextRequest.php | 69 +++ src/PayPal/Order/DTO/VenmoRequest.php | 113 ++++ .../DTO/VenmoWalletAttributesResponse.php | 63 +++ src/PayPal/Order/DTO/VenmoWalletResponse.php | 249 +++++++++ .../PayPalOrderEventSubscriber.php | 12 +- .../Order/PayPalOrderHttpClientInterface.php | 37 ++ .../Order/Query/GetPayPalOrderQuery.php | 59 +++ .../Order/Query/GetPayPalOrderQueryResult.php | 46 ++ .../GetPayPalOrderQueryHandler.php | 64 +++ .../PaymentMethodTokenRepository.php | 131 +++++ .../PaymentMethodTokenService.php | 60 +++ .../GetCustomerPaymentMethodTokensQuery.php | 92 ++++ ...ustomerPaymentMethodTokensQueryHandler.php | 76 +++ ...CustomerPaymentMethodTokensQueryResult.php | 92 ++++ .../ValueObject/PaymentMethodTokenId.php | 74 +++ .../DTO/CreatePayPalOrderRequestTest.php | 96 ++++ 133 files changed, 17915 insertions(+), 61 deletions(-) create mode 100644 controllers/front/vault.php create mode 100644 src/Cart/CartInterface.php create mode 100644 src/Cart/CartRepositoryInterface.php create mode 100644 src/PayPal/Customer/PayPalCustomerRepository.php create mode 100644 src/PayPal/Customer/ValueObject/PayPalCustomerId.php create mode 100644 src/PayPal/OAuth/OAuthService.php create mode 100644 src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQuery.php create mode 100644 src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryHandler.php create mode 100644 src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryResult.php create mode 100644 src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php create mode 100644 src/PayPal/Order/DTO/AddressDetails.php create mode 100644 src/PayPal/Order/DTO/AddressPortable2.php create mode 100644 src/PayPal/Order/DTO/AddressRequest.php create mode 100644 src/PayPal/Order/DTO/Amount.php create mode 100644 src/PayPal/Order/DTO/AmountBreakdown.php create mode 100644 src/PayPal/Order/DTO/AmountWithBreakdown.php create mode 100644 src/PayPal/Order/DTO/ApplePayAttributesRequest.php create mode 100644 src/PayPal/Order/DTO/ApplePayRequest.php create mode 100644 src/PayPal/Order/DTO/ApplicationContextRequest.php create mode 100644 src/PayPal/Order/DTO/AuthenticationResponse.php create mode 100644 src/PayPal/Order/DTO/AuthorizationWithAdditionalData.php create mode 100644 src/PayPal/Order/DTO/Bancontact.php create mode 100644 src/PayPal/Order/DTO/BancontactRequest.php create mode 100644 src/PayPal/Order/DTO/BinDetails.php create mode 100644 src/PayPal/Order/DTO/Blik.php create mode 100644 src/PayPal/Order/DTO/BlikOneClickResponse.php create mode 100644 src/PayPal/Order/DTO/BlikRequest.php create mode 100644 src/PayPal/Order/DTO/Capture.php create mode 100644 src/PayPal/Order/DTO/CardAttributesRequest.php create mode 100644 src/PayPal/Order/DTO/CardAttributesResponse.php create mode 100644 src/PayPal/Order/DTO/CardExperienceContextRequest.php create mode 100644 src/PayPal/Order/DTO/CardFromRequest.php create mode 100644 src/PayPal/Order/DTO/CardRequest.php create mode 100644 src/PayPal/Order/DTO/CardResponse.php create mode 100644 src/PayPal/Order/DTO/CardStoredCredentialsRequest.php create mode 100644 src/PayPal/Order/DTO/CardSupplementaryData.php create mode 100644 src/PayPal/Order/DTO/CardSupplementaryDataRequest.php create mode 100644 src/PayPal/Order/DTO/CardVerification.php create mode 100644 src/PayPal/Order/DTO/CobrandedCard.php create mode 100644 src/PayPal/Order/DTO/CreatePayPalOrderRequest.php create mode 100644 src/PayPal/Order/DTO/CreatePayPalOrderResponse.php create mode 100644 src/PayPal/Order/DTO/Customer.php create mode 100644 src/PayPal/Order/DTO/CustomerRequest.php create mode 100644 src/PayPal/Order/DTO/Eps.php create mode 100644 src/PayPal/Order/DTO/EpsRequest.php create mode 100644 src/PayPal/Order/DTO/ExchangeRate.php create mode 100644 src/PayPal/Order/DTO/ExperienceContextRequest.php create mode 100644 src/PayPal/Order/DTO/Giropay.php create mode 100644 src/PayPal/Order/DTO/GiropayRequest.php create mode 100644 src/PayPal/Order/DTO/GooglePayRequest.php create mode 100644 src/PayPal/Order/DTO/Ideal.php create mode 100644 src/PayPal/Order/DTO/IdealRequest.php create mode 100644 src/PayPal/Order/DTO/Item.php create mode 100644 src/PayPal/Order/DTO/ItemRequest.php create mode 100644 src/PayPal/Order/DTO/Level2CardProcessingData.php create mode 100644 src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php create mode 100644 src/PayPal/Order/DTO/Level3CardProcessingData.php create mode 100644 src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php create mode 100644 src/PayPal/Order/DTO/LineItem.php create mode 100644 src/PayPal/Order/DTO/LineItemRequest.php create mode 100644 src/PayPal/Order/DTO/LinkDescription.php create mode 100644 src/PayPal/Order/DTO/MerchantPayableBreakdown.php create mode 100644 src/PayPal/Order/DTO/MyBankRequest.php create mode 100644 src/PayPal/Order/DTO/Mybank.php create mode 100644 src/PayPal/Order/DTO/Name.php create mode 100644 src/PayPal/Order/DTO/NetAmountBreakdownItem.php create mode 100644 src/PayPal/Order/DTO/NetworkTransactionReference.php create mode 100644 src/PayPal/Order/DTO/P24.php create mode 100644 src/PayPal/Order/DTO/P24Request.php create mode 100644 src/PayPal/Order/DTO/PayPalRequest.php create mode 100644 src/PayPal/Order/DTO/PayPalWalletAttributesRequest.php create mode 100644 src/PayPal/Order/DTO/PayPalWalletExperienceContext.php create mode 100644 src/PayPal/Order/DTO/PayPalWalletVaultAttributesRequest.php create mode 100644 src/PayPal/Order/DTO/Payee.php create mode 100644 src/PayPal/Order/DTO/PayeeRequest.php create mode 100644 src/PayPal/Order/DTO/Payer.php create mode 100644 src/PayPal/Order/DTO/PaymentCollection.php create mode 100644 src/PayPal/Order/DTO/PaymentInstruction.php create mode 100644 src/PayPal/Order/DTO/PaymentSourceRequest.php create mode 100644 src/PayPal/Order/DTO/PaymentSourceResponse.php create mode 100644 src/PayPal/Order/DTO/PaypalWalletAttributesResponse.php create mode 100644 src/PayPal/Order/DTO/PaypalWalletResponse.php create mode 100644 src/PayPal/Order/DTO/Phone.php create mode 100644 src/PayPal/Order/DTO/PhoneWithType.php create mode 100644 src/PayPal/Order/DTO/PlatformFee.php create mode 100644 src/PayPal/Order/DTO/PreviousNetworkTransactionReferenceRequest.php create mode 100644 src/PayPal/Order/DTO/ProcessorResponse.php create mode 100644 src/PayPal/Order/DTO/PurchaseUnit.php create mode 100644 src/PayPal/Order/DTO/PurchaseUnitRequest.php create mode 100644 src/PayPal/Order/DTO/Reason.php create mode 100644 src/PayPal/Order/DTO/Refund.php create mode 100644 src/PayPal/Order/DTO/SellerProtection.php create mode 100644 src/PayPal/Order/DTO/SellerReceivableBreakdown.php create mode 100644 src/PayPal/Order/DTO/ShippingOption.php create mode 100644 src/PayPal/Order/DTO/ShippingOptionRequest.php create mode 100644 src/PayPal/Order/DTO/ShippingRequest.php create mode 100644 src/PayPal/Order/DTO/ShippingWithTrackingDetails.php create mode 100644 src/PayPal/Order/DTO/Sofort.php create mode 100644 src/PayPal/Order/DTO/SofortRequest.php create mode 100644 src/PayPal/Order/DTO/StoredPaymentSourceRequest.php create mode 100644 src/PayPal/Order/DTO/SupplementaryData.php create mode 100644 src/PayPal/Order/DTO/SupplementaryDataRequest.php create mode 100644 src/PayPal/Order/DTO/TaxInfo.php create mode 100644 src/PayPal/Order/DTO/ThreeDSecureAuthenticationResponse.php create mode 100644 src/PayPal/Order/DTO/TokenRequest.php create mode 100644 src/PayPal/Order/DTO/Tracker.php create mode 100644 src/PayPal/Order/DTO/TrackerItem.php create mode 100644 src/PayPal/Order/DTO/Trustly.php create mode 100644 src/PayPal/Order/DTO/VaultAttributesRequest.php create mode 100644 src/PayPal/Order/DTO/VaultResponse.php create mode 100644 src/PayPal/Order/DTO/VenmoExperienceContextRequest.php create mode 100644 src/PayPal/Order/DTO/VenmoRequest.php create mode 100644 src/PayPal/Order/DTO/VenmoWalletAttributesResponse.php create mode 100644 src/PayPal/Order/DTO/VenmoWalletResponse.php create mode 100644 src/PayPal/Order/PayPalOrderHttpClientInterface.php create mode 100644 src/PayPal/Order/Query/GetPayPalOrderQuery.php create mode 100644 src/PayPal/Order/Query/GetPayPalOrderQueryResult.php create mode 100644 src/PayPal/Order/QueryHandler/GetPayPalOrderQueryHandler.php create mode 100644 src/PaymentMethodToken/PaymentMethodTokenRepository.php create mode 100644 src/PaymentMethodToken/PaymentMethodTokenService.php create mode 100644 src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQuery.php create mode 100644 src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryHandler.php create mode 100644 src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryResult.php create mode 100644 src/PaymentMethodToken/ValueObject/PaymentMethodTokenId.php create mode 100644 tests/Unit/PayPal/Order/DTO/CreatePayPalOrderRequestTest.php diff --git a/config/common.yml b/config/common.yml index 65cfa2487..83f83fafa 100644 --- a/config/common.yml +++ b/config/common.yml @@ -369,6 +369,7 @@ services: - '@ps_checkout.paypal.order.translations' - '@ps_checkout.context.shop' + ps_checkout.paypal.builder.view_order_summary: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\PayPalOrderSummaryViewBuilder' public: true @@ -469,6 +470,7 @@ services: PrestaShop\Module\PrestashopCheckout\Order\Query\GetOrderForApprovalReversedQuery: "ps_checkout.query.handler.order.get_order_for_approval_reversed" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderForCartIdQuery: "ps_checkout.query.handler.paypal.order.get_paypal_order_for_cart_id" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetCurrentPayPalOrderStatusQuery: "ps_checkout.query.handler.paypal.order.get_current_paypal_order_status" + PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderQuery: "ps_checkout.query.handler.paypal.order.get_paypal_order" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderForCheckoutCompletedQuery: "ps_checkout.query.handler.paypal.order.get_paypal_order_for_checkout_completed" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderForOrderConfirmationQuery: "ps_checkout.query.handler.paypal.order.get_paypal_order_for_order_confirmation" PrestaShop\Module\PrestashopCheckout\Checkout\Command\UpdatePaymentMethodSelectedCommand: "ps_checkout.query.handler.checkout.update_payment_method_selected" @@ -504,6 +506,7 @@ services: - "@ps_checkout.checkout.checker" - "@ps_checkout.paypal.order.service.check_transition_paypal_order_status" - "@ps_checkout.order.state.service.order_state_mapper" + - '@ps_checkout.paypal.configuration' ps_checkout.event.subscriber.paypal.capture: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber' @@ -578,9 +581,9 @@ services: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\CreatePayPalOrderCommandHandler' public: true arguments: - - "@ps_checkout.http.client.checkout" - - "@ps_checkout.event.dispatcher" - - "@ps_checkout.context.shop" + - '@?' + - '@?' + - '@ps_checkout.event.dispatcher' ps_checkout.command.handler.paypal.order.update_paypal_order: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\UpdatePayPalOrderCommandHandler' @@ -597,6 +600,15 @@ services: - "@ps_checkout.http.client.checkout" - "@ps_checkout.event.dispatcher" - "@ps_checkout.cache.paypal.order" + - "@ps_checkout.repository.pscheckoutcart" + - '@ps_checkout.paypal.configuration' + + ps_checkout.query.handler.paypal.order.get_paypal_order: + class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\QueryHandler\GetPayPalOrderQueryHandler' + public: true + arguments: + - '@ps_checkout.cache.paypal.order' + - '@ps_checkout.repository.pscheckoutcart' ps_checkout.query.handler.paypal.order.get_current_paypal_order_status: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\QueryHandler\GetCurrentPayPalOrderStatusQueryHandler' @@ -723,15 +735,12 @@ services: arguments: - '@PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' - ps_checkout.environment.payment: - class: 'PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv' - public: true ps_checkout.http.client.configuration: class: 'PrestaShop\Module\PrestashopCheckout\Http\CheckoutHttpClientConfigurationBuilder' public: true arguments: - - "@ps_checkout.environment.payment" + - '@PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv' - "@ps_checkout.prestashop.router" - "@ps_checkout.context.shop" - "@ps_checkout.repository.prestashop.account" diff --git a/controllers/front/create.php b/controllers/front/create.php index b5fadb430..ded576aef 100755 --- a/controllers/front/create.php +++ b/controllers/front/create.php @@ -20,6 +20,7 @@ */ use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; +use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; use PrestaShop\Module\PrestashopCheckout\Controller\AbstractFrontController; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderForCartIdQuery; @@ -43,6 +44,9 @@ class Ps_CheckoutCreateModuleFrontController extends AbstractFrontController public function postProcess() { try { + /** @var CommandBusInterface $commandBus */ + $commandBus = $this->module->getService('ps_checkout.bus.command'); + // BEGIN Express Checkout $bodyValues = []; $bodyContent = file_get_contents('php://input'); @@ -116,6 +120,11 @@ public function postProcess() 'exceptionCode' => null, 'exceptionMessage' => null, ]); + } catch (CartNotFoundException $exception) { + $this->exitWithResponse([ + 'httpCode' => 400, + 'body' => 'No cart found.', + ]); } catch (Exception $exception) { $this->module->getLogger()->error( 'CreateController - Exception ' . $exception->getCode(), diff --git a/controllers/front/vault.php b/controllers/front/vault.php new file mode 100644 index 000000000..bf1f78faa --- /dev/null +++ b/controllers/front/vault.php @@ -0,0 +1,71 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; +use PrestaShop\Module\PrestashopCheckout\Controller\AbstractFrontController; +use PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\Query\GetCustomerPaymentMethodTokensQuery; +use PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\Query\GetCustomerPaymentMethodTokensQueryResult; +use Psr\Log\LoggerInterface; + +/** + * This controller receive ajax call to manage the Customer PayPal Payment Method tokens + */ +class Ps_CheckoutVaultModuleFrontController extends AbstractFrontController +{ + /** + * @see FrontController::postProcess() + */ + public function postProcess() + { + try { + /** @var CommandBusInterface $commandBus */ + $commandBus = $this->module->getService('ps_checkout.bus.command'); + /** @var GetCustomerPaymentMethodTokensQueryResult $getCustomerPaymentMethodTokensQueryResult */ + $getCustomerPaymentMethodTokensQueryResult = $commandBus->handle(new GetCustomerPaymentMethodTokensQuery( + $this->getCustomerId(), + $this->getPageSize(), + $this->getPageNumber() + )); + + $this->exitWithResponse([ + 'status' => true, + 'httpCode' => 200, + 'body' => [ + 'customerId' => $getCustomerPaymentMethodTokensQueryResult->getCustomerId(), + 'paymentTokens' => $getCustomerPaymentMethodTokensQueryResult->getPaymentTokens(), + 'totalItems' => $getCustomerPaymentMethodTokensQueryResult->getTotalItems(), + 'totalPages' => $getCustomerPaymentMethodTokensQueryResult->getTotalPages(), + ], + ]); + } catch (Exception $exception) { + /** @var LoggerInterface $logger */ + $logger = $this->module->getService('ps_checkout.logger'); + $logger->error( + sprintf( + 'VaultController exception %s : %s', + $exception->getCode(), + $exception->getMessage() + ) + ); + + $this->exitWithExceptionMessage($exception); + } + } +} diff --git a/src/Cart/CartInterface.php b/src/Cart/CartInterface.php new file mode 100644 index 000000000..1c635a8b0 --- /dev/null +++ b/src/Cart/CartInterface.php @@ -0,0 +1,45 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Cart; + +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PurchaseUnitRequest; + +interface CartInterface +{ + /** + * @return int + */ + public function getId(); + + /** + * @return string + */ + public function getCurrencyCode(); + + public function getCustomer(); + + public function getBillingAddress(); + + /** + * @return PurchaseUnitRequest[] + */ + public function getPurchaseUnits(); +} diff --git a/src/Cart/CartRepositoryInterface.php b/src/Cart/CartRepositoryInterface.php new file mode 100644 index 000000000..f38d7e206 --- /dev/null +++ b/src/Cart/CartRepositoryInterface.php @@ -0,0 +1,36 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Cart; + +use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; +use PrestaShop\Module\PrestashopCheckout\Cart\ValueObject\CartId; + +interface CartRepositoryInterface +{ + /** + * @param CartId $cartId + * + * @return CartInterface + * + * @throws CartNotFoundException + */ + public function getCartById(CartId $cartId); +} diff --git a/src/Checkout/CommandHandler/SavePayPalOrderStatusCommandHandler.php b/src/Checkout/CommandHandler/SavePayPalOrderStatusCommandHandler.php index 00483385b..80e1beda5 100644 --- a/src/Checkout/CommandHandler/SavePayPalOrderStatusCommandHandler.php +++ b/src/Checkout/CommandHandler/SavePayPalOrderStatusCommandHandler.php @@ -46,6 +46,7 @@ public function __construct(PsCheckoutCartRepository $psCheckoutCartRepository) */ public function handle(SavePayPalOrderStatusCommand $command) { + // TODO: To be repurposed try { /** @var PsCheckoutCart|false $psCheckoutCart */ $psCheckoutCart = $this->psCheckoutCartRepository->findOneByPayPalOrderId($command->getOrderPayPalId()->getValue()); diff --git a/src/Controller/AbstractFrontController.php b/src/Controller/AbstractFrontController.php index 6de73b31c..f823f56d3 100644 --- a/src/Controller/AbstractFrontController.php +++ b/src/Controller/AbstractFrontController.php @@ -22,11 +22,15 @@ use Exception; use ModuleFrontController; +use PrestaShop\Module\PrestashopCheckout\Customer\Exception\CustomerException; +use PrestaShop\Module\PrestashopCheckout\Customer\ValueObject\CustomerId; +use Ps_checkout; +use Tools; class AbstractFrontController extends ModuleFrontController { /** - * @var \Ps_checkout + * @var Ps_checkout */ public $module; @@ -73,4 +77,30 @@ protected function exitWithResponse(array $response = []) exit; } + + /** + * @return CustomerId|null + * + * @throws CustomerException + */ + protected function getCustomerId() + { + return $this->context->customer->isLogged() ? new CustomerId($this->context->customer->id) : null; + } + + /** + * @return int + */ + protected function getPageSize() + { + return (int) Tools::getValue('pageSize', 10); + } + + /** + * @return int + */ + protected function getPageNumber() + { + return (int) Tools::getValue('pageNumber', 1); + } } diff --git a/src/Database/TableManager.php b/src/Database/TableManager.php index 501385036..319b4a790 100644 --- a/src/Database/TableManager.php +++ b/src/Database/TableManager.php @@ -80,6 +80,20 @@ public function createTable() PRIMARY KEY (`name`, `id_shop`), INDEX (`id_shop`) ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_customer` ( + `id_customer` int unsigned NOT NULL, + `paypal_customer_id` varchar(50) NOT NULL, + PRIMARY KEY (`id_customer`, `paypal_customer_id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_payment_token` ( + `id` varchar(50) NOT NULL, + `paypal_customer_id` varchar(50) NOT NULL, + `payment_source` varchar(50) NOT NULL, + `data` text NOT NULL, + PRIMARY KEY (`id_customer`, `paypal_customer_id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; '); $this->checkTable(); diff --git a/src/Handler/CreatePaypalOrderHandler.php b/src/Handler/CreatePaypalOrderHandler.php index cb34dc75d..fbacb6ba1 100644 --- a/src/Handler/CreatePaypalOrderHandler.php +++ b/src/Handler/CreatePaypalOrderHandler.php @@ -41,12 +41,8 @@ class CreatePaypalOrderHandler */ private $context; - public function __construct(Context $context = null) + public function __construct(Context $context) { - if (null === $context) { - $context = Context::getContext(); - } - $this->context = $context; } diff --git a/src/PayPal/Customer/PayPalCustomerRepository.php b/src/PayPal/Customer/PayPalCustomerRepository.php new file mode 100644 index 000000000..2fad8188b --- /dev/null +++ b/src/PayPal/Customer/PayPalCustomerRepository.php @@ -0,0 +1,88 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Customer; + +use Db; +use DbQuery; +use Exception; +use PrestaShop\Module\PrestashopCheckout\Customer\ValueObject\CustomerId; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\ValueObject\PayPalCustomerId; + +class PayPalCustomerRepository +{ + /** + * @var Db + */ + private $db; + + /** + * @param Db $db + */ + public function __construct(Db $db) + { + $this->db = $db; + } + + /** + * @param CustomerId $customerId + * + * @return PayPalCustomerId|null + * + * @throws Exception + */ + public function findPayPalCustomerIdByCustomerId(CustomerId $customerId) + { + try { + $query = new DbQuery(); + $query->select('`paypal_customer_id`'); + $query->from('pscheckout_customer'); + $query->where('`id_customer` = ' . (int) $customerId->getValue()); + $customerIdPayPal = $this->db->getValue($query); + + return $customerIdPayPal ? new PayPalCustomerId($customerIdPayPal) : null; + } catch (Exception $exception) { + throw new Exception('Failed to find PayPal Customer ID', 0, $exception); + } + } + + /** + * @param CustomerId $customerId + * @param PayPalCustomerId $paypalCustomerId + * + * @return void + * + * @throws Exception + */ + public function save(CustomerId $customerId, PayPalCustomerId $paypalCustomerId) + { + try { + $this->db->insert( + 'pscheckout_customer', + [ + 'id_customer' => (int) $customerId->getValue(), + 'paypal_customer_id' => pSQL($paypalCustomerId->getValue()), + ] + ); + } catch (Exception $exception) { + throw new Exception('Failed to save PayPal Customer ID', 0, $exception); + } + } +} diff --git a/src/PayPal/Customer/ValueObject/PayPalCustomerId.php b/src/PayPal/Customer/ValueObject/PayPalCustomerId.php new file mode 100644 index 000000000..279d22f4f --- /dev/null +++ b/src/PayPal/Customer/ValueObject/PayPalCustomerId.php @@ -0,0 +1,74 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Customer\ValueObject; + +use InvalidArgumentException; + +class PayPalCustomerId +{ + /** + * @var string + */ + private $customerId; + + /** + * @param string $customerId + * + * @throws InvalidArgumentException + */ + public function __construct($customerId) + { + $this->assertIsValid($customerId); + $this->customerId = $customerId; + } + + /** + * @return string + */ + public function getValue() + { + return $this->customerId; + } + + /** + * @param string $customerId + * + * @return void + * + * @throws InvalidArgumentException + */ + private function assertIsValid($customerId) + { + if (!is_string($customerId)) { + throw new InvalidArgumentException('PayPal Customer ID must be a string.'); + } + + $length = strlen($customerId); + + if ($length < 1 || $length > 22) { + throw new InvalidArgumentException('PayPal Customer ID must be between 1 and 22 characters long.'); + } + + if (preg_match('/^[0-9a-zA-Z_-]+$/', $customerId) !== 1) { + throw new InvalidArgumentException('PayPal Customer ID must be alphanumeric.'); + } + } +} diff --git a/src/PayPal/OAuth/OAuthService.php b/src/PayPal/OAuth/OAuthService.php new file mode 100644 index 000000000..cba28d6c3 --- /dev/null +++ b/src/PayPal/OAuth/OAuthService.php @@ -0,0 +1,66 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\OAuth; + +use Exception; +use GuzzleHttp\Psr7\Request; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\ValueObject\PayPalCustomerId; + +class OAuthService +{ + private $httpClient; + + public function __construct($httpClient) + { + $this->httpClient = $httpClient; + } + + /** + * @param PayPalCustomerId|null $customerId + * + * @return string + * + * @throws Exception + */ + public function getUserIdToken(PayPalCustomerId $customerId = null) + { + try { + $body = 'grant_type=client_credentials&response_type=id_token'; + + if ($customerId) { + $body .= '&target_customer_id=' . $customerId->getValue(); + } + + $request = new Request('POST', '', [], $body); + $response = $this->httpClient->sendRequest($request); + + $data = json_decode($response->getBody()->getContents(), true); + + if (empty($data['id_token'])) { + throw new Exception('Failed to get PayPal User ID token from response.'); + } + + return $data['id_token']; + } catch (Exception $exception) { + throw new Exception('Failed to get PayPal User ID token.', 0, $exception); + } + } +} diff --git a/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQuery.php b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQuery.php new file mode 100644 index 000000000..5d94ff131 --- /dev/null +++ b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQuery.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\OAuth\Query; + +use PrestaShop\Module\PrestashopCheckout\Customer\ValueObject\CustomerId; + +class GetPayPalGetUserIdTokenQuery +{ + /** + * @var CustomerId|null + */ + private $customerId; + + /** + * @param CustomerId|null $customerId + */ + public function __construct(CustomerId $customerId = null) + { + $this->customerId = $customerId; + } + + /** + * @return CustomerId|null + */ + public function getCustomerId() + { + return $this->customerId; + } +} diff --git a/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryHandler.php b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryHandler.php new file mode 100644 index 000000000..cd410218e --- /dev/null +++ b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryHandler.php @@ -0,0 +1,62 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\OAuth\Query; + +use Exception; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\PayPalCustomerRepository; +use PrestaShop\Module\PrestashopCheckout\PayPal\OAuth\OAuthService; + +class GetPayPalGetUserIdTokenQueryHandler +{ + /** + * @var OAuthService + */ + private $OAuthService; + + /** + * @var PayPalCustomerRepository + */ + private $customerRepository; + + /** + * @param OAuthService $OAuthService + * @param PayPalCustomerRepository $customerRepository + */ + public function __construct(OAuthService $OAuthService, PayPalCustomerRepository $customerRepository) + { + $this->OAuthService = $OAuthService; + $this->customerRepository = $customerRepository; + } + + /** + * @param GetPayPalGetUserIdTokenQuery $query + * + * @return GetPayPalGetUserIdTokenQueryResult + * + * @throws Exception + */ + public function handle(GetPayPalGetUserIdTokenQuery $query) + { + $customerIdPayPal = $query->getCustomerId() ? $this->customerRepository->findPayPalCustomerIdByCustomerId($query->getCustomerId()) : null; + + return new GetPayPalGetUserIdTokenQueryResult($this->OAuthService->getUserIdToken($customerIdPayPal)); + } +} diff --git a/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryResult.php b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryResult.php new file mode 100644 index 000000000..e3a3f4a9b --- /dev/null +++ b/src/PayPal/OAuth/Query/GetPayPalGetUserIdTokenQueryResult.php @@ -0,0 +1,45 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\OAuth\Query; + +class GetPayPalGetUserIdTokenQueryResult +{ + /** + * @var string + */ + private $userIdToken; + + /** + * @param string $userIdToken + */ + public function __construct($userIdToken) + { + $this->userIdToken = $userIdToken; + } + + /** + * @return string + */ + public function getUserIdToken() + { + return $this->userIdToken; + } +} diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index d3a9f4233..733d8eace 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -20,41 +20,36 @@ namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler; -use PrestaShop\Module\PrestashopCheckout\Builder\Payload\OrderPayloadBuilder; +use PrestaShop\Module\PrestashopCheckout\Cart\CartRepositoryInterface; +use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; use PrestaShop\Module\PrestashopCheckout\Event\EventDispatcherInterface; -use PrestaShop\Module\PrestashopCheckout\Exception\PayPalException; -use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; -use PrestaShop\Module\PrestashopCheckout\Http\CheckoutHttpClient; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand; -use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Event\PayPalOrderCreatedEvent; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\CreatePayPalOrderPayloadBuilderInterface; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Exception\PayPalOrderException; -use PrestaShop\Module\PrestashopCheckout\Presenter\Cart\CartPresenter; -use PrestaShop\Module\PrestashopCheckout\ShopContext; class CreatePayPalOrderCommandHandler { /** - * @var EventDispatcherInterface + * @var CartRepositoryInterface */ - private $eventDispatcher; - + private $cartRepository; /** - * @var CheckoutHttpClient + * @var CreatePayPalOrderPayloadBuilderInterface */ - private $httpClient; + private $createPayPalOrderPayloadBuilder; /** - * @var ShopContext + * @var EventDispatcherInterface */ - private $shopContext; + private $eventDispatcher; public function __construct( - CheckoutHttpClient $httpClient, - EventDispatcherInterface $eventDispatcher, - ShopContext $shopContext + CartRepositoryInterface $cartRepository, + CreatePayPalOrderPayloadBuilderInterface $createPayPalOrderPayloadBuilder, + EventDispatcherInterface $eventDispatcher ) { - $this->httpClient = $httpClient; + $this->cartRepository = $cartRepository; + $this->createPayPalOrderPayloadBuilder = $createPayPalOrderPayloadBuilder; $this->eventDispatcher = $eventDispatcher; - $this->shopContext = $shopContext; } /** @@ -62,34 +57,19 @@ public function __construct( * * @return void * - * @throws PayPalException * @throws PayPalOrderException - * @throws PsCheckoutException + * @throws CartNotFoundException */ public function handle(CreatePayPalOrderCommand $command) { - $cartPresenter = (new CartPresenter())->present(); - $builder = new OrderPayloadBuilder($cartPresenter); - $builder->setIsCard($command->getFundingSource() === 'card'); - $builder->setExpressCheckout($command->isExpressCheckout()); - - if ($this->shopContext->isShop17()) { - // Build full payload in 1.7 - $builder->buildFullPayload(); - } else { - // if on 1.6 always build minimal payload - $builder->buildMinimalPayload(); - } - - $response = $this->httpClient->createOrder($builder->presentPayload()->getArray()); - $order = json_decode($response->getBody(), true); - $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( - $order['id'], - $order, - $command->getCartId()->getValue(), - $command->isHostedFields(), - $command->isExpressCheckout(), - $command->getFundingSource() - )); + $cart = $this->cartRepository->getCartById($command->getCartId()); + $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); +// $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( +// $order->getId(), +// $order->toArray(), +// $command->getCartId(), +// $command->isHostedFields(), +// $command->isExpressCheckout() +// )); } } diff --git a/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php b/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php new file mode 100644 index 000000000..55be44e6c --- /dev/null +++ b/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php @@ -0,0 +1,35 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order; + +use PrestaShop\Module\PrestashopCheckout\Cart\CartInterface; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; + +interface CreatePayPalOrderPayloadBuilderInterface +{ + /** + * @param CartInterface $cart + * @param string $fundingSource + * + * @return CreatePayPalOrderRequest + */ + public function build(CartInterface $cart, $fundingSource); +} diff --git a/src/PayPal/Order/DTO/AddressDetails.php b/src/PayPal/Order/DTO/AddressDetails.php new file mode 100644 index 000000000..784a2b5e1 --- /dev/null +++ b/src/PayPal/Order/DTO/AddressDetails.php @@ -0,0 +1,220 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AddressDetails +{ + /** + * The street number. + * + * @var string|null + */ + protected $street_number; + /** + * The street name. Just `Drury` in `Drury Lane`. + * + * @var string|null + */ + protected $street_name; + /** + * The street type. For example, avenue, boulevard, road, or expressway. + * + * @var string|null + */ + protected $street_type; + /** + * The delivery service. Post office box, bag number, or post office name. + * + * @var string|null + */ + protected $delivery_service; + /** + * A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, <code>Craven House</code>. + * + * @var string|null + */ + protected $building_name; + /** + * The first-order entity below a named building or location that represents the sub-premises. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment. + * + * @var string|null + */ + protected $sub_building; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->street_number = isset($data['street_number']) ? $data['street_number'] : null; + $this->street_name = isset($data['street_name']) ? $data['street_name'] : null; + $this->street_type = isset($data['street_type']) ? $data['street_type'] : null; + $this->delivery_service = isset($data['delivery_service']) ? $data['delivery_service'] : null; + $this->building_name = isset($data['building_name']) ? $data['building_name'] : null; + $this->sub_building = isset($data['sub_building']) ? $data['sub_building'] : null; + } + + /** + * Gets street_number. + * + * @return string|null + */ + public function getStreetNumber() + { + return $this->street_number; + } + + /** + * Sets street_number. + * + * @param string|null $street_number the street number + * + * @return $this + */ + public function setStreetNumber($street_number = null) + { + $this->street_number = $street_number; + + return $this; + } + + /** + * Gets street_name. + * + * @return string|null + */ + public function getStreetName() + { + return $this->street_name; + } + + /** + * Sets street_name. + * + * @param string|null $street_name The street name. Just `Drury` in `Drury Lane`. + * + * @return $this + */ + public function setStreetName($street_name = null) + { + $this->street_name = $street_name; + + return $this; + } + + /** + * Gets street_type. + * + * @return string|null + */ + public function getStreetType() + { + return $this->street_type; + } + + /** + * Sets street_type. + * + * @param string|null $street_type The street type. For example, avenue, boulevard, road, or expressway. + * + * @return $this + */ + public function setStreetType($street_type = null) + { + $this->street_type = $street_type; + + return $this; + } + + /** + * Gets delivery_service. + * + * @return string|null + */ + public function getDeliveryService() + { + return $this->delivery_service; + } + + /** + * Sets delivery_service. + * + * @param string|null $delivery_service The delivery service. Post office box, bag number, or post office name. + * + * @return $this + */ + public function setDeliveryService($delivery_service = null) + { + $this->delivery_service = $delivery_service; + + return $this; + } + + /** + * Gets building_name. + * + * @return string|null + */ + public function getBuildingName() + { + return $this->building_name; + } + + /** + * Sets building_name. + * + * @param string|null $building_name A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, Craven House. + * + * @return $this + */ + public function setBuildingName($building_name = null) + { + $this->building_name = $building_name; + + return $this; + } + + /** + * Gets sub_building. + * + * @return string|null + */ + public function getSubBuilding() + { + return $this->sub_building; + } + + /** + * Sets sub_building. + * + * @param string|null $sub_building The first-order entity below a named building or location that represents the sub-premises. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment. + * + * @return $this + */ + public function setSubBuilding($sub_building = null) + { + $this->sub_building = $sub_building; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/AddressPortable2.php b/src/PayPal/Order/DTO/AddressPortable2.php new file mode 100644 index 000000000..961a329da --- /dev/null +++ b/src/PayPal/Order/DTO/AddressPortable2.php @@ -0,0 +1,342 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AddressPortable2 +{ + /** + * The [2-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string + */ + protected $country_code; + /** + * The first line of the address, such as number and street, for example, `173 Drury Lane`. Needed for data entry, and Compliance and Risk checks. This field needs to pass the full address. + * + * @var string|null + */ + protected $address_line_1; + /** + * The second line of the address, for example, a suite or apartment number. + * + * @var string|null + */ + protected $address_line_2; + /** + * The third line of the address, if needed. Examples include a street complement for Brazil, direction text, such as `next to Walmart`, or a landmark in an Indian address. + * + * @var string|null + */ + protected $address_line_3; + /** + * The neighborhood, ward, or district. This is smaller than `admin_area_level_3` or `sub_locality`. Value is:<ul><li>The postal sorting code that is used in Guernsey and many French territories, such as French Guiana.</li><li>The fine-grained administrative levels in China.</li></ul> + * + * @var string|null + */ + protected $admin_area_4; + /** + * The sub-locality, suburb, neighborhood, or district. This is smaller than `admin_area_level_2`. Value is:<ul><li>Brazil. Suburb, *bairro*, or neighborhood.</li><li>India. Sub-locality or district. Street name information isn't always available, but a sub-locality or district can be a very small area.</li></ul> + * + * @var string|null + */ + protected $admin_area_3; + /** + * A city, town, or village. Smaller than `admin_area_level_1`. + * + * @var string|null + */ + protected $admin_area_2; + /** + * The highest-level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. This data is formatted for postal delivery, for example, `CA` and not `California`. Value, by country, is:<ul><li>UK. A county.</li><li>US. A state.</li><li>Canada. A province.</li><li>Japan. A prefecture.</li><li>Switzerland. A *kanton*.</li></ul> + * + * @var string|null + */ + protected $admin_area_1; + /** + * The postal code, which is the ZIP code or equivalent. Typically required for countries with a postal code or an equivalent. See [postal code](https://en.wikipedia.org/wiki/Postal_code). + * + * @var string|null + */ + protected $postal_code; + /** + * @var AddressDetails|null + */ + protected $address_details; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->address_line_1 = isset($data['address_line_1']) ? $data['address_line_1'] : null; + $this->address_line_2 = isset($data['address_line_2']) ? $data['address_line_2'] : null; + $this->address_line_3 = isset($data['address_line_3']) ? $data['address_line_3'] : null; + $this->admin_area_4 = isset($data['admin_area_4']) ? $data['admin_area_4'] : null; + $this->admin_area_3 = isset($data['admin_area_3']) ? $data['admin_area_3'] : null; + $this->admin_area_2 = isset($data['admin_area_2']) ? $data['admin_area_2'] : null; + $this->admin_area_1 = isset($data['admin_area_1']) ? $data['admin_area_1'] : null; + $this->postal_code = isset($data['postal_code']) ? $data['postal_code'] : null; + $this->address_details = isset($data['address_details']) ? $data['address_details'] : null; + } + + /** + * Gets country_code. + * + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string $country_code The [2-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets address_line_1. + * + * @return string|null + */ + public function getAddressLine1() + { + return $this->address_line_1; + } + + /** + * Sets address_line_1. + * + * @param string|null $address_line_1 The first line of the address, such as number and street, for example, `173 Drury Lane`. Needed for data entry, and Compliance and Risk checks. This field needs to pass the full address. + * + * @return $this + */ + public function setAddressLine1($address_line_1 = null) + { + $this->address_line_1 = $address_line_1; + + return $this; + } + + /** + * Gets address_line_2. + * + * @return string|null + */ + public function getAddressLine2() + { + return $this->address_line_2; + } + + /** + * Sets address_line_2. + * + * @param string|null $address_line_2 the second line of the address, for example, a suite or apartment number + * + * @return $this + */ + public function setAddressLine2($address_line_2 = null) + { + $this->address_line_2 = $address_line_2; + + return $this; + } + + /** + * Gets address_line_3. + * + * @return string|null + */ + public function getAddressLine3() + { + return $this->address_line_3; + } + + /** + * Sets address_line_3. + * + * @param string|null $address_line_3 The third line of the address, if needed. Examples include a street complement for Brazil, direction text, such as `next to Walmart`, or a landmark in an Indian address. + * + * @return $this + */ + public function setAddressLine3($address_line_3 = null) + { + $this->address_line_3 = $address_line_3; + + return $this; + } + + /** + * Gets admin_area_4. + * + * @return string|null + */ + public function getAdminArea4() + { + return $this->admin_area_4; + } + + /** + * Sets admin_area_4. + * + * @param string|null $admin_area_4 The neighborhood, ward, or district. This is smaller than `admin_area_level_3` or `sub_locality`. Value is:
  • The postal sorting code that is used in Guernsey and many French territories, such as French Guiana.
  • The fine-grained administrative levels in China.
+ * + * @return $this + */ + public function setAdminArea4($admin_area_4 = null) + { + $this->admin_area_4 = $admin_area_4; + + return $this; + } + + /** + * Gets admin_area_3. + * + * @return string|null + */ + public function getAdminArea3() + { + return $this->admin_area_3; + } + + /** + * Sets admin_area_3. + * + * @param string|null $admin_area_3 The sub-locality, suburb, neighborhood, or district. This is smaller than `admin_area_level_2`. Value is:
  • Brazil. Suburb, *bairro*, or neighborhood.
  • India. Sub-locality or district. Street name information isn't always available, but a sub-locality or district can be a very small area.
+ * + * @return $this + */ + public function setAdminArea3($admin_area_3 = null) + { + $this->admin_area_3 = $admin_area_3; + + return $this; + } + + /** + * Gets admin_area_2. + * + * @return string|null + */ + public function getAdminArea2() + { + return $this->admin_area_2; + } + + /** + * Sets admin_area_2. + * + * @param string|null $admin_area_2 A city, town, or village. Smaller than `admin_area_level_1`. + * + * @return $this + */ + public function setAdminArea2($admin_area_2 = null) + { + $this->admin_area_2 = $admin_area_2; + + return $this; + } + + /** + * Gets admin_area_1. + * + * @return string|null + */ + public function getAdminArea1() + { + return $this->admin_area_1; + } + + /** + * Sets admin_area_1. + * + * @param string|null $admin_area_1 The highest-level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. This data is formatted for postal delivery, for example, `CA` and not `California`. Value, by country, is:
  • UK. A county.
  • US. A state.
  • Canada. A province.
  • Japan. A prefecture.
  • Switzerland. A *kanton*.
+ * + * @return $this + */ + public function setAdminArea1($admin_area_1 = null) + { + $this->admin_area_1 = $admin_area_1; + + return $this; + } + + /** + * Gets postal_code. + * + * @return string|null + */ + public function getPostalCode() + { + return $this->postal_code; + } + + /** + * Sets postal_code. + * + * @param string|null $postal_code The postal code, which is the ZIP code or equivalent. Typically required for countries with a postal code or an equivalent. See [postal code](https://en.wikipedia.org/wiki/Postal_code). + * + * @return $this + */ + public function setPostalCode($postal_code = null) + { + $this->postal_code = $postal_code; + + return $this; + } + + /** + * Gets address_details. + * + * @return AddressDetails|null + */ + public function getAddressDetails() + { + return $this->address_details; + } + + /** + * Sets address_details. + * + * @param AddressDetails|null $address_details + * + * @return $this + */ + public function setAddressDetails(AddressDetails $address_details = null) + { + $this->address_details = $address_details; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/AddressRequest.php b/src/PayPal/Order/DTO/AddressRequest.php new file mode 100644 index 000000000..17e1c4f04 --- /dev/null +++ b/src/PayPal/Order/DTO/AddressRequest.php @@ -0,0 +1,231 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AddressRequest +{ + /** + * @var string + */ + private $address_line_1; + + /** + * @var string + */ + private $address_line_2; + + /** + * @var string + */ + private $address_line_3; + + /** + * @var string + */ + private $admin_area_1; + + /** + * @var string + */ + private $admin_area_2; + + /** + * @var string + */ + private $admin_area_3; + + /** + * @var string + */ + private $admin_area_4; + + /** + * @var string + */ + private $postal_code; + + /** + * @var string + */ + private $country_code; + + /** + * @return string + */ + public function getAddressLine1() + { + return $this->address_line_1; + } + + /** + * @param string $address_line_1 + * + * @return void + */ + public function setAddressLine1($address_line_1) + { + $this->address_line_1 = $address_line_1; + } + + /** + * @return string + */ + public function getAddressLine2() + { + return $this->address_line_2; + } + + /** + * @param string $address_line_2 + * + * @return void + */ + public function setAddressLine2($address_line_2) + { + $this->address_line_2 = $address_line_2; + } + + /** + * @return string + */ + public function getAddressLine3() + { + return $this->address_line_3; + } + + /** + * @param string $address_line_3 + * + * @return void + */ + public function setAddressLine3($address_line_3) + { + $this->address_line_3 = $address_line_3; + } + + /** + * @return string + */ + public function getAdminArea1() + { + return $this->admin_area_1; + } + + /** + * @param string $admin_area_1 + * + * @return void + */ + public function setAdminArea1($admin_area_1) + { + $this->admin_area_1 = $admin_area_1; + } + + /** + * @return string + */ + public function getAdminArea2() + { + return $this->admin_area_2; + } + + /** + * @param string $admin_area_2 + * + * @return void + */ + public function setAdminArea2($admin_area_2) + { + $this->admin_area_2 = $admin_area_2; + } + + /** + * @return string + */ + public function getAdminArea3() + { + return $this->admin_area_3; + } + + /** + * @param string $admin_area_3 + * + * @return void + */ + public function setAdminArea3($admin_area_3) + { + $this->admin_area_3 = $admin_area_3; + } + + /** + * @return string + */ + public function getAdminArea4() + { + return $this->admin_area_4; + } + + /** + * @param string $admin_area_4 + * + * @return void + */ + public function setAdminArea4($admin_area_4) + { + $this->admin_area_4 = $admin_area_4; + } + + /** + * @return string + */ + public function getPostalCode() + { + return $this->postal_code; + } + + /** + * @param string $postal_code + * + * @return void + */ + public function setPostalCode($postal_code) + { + $this->postal_code = $postal_code; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } +} diff --git a/src/PayPal/Order/DTO/Amount.php b/src/PayPal/Order/DTO/Amount.php new file mode 100644 index 000000000..12d0cd1c0 --- /dev/null +++ b/src/PayPal/Order/DTO/Amount.php @@ -0,0 +1,70 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Amount +{ + /** + * @var string + */ + private $currency_code; + + /** + * @var string + */ + private $value; + + /** + * @return string + */ + public function getCurrencyCode() + { + return $this->currency_code; + } + + /** + * @param string $currency_code + * + * @return void + */ + public function setCurrencyCode($currency_code) + { + $this->currency_code = $currency_code; + } + + /** + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * @param string $value + * + * @return void + */ + public function setValue($value) + { + $this->value = $value; + } +} diff --git a/src/PayPal/Order/DTO/AmountBreakdown.php b/src/PayPal/Order/DTO/AmountBreakdown.php new file mode 100644 index 000000000..0d556843a --- /dev/null +++ b/src/PayPal/Order/DTO/AmountBreakdown.php @@ -0,0 +1,179 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AmountBreakdown +{ + /** + * @var Amount + */ + private $item_total; + /** + * @var Amount + */ + private $shipping; + /** + * @var Amount + */ + private $handling; + /** + * @var Amount + */ + private $tax_total; + /** + * @var Amount + */ + private $insurance; + /** + * @var Amount + */ + private $shipping_discount; + /** + * @var Amount + */ + private $discount; + + /** + * @return Amount + */ + public function getItemTotal() + { + return $this->item_total; + } + + /** + * @param Amount $item_total + * + * @return void + */ + public function setItemTotal(Amount $item_total) + { + $this->item_total = $item_total; + } + + /** + * @return Amount + */ + public function getShipping() + { + return $this->shipping; + } + + /** + * @param Amount $shipping + * + * @return void + */ + public function setShipping(Amount $shipping) + { + $this->shipping = $shipping; + } + + /** + * @return Amount + */ + public function getHandling() + { + return $this->handling; + } + + /** + * @param Amount $handling + * + * @return void + */ + public function setHandling(Amount $handling) + { + $this->handling = $handling; + } + + /** + * @return Amount + */ + public function getTaxTotal() + { + return $this->tax_total; + } + + /** + * @param Amount $tax_total + * + * @return void + */ + public function setTaxTotal(Amount $tax_total) + { + $this->tax_total = $tax_total; + } + + /** + * @return Amount + */ + public function getInsurance() + { + return $this->insurance; + } + + /** + * @param Amount $insurance + * + * @return void + */ + public function setInsurance(Amount $insurance) + { + $this->insurance = $insurance; + } + + /** + * @return Amount + */ + public function getShippingDiscount() + { + return $this->shipping_discount; + } + + /** + * @param Amount $shipping_discount + * + * @return void + */ + public function setShippingDiscount(Amount $shipping_discount) + { + $this->shipping_discount = $shipping_discount; + } + + /** + * @return Amount + */ + public function getDiscount() + { + return $this->discount; + } + + /** + * @param Amount $discount + * + * @return void + */ + public function setDiscount(Amount $discount) + { + $this->discount = $discount; + } +} diff --git a/src/PayPal/Order/DTO/AmountWithBreakdown.php b/src/PayPal/Order/DTO/AmountWithBreakdown.php new file mode 100644 index 000000000..039fcc1e4 --- /dev/null +++ b/src/PayPal/Order/DTO/AmountWithBreakdown.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AmountWithBreakdown extends Amount +{ + /** + * @var AmountBreakdown + */ + private $breakdown; + + /** + * @return AmountBreakdown + */ + public function getBreakdown() + { + return $this->breakdown; + } + + /** + * @param AmountBreakdown $breakdown + * + * @return void + */ + public function setBreakdown(AmountBreakdown $breakdown) + { + $this->breakdown = $breakdown; + } +} diff --git a/src/PayPal/Order/DTO/ApplePayAttributesRequest.php b/src/PayPal/Order/DTO/ApplePayAttributesRequest.php new file mode 100644 index 000000000..c855bff9b --- /dev/null +++ b/src/PayPal/Order/DTO/ApplePayAttributesRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ApplePayAttributesRequest +{ + /** + * @var CustomerRequest + */ + private $customer; + /** + * @var VaultAttributesRequest + */ + private $vault; + + /** + * @return CustomerRequest + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * @param CustomerRequest $customer + * + * @return void + */ + public function setCustomer(CustomerRequest $customer) + { + $this->customer = $customer; + } + + /** + * @return VaultAttributesRequest + */ + public function getVault() + { + return $this->vault; + } + + /** + * @param VaultAttributesRequest $vault + * + * @return void + */ + public function setVault(VaultAttributesRequest $vault) + { + $this->vault = $vault; + } +} diff --git a/src/PayPal/Order/DTO/ApplePayRequest.php b/src/PayPal/Order/DTO/ApplePayRequest.php new file mode 100644 index 000000000..6a10ec4cd --- /dev/null +++ b/src/PayPal/Order/DTO/ApplePayRequest.php @@ -0,0 +1,179 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ApplePayRequest +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $email_address; + /** + * @var Phone + */ + private $phone_number; + /** + * @var CardStoredCredentialsRequest + */ + private $stored_credentials; + /** + * @var string + */ + private $vault_id; + /** + * @var ApplePayAttributesRequest + */ + private $attributes; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return Phone + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * @param Phone $phone_number + * + * @return void + */ + public function setPhoneNumber(Phone $phone_number) + { + $this->phone_number = $phone_number; + } + + /** + * @return CardStoredCredentialsRequest + */ + public function getStoredCredentials() + { + return $this->stored_credentials; + } + + /** + * @param CardStoredCredentialsRequest $stored_credentials + * + * @return void + */ + public function setStoredCredentials(CardStoredCredentialsRequest $stored_credentials) + { + $this->stored_credentials = $stored_credentials; + } + + /** + * @return string + */ + public function getVaultId() + { + return $this->vault_id; + } + + /** + * @param string $vault_id + * + * @return void + */ + public function setVaultId($vault_id) + { + $this->vault_id = $vault_id; + } + + /** + * @return ApplePayAttributesRequest + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * @param ApplePayAttributesRequest $attributes + * + * @return void + */ + public function setAttributes(ApplePayAttributesRequest $attributes) + { + $this->attributes = $attributes; + } +} diff --git a/src/PayPal/Order/DTO/ApplicationContextRequest.php b/src/PayPal/Order/DTO/ApplicationContextRequest.php new file mode 100644 index 000000000..47b152ba9 --- /dev/null +++ b/src/PayPal/Order/DTO/ApplicationContextRequest.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ApplicationContextRequest +{ + /** + * @var StoredPaymentSourceRequest + */ + private $stored_payment_source; + + /** + * @return StoredPaymentSourceRequest + */ + public function getStoredPaymentSource() + { + return $this->stored_payment_source; + } + + /** + * @param StoredPaymentSourceRequest $stored_payment_source + * + * @return void + */ + public function setStoredPaymentSource(StoredPaymentSourceRequest $stored_payment_source) + { + $this->stored_payment_source = $stored_payment_source; + } +} diff --git a/src/PayPal/Order/DTO/AuthenticationResponse.php b/src/PayPal/Order/DTO/AuthenticationResponse.php new file mode 100644 index 000000000..a163c3c73 --- /dev/null +++ b/src/PayPal/Order/DTO/AuthenticationResponse.php @@ -0,0 +1,153 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AuthenticationResponse +{ + /** + * @var string|null + */ + protected $liability_shift; + + /** + * @var ThreeDSecureAuthenticationResponse|null + */ + protected $three_d_secure; + + /** + * @var mixed|null + */ + protected $authentication_flow; + + /** + * @var mixed|null + */ + protected $exemption_details; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->liability_shift = isset($data['liability_shift']) ? $data['liability_shift'] : null; + $this->three_d_secure = isset($data['three_d_secure']) ? $data['three_d_secure'] : null; + $this->authentication_flow = isset($data['authentication_flow']) ? $data['authentication_flow'] : null; + $this->exemption_details = isset($data['exemption_details']) ? $data['exemption_details'] : null; + } + + /** + * Gets liability_shift. + * + * @return string|null + */ + public function getLiabilityShift() + { + return $this->liability_shift; + } + + /** + * Sets liability_shift. + * + * @param string|null $liability_shift + * + * @return $this + */ + public function setLiabilityShift($liability_shift = null) + { + $this->liability_shift = $liability_shift; + + return $this; + } + + /** + * Gets three_d_secure. + * + * @return ThreeDSecureAuthenticationResponse|null + */ + public function getThreeDSecure() + { + return $this->three_d_secure; + } + + /** + * Sets three_d_secure. + * + * @param ThreeDSecureAuthenticationResponse|null $three_d_secure + * + * @return $this + */ + public function setThreeDSecure(ThreeDSecureAuthenticationResponse $three_d_secure = null) + { + $this->three_d_secure = $three_d_secure; + + return $this; + } + + /** + * Gets authentication_flow. + * + * @return mixed|null + */ + public function getAuthenticationFlow() + { + return $this->authentication_flow; + } + + /** + * Sets authentication_flow. + * + * @param mixed|null $authentication_flow + * + * @return $this + */ + public function setAuthenticationFlow($authentication_flow = null) + { + $this->authentication_flow = $authentication_flow; + + return $this; + } + + /** + * Gets exemption_details. + * + * @return mixed|null + */ + public function getExemptionDetails() + { + return $this->exemption_details; + } + + /** + * Sets exemption_details. + * + * @param mixed|null $exemption_details + * + * @return $this + */ + public function setExemptionDetails($exemption_details = null) + { + $this->exemption_details = $exemption_details; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/AuthorizationWithAdditionalData.php b/src/PayPal/Order/DTO/AuthorizationWithAdditionalData.php new file mode 100644 index 000000000..ed76fff58 --- /dev/null +++ b/src/PayPal/Order/DTO/AuthorizationWithAdditionalData.php @@ -0,0 +1,439 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class AuthorizationWithAdditionalData +{ + /** + * The status for the authorized payment. + * + * @var string|null + */ + protected $status; + + /** + * @var Reason|null + */ + protected $status_details; + + /** + * The PayPal-generated ID for the authorized payment. + * + * @var string|null + */ + protected $id; + + /** + * @var Amount|null + */ + protected $amount; + + /** + * The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @var string|null + */ + protected $invoice_id; + + /** + * The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @var string|null + */ + protected $custom_id; + + /** + * @var NetworkTransactionReference|null + */ + protected $network_transaction_reference; + + /** + * @var SellerProtection|null + */ + protected $seller_protection; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $expiration_time; + + /** + * An array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links). + * + * @var LinkDescription[]|null + */ + protected $links; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $create_time; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $update_time; + + /** + * @var ProcessorResponse|null + */ + protected $processor_response; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->status = isset($data['status']) ? $data['status'] : null; + $this->status_details = isset($data['status_details']) ? $data['status_details'] : null; + $this->id = isset($data['id']) ? $data['id'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + $this->invoice_id = isset($data['invoice_id']) ? $data['invoice_id'] : null; + $this->custom_id = isset($data['custom_id']) ? $data['custom_id'] : null; + $this->network_transaction_reference = isset($data['network_transaction_reference']) ? $data['network_transaction_reference'] : null; + $this->seller_protection = isset($data['seller_protection']) ? $data['seller_protection'] : null; + $this->expiration_time = isset($data['expiration_time']) ? $data['expiration_time'] : null; + $this->links = isset($data['links']) ? $data['links'] : null; + $this->create_time = isset($data['create_time']) ? $data['create_time'] : null; + $this->update_time = isset($data['update_time']) ? $data['update_time'] : null; + $this->processor_response = isset($data['processor_response']) ? $data['processor_response'] : null; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status the status for the authorized payment + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets status_details. + * + * @return Reason|null + */ + public function getStatusDetails() + { + return $this->status_details; + } + + /** + * Sets status_details. + * + * @param Reason|null $status_details + * + * @return $this + */ + public function setStatusDetails(Reason $status_details = null) + { + $this->status_details = $status_details; + + return $this; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the PayPal-generated ID for the authorized payment + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets amount. + * + * @return Amount|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount|null $amount + * + * @return $this + */ + public function setAmount(Amount $amount = null) + { + $this->amount = $amount; + + return $this; + } + + /** + * Gets invoice_id. + * + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * Sets invoice_id. + * + * @param string|null $invoice_id The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @return $this + */ + public function setInvoiceId($invoice_id = null) + { + $this->invoice_id = $invoice_id; + + return $this; + } + + /** + * Gets custom_id. + * + * @return string|null + */ + public function getCustomId() + { + return $this->custom_id; + } + + /** + * Sets custom_id. + * + * @param string|null $custom_id The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @return $this + */ + public function setCustomId($custom_id = null) + { + $this->custom_id = $custom_id; + + return $this; + } + + /** + * Gets network_transaction_reference. + * + * @return NetworkTransactionReference|null + */ + public function getNetworkTransactionReference() + { + return $this->network_transaction_reference; + } + + /** + * Sets network_transaction_reference. + * + * @param NetworkTransactionReference|null $network_transaction_reference + * + * @return $this + */ + public function setNetworkTransactionReference(NetworkTransactionReference $network_transaction_reference = null) + { + $this->network_transaction_reference = $network_transaction_reference; + + return $this; + } + + /** + * Gets seller_protection. + * + * @return SellerProtection|null + */ + public function getSellerProtection() + { + return $this->seller_protection; + } + + /** + * Sets seller_protection. + * + * @param SellerProtection|null $seller_protection + * + * @return $this + */ + public function setSellerProtection(SellerProtection $seller_protection = null) + { + $this->seller_protection = $seller_protection; + + return $this; + } + + /** + * Gets expiration_time. + * + * @return string|null + */ + public function getExpirationTime() + { + return $this->expiration_time; + } + + /** + * Sets expiration_time. + * + * @param string|null $expiration_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setExpirationTime($expiration_time = null) + { + $this->expiration_time = $expiration_time; + + return $this; + } + + /** + * Gets links. + * + * @return LinkDescription[]|null + */ + public function getLinks() + { + return $this->links; + } + + /** + * Sets links. + * + * @param LinkDescription[]|null $links an array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links) + * + * @return $this + */ + public function setLinks(array $links = null) + { + $this->links = $links; + + return $this; + } + + /** + * Gets create_time. + * + * @return string|null + */ + public function getCreateTime() + { + return $this->create_time; + } + + /** + * Sets create_time. + * + * @param string|null $create_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setCreateTime($create_time = null) + { + $this->create_time = $create_time; + + return $this; + } + + /** + * Gets update_time. + * + * @return string|null + */ + public function getUpdateTime() + { + return $this->update_time; + } + + /** + * Sets update_time. + * + * @param string|null $update_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setUpdateTime($update_time = null) + { + $this->update_time = $update_time; + + return $this; + } + + /** + * Gets processor_response. + * + * @return ProcessorResponse|null + */ + public function getProcessorResponse() + { + return $this->processor_response; + } + + /** + * Sets processor_response. + * + * @param ProcessorResponse|null $processor_response + * + * @return $this + */ + public function setProcessorResponse(ProcessorResponse $processor_response = null) + { + $this->processor_response = $processor_response; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Bancontact.php b/src/PayPal/Order/DTO/Bancontact.php new file mode 100644 index 000000000..1e68d30d3 --- /dev/null +++ b/src/PayPal/Order/DTO/Bancontact.php @@ -0,0 +1,223 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Bancontact +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * The last characters of the IBAN used to pay. + * + * @var string|null + */ + protected $iban_last_chars; + + /** + * The last digits of the card used to fund the Bancontact payment. + * + * @var string|null + */ + protected $card_last_digits; + + /** + * @var mixed|null + */ + protected $attributes; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + $this->iban_last_chars = isset($data['iban_last_chars']) ? $data['iban_last_chars'] : null; + $this->card_last_digits = isset($data['card_last_digits']) ? $data['card_last_digits'] : null; + $this->attributes = isset($data['attributes']) ? $data['attributes'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } + + /** + * Gets iban_last_chars. + * + * @return string|null + */ + public function getIbanLastChars() + { + return $this->iban_last_chars; + } + + /** + * Sets iban_last_chars. + * + * @param string|null $iban_last_chars the last characters of the IBAN used to pay + * + * @return $this + */ + public function setIbanLastChars($iban_last_chars = null) + { + $this->iban_last_chars = $iban_last_chars; + + return $this; + } + + /** + * Gets card_last_digits. + * + * @return string|null + */ + public function getCardLastDigits() + { + return $this->card_last_digits; + } + + /** + * Sets card_last_digits. + * + * @param string|null $card_last_digits the last digits of the card used to fund the Bancontact payment + * + * @return $this + */ + public function setCardLastDigits($card_last_digits = null) + { + $this->card_last_digits = $card_last_digits; + + return $this; + } + + /** + * Gets attributes. + * + * @return mixed|null + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Sets attributes. + * + * @param mixed|null $attributes + * + * @return $this + */ + public function setAttributes($attributes = null) + { + $this->attributes = $attributes; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/BancontactRequest.php b/src/PayPal/Order/DTO/BancontactRequest.php new file mode 100644 index 000000000..f3aabb580 --- /dev/null +++ b/src/PayPal/Order/DTO/BancontactRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class BancontactRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/BinDetails.php b/src/PayPal/Order/DTO/BinDetails.php new file mode 100644 index 000000000..e4314cebf --- /dev/null +++ b/src/PayPal/Order/DTO/BinDetails.php @@ -0,0 +1,161 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class BinDetails +{ + /** + * The Bank Identification Number (BIN) signifies the number that is being used to identify the granular level details (except the PII information) of the card. + * + * @var string|null + */ + protected $bin; + + /** + * The issuer of the card instrument. + * + * @var string|null + */ + protected $issuing_bank; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $bin_country_code; + + /** + * The type of card product assigned to the BIN by the issuer. These values are defined by the issuer and may change over time. Some examples include: PREPAID_GIFT, CONSUMER, CORPORATE. + * + * @var string[]|null + */ + protected $products; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->bin = isset($data['bin']) ? $data['bin'] : null; + $this->issuing_bank = isset($data['issuing_bank']) ? $data['issuing_bank'] : null; + $this->bin_country_code = isset($data['bin_country_code']) ? $data['bin_country_code'] : null; + $this->products = isset($data['products']) ? $data['products'] : null; + } + + /** + * Gets bin. + * + * @return string|null + */ + public function getBin() + { + return $this->bin; + } + + /** + * Sets bin. + * + * @param string|null $bin the Bank Identification Number (BIN) signifies the number that is being used to identify the granular level details (except the PII information) of the card + * + * @return $this + */ + public function setBin($bin = null) + { + $this->bin = $bin; + + return $this; + } + + /** + * Gets issuing_bank. + * + * @return string|null + */ + public function getIssuingBank() + { + return $this->issuing_bank; + } + + /** + * Sets issuing_bank. + * + * @param string|null $issuing_bank the issuer of the card instrument + * + * @return $this + */ + public function setIssuingBank($issuing_bank = null) + { + $this->issuing_bank = $issuing_bank; + + return $this; + } + + /** + * Gets bin_country_code. + * + * @return string|null + */ + public function getBinCountryCode() + { + return $this->bin_country_code; + } + + /** + * Sets bin_country_code. + * + * @param string|null $bin_country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setBinCountryCode($bin_country_code = null) + { + $this->bin_country_code = $bin_country_code; + + return $this; + } + + /** + * Gets products. + * + * @return string[]|null + */ + public function getProducts() + { + return $this->products; + } + + /** + * Sets products. + * + * @param string[]|null $products The type of card product assigned to the BIN by the issuer. These values are defined by the issuer and may change over time. Some examples include: PREPAID_GIFT, CONSUMER, CORPORATE. + * + * @return $this + */ + public function setProducts(array $products = null) + { + $this->products = $products; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Blik.php b/src/PayPal/Order/DTO/Blik.php new file mode 100644 index 000000000..462ddbd81 --- /dev/null +++ b/src/PayPal/Order/DTO/Blik.php @@ -0,0 +1,159 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Blik +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email; + + /** + * @var BlikOneClickResponse|null + */ + protected $one_click; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->email = isset($data['email']) ? $data['email'] : null; + $this->one_click = isset($data['one_click']) ? $data['one_click'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets email. + * + * @return string|null + */ + public function getEmail() + { + return $this->email; + } + + /** + * Sets email. + * + * @param string|null $email The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmail($email = null) + { + $this->email = $email; + + return $this; + } + + /** + * Gets one_click. + * + * @return BlikOneClickResponse|null + */ + public function getOneClick() + { + return $this->one_click; + } + + /** + * Sets one_click. + * + * @param BlikOneClickResponse|null $one_click + * + * @return $this + */ + public function setOneClick(BlikOneClickResponse $one_click = null) + { + $this->one_click = $one_click; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/BlikOneClickResponse.php b/src/PayPal/Order/DTO/BlikOneClickResponse.php new file mode 100644 index 000000000..b94b96912 --- /dev/null +++ b/src/PayPal/Order/DTO/BlikOneClickResponse.php @@ -0,0 +1,65 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class BlikOneClickResponse +{ + /** + * The merchant generated, unique reference serving as a primary identifier for accounts connected between Blik and a merchant. + * + * @var string|null + */ + protected $consumer_reference; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->consumer_reference = isset($data['consumer_reference']) ? $data['consumer_reference'] : null; + } + + /** + * Gets consumer_reference. + * + * @return string|null + */ + public function getConsumerReference() + { + return $this->consumer_reference; + } + + /** + * Sets consumer_reference. + * + * @param string|null $consumer_reference the merchant generated, unique reference serving as a primary identifier for accounts connected between Blik and a merchant + * + * @return $this + */ + public function setConsumerReference($consumer_reference = null) + { + $this->consumer_reference = $consumer_reference; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/BlikRequest.php b/src/PayPal/Order/DTO/BlikRequest.php new file mode 100644 index 000000000..6af509354 --- /dev/null +++ b/src/PayPal/Order/DTO/BlikRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class BlikRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var string + */ + private $email; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return string + */ + public function getEmail() + { + return $this->email; + } + + /** + * @param string $email + * + * @return void + */ + public function setEmail($email) + { + $this->email = $email; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/Capture.php b/src/PayPal/Order/DTO/Capture.php new file mode 100644 index 000000000..22148a0e4 --- /dev/null +++ b/src/PayPal/Order/DTO/Capture.php @@ -0,0 +1,499 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Capture +{ + /** + * The status of the captured payment. + * + * @var string|null + */ + protected $status; + + /** + * @var Reason|null + */ + protected $status_details; + + /** + * The PayPal-generated ID for the captured payment. + * + * @var string|null + */ + protected $id; + + /** + * @var Amount|null + */ + protected $amount; + + /** + * The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @var string|null + */ + protected $invoice_id; + + /** + * The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @var string|null + */ + protected $custom_id; + + /** + * @var NetworkTransactionReference|null + */ + protected $network_transaction_reference; + + /** + * @var SellerProtection|null + */ + protected $seller_protection; + + /** + * Indicates whether you can make additional captures against the authorized payment. Set to `true` if you do not intend to capture additional payments against the authorization. Set to `false` if you intend to capture additional payments against the authorization. + * + * @var bool|null + */ + protected $final_capture; + + /** + * @var SellerReceivableBreakdown|null + */ + protected $seller_receivable_breakdown; + + /** + * @var string|null + */ + protected $disbursement_mode; + + /** + * An array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links). + * + * @var LinkDescription[]|null + */ + protected $links; + + /** + * @var ProcessorResponse|null + */ + protected $processor_response; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $create_time; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $update_time; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->status = isset($data['status']) ? $data['status'] : null; + $this->status_details = isset($data['status_details']) ? $data['status_details'] : null; + $this->id = isset($data['id']) ? $data['id'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + $this->invoice_id = isset($data['invoice_id']) ? $data['invoice_id'] : null; + $this->custom_id = isset($data['custom_id']) ? $data['custom_id'] : null; + $this->network_transaction_reference = isset($data['network_transaction_reference']) ? $data['network_transaction_reference'] : null; + $this->seller_protection = isset($data['seller_protection']) ? $data['seller_protection'] : null; + $this->final_capture = isset($data['final_capture']) ? $data['final_capture'] : false; + $this->seller_receivable_breakdown = isset($data['seller_receivable_breakdown']) ? $data['seller_receivable_breakdown'] : null; + $this->disbursement_mode = isset($data['disbursement_mode']) ? $data['disbursement_mode'] : null; + $this->links = isset($data['links']) ? $data['links'] : null; + $this->processor_response = isset($data['processor_response']) ? $data['processor_response'] : null; + $this->create_time = isset($data['create_time']) ? $data['create_time'] : null; + $this->update_time = isset($data['update_time']) ? $data['update_time'] : null; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status the status of the captured payment + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets status_details. + * + * @return Reason|null + */ + public function getStatusDetails() + { + return $this->status_details; + } + + /** + * Sets status_details. + * + * @param Reason|null $status_details + * + * @return $this + */ + public function setStatusDetails(Reason $status_details = null) + { + $this->status_details = $status_details; + + return $this; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the PayPal-generated ID for the captured payment + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets amount. + * + * @return Amount|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount|null $amount + * + * @return $this + */ + public function setAmount(Amount $amount = null) + { + $this->amount = $amount; + + return $this; + } + + /** + * Gets invoice_id. + * + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * Sets invoice_id. + * + * @param string|null $invoice_id The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @return $this + */ + public function setInvoiceId($invoice_id = null) + { + $this->invoice_id = $invoice_id; + + return $this; + } + + /** + * Gets custom_id. + * + * @return string|null + */ + public function getCustomId() + { + return $this->custom_id; + } + + /** + * Sets custom_id. + * + * @param string|null $custom_id The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @return $this + */ + public function setCustomId($custom_id = null) + { + $this->custom_id = $custom_id; + + return $this; + } + + /** + * Gets network_transaction_reference. + * + * @return NetworkTransactionReference|null + */ + public function getNetworkTransactionReference() + { + return $this->network_transaction_reference; + } + + /** + * Sets network_transaction_reference. + * + * @param NetworkTransactionReference|null $network_transaction_reference + * + * @return $this + */ + public function setNetworkTransactionReference(NetworkTransactionReference $network_transaction_reference = null) + { + $this->network_transaction_reference = $network_transaction_reference; + + return $this; + } + + /** + * Gets seller_protection. + * + * @return SellerProtection|null + */ + public function getSellerProtection() + { + return $this->seller_protection; + } + + /** + * Sets seller_protection. + * + * @param SellerProtection|null $seller_protection + * + * @return $this + */ + public function setSellerProtection(SellerProtection $seller_protection = null) + { + $this->seller_protection = $seller_protection; + + return $this; + } + + /** + * Gets final_capture. + * + * @return bool|null + */ + public function isFinalCapture() + { + return $this->final_capture; + } + + /** + * Sets final_capture. + * + * @param bool|null $final_capture Indicates whether you can make additional captures against the authorized payment. Set to `true` if you do not intend to capture additional payments against the authorization. Set to `false` if you intend to capture additional payments against the authorization. + * + * @return $this + */ + public function setFinalCapture($final_capture = null) + { + $this->final_capture = $final_capture; + + return $this; + } + + /** + * Gets seller_receivable_breakdown. + * + * @return SellerReceivableBreakdown|null + */ + public function getSellerReceivableBreakdown() + { + return $this->seller_receivable_breakdown; + } + + /** + * Sets seller_receivable_breakdown. + * + * @param SellerReceivableBreakdown|null $seller_receivable_breakdown + * + * @return $this + */ + public function setSellerReceivableBreakdown(SellerReceivableBreakdown $seller_receivable_breakdown = null) + { + $this->seller_receivable_breakdown = $seller_receivable_breakdown; + + return $this; + } + + /** + * Gets disbursement_mode. + * + * @return string|null + */ + public function getDisbursementMode() + { + return $this->disbursement_mode; + } + + /** + * Sets disbursement_mode. + * + * @param string|null $disbursement_mode + * + * @return $this + */ + public function setDisbursementMode($disbursement_mode = null) + { + $this->disbursement_mode = $disbursement_mode; + + return $this; + } + + /** + * Gets links. + * + * @return LinkDescription[]|null + */ + public function getLinks() + { + return $this->links; + } + + /** + * Sets links. + * + * @param LinkDescription[]|null $links an array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links) + * + * @return $this + */ + public function setLinks(array $links = null) + { + $this->links = $links; + + return $this; + } + + /** + * Gets processor_response. + * + * @return ProcessorResponse|null + */ + public function getProcessorResponse() + { + return $this->processor_response; + } + + /** + * Sets processor_response. + * + * @param ProcessorResponse|null $processor_response + * + * @return $this + */ + public function setProcessorResponse(ProcessorResponse $processor_response = null) + { + $this->processor_response = $processor_response; + + return $this; + } + + /** + * Gets create_time. + * + * @return string|null + */ + public function getCreateTime() + { + return $this->create_time; + } + + /** + * Sets create_time. + * + * @param string|null $create_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setCreateTime($create_time = null) + { + $this->create_time = $create_time; + + return $this; + } + + /** + * Gets update_time. + * + * @return string|null + */ + public function getUpdateTime() + { + return $this->update_time; + } + + /** + * Sets update_time. + * + * @param string|null $update_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setUpdateTime($update_time = null) + { + $this->update_time = $update_time; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CardAttributesRequest.php b/src/PayPal/Order/DTO/CardAttributesRequest.php new file mode 100644 index 000000000..bb941cf6d --- /dev/null +++ b/src/PayPal/Order/DTO/CardAttributesRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardAttributesRequest +{ + /** + * @var CustomerRequest + */ + private $customer; + /** + * @var VaultAttributesRequest + */ + private $vault; + /** + * @var CardVerification + */ + private $verification; + + /** + * @return CustomerRequest + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * @param CustomerRequest $customer + * + * @return void + */ + public function setCustomer(CustomerRequest $customer) + { + $this->customer = $customer; + } + + /** + * @return VaultAttributesRequest + */ + public function getVault() + { + return $this->vault; + } + + /** + * @param VaultAttributesRequest $vault + * + * @return void + */ + public function setVault(VaultAttributesRequest $vault) + { + $this->vault = $vault; + } + + /** + * @return CardVerification + */ + public function getVerification() + { + return $this->verification; + } + + /** + * @param CardVerification $verification + * + * @return void + */ + public function setVerification(CardVerification $verification) + { + $this->verification = $verification; + } +} diff --git a/src/PayPal/Order/DTO/CardAttributesResponse.php b/src/PayPal/Order/DTO/CardAttributesResponse.php new file mode 100644 index 000000000..656a105df --- /dev/null +++ b/src/PayPal/Order/DTO/CardAttributesResponse.php @@ -0,0 +1,63 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardAttributesResponse +{ + /** + * @var VaultResponse|null + */ + protected $vault; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->vault = isset($data['vault']) ? $data['vault'] : null; + } + + /** + * Gets vault. + * + * @return VaultResponse|null + */ + public function getVault() + { + return $this->vault; + } + + /** + * Sets vault. + * + * @param VaultResponse|null $vault + * + * @return $this + */ + public function setVault(VaultResponse $vault = null) + { + $this->vault = $vault; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CardExperienceContextRequest.php b/src/PayPal/Order/DTO/CardExperienceContextRequest.php new file mode 100644 index 000000000..beb85d4c5 --- /dev/null +++ b/src/PayPal/Order/DTO/CardExperienceContextRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardExperienceContextRequest +{ + /** + * @var string + */ + private $return_url; + /** + * @var string + */ + private $cancel_url; + + /** + * @return string + */ + public function getReturnUrl() + { + return $this->return_url; + } + + /** + * @param string $return_url + * + * @return void + */ + public function setReturnUrl($return_url) + { + $this->return_url = $return_url; + } + + /** + * @return string + */ + public function getCancelUrl() + { + return $this->cancel_url; + } + + /** + * @param string $cancel_url + * + * @return void + */ + public function setCancelUrl($cancel_url) + { + $this->cancel_url = $cancel_url; + } +} diff --git a/src/PayPal/Order/DTO/CardFromRequest.php b/src/PayPal/Order/DTO/CardFromRequest.php new file mode 100644 index 000000000..0d68f43a9 --- /dev/null +++ b/src/PayPal/Order/DTO/CardFromRequest.php @@ -0,0 +1,97 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardFromRequest +{ + /** + * The year and month, in ISO-8601 `YYYY-MM` date format. See [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). + * + * @var string|null + */ + protected $expiry; + + /** + * The last digits of the payment card. + * + * @var string|null + */ + protected $last_digits; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->expiry = isset($data['expiry']) ? $data['expiry'] : null; + $this->last_digits = isset($data['last_digits']) ? $data['last_digits'] : null; + } + + /** + * Gets expiry. + * + * @return string|null + */ + public function getExpiry() + { + return $this->expiry; + } + + /** + * Sets expiry. + * + * @param string|null $expiry The year and month, in ISO-8601 `YYYY-MM` date format. See [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). + * + * @return $this + */ + public function setExpiry($expiry = null) + { + $this->expiry = $expiry; + + return $this; + } + + /** + * Gets last_digits. + * + * @return string|null + */ + public function getLastDigits() + { + return $this->last_digits; + } + + /** + * Sets last_digits. + * + * @param string|null $last_digits the last digits of the payment card + * + * @return $this + */ + public function setLastDigits($last_digits = null) + { + $this->last_digits = $last_digits; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CardRequest.php b/src/PayPal/Order/DTO/CardRequest.php new file mode 100644 index 000000000..be0a2d6bd --- /dev/null +++ b/src/PayPal/Order/DTO/CardRequest.php @@ -0,0 +1,157 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardRequest +{ + /** + * @var string + */ + private $name; + /** + * @var AddressRequest + */ + private $billing_address; + /** + * @var CardAttributesRequest + */ + private $attributes; + /** + * @var string + */ + private $vault_id; + /** + * @var CardStoredCredentialsRequest + */ + private $stored_credentials; + /** + * @var CardExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return AddressRequest + */ + public function getBillingAddress() + { + return $this->billing_address; + } + + /** + * @param AddressRequest $billing_address + * + * @return void + */ + public function setBillingAddress(AddressRequest $billing_address) + { + $this->billing_address = $billing_address; + } + + /** + * @return CardAttributesRequest + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * @param CardAttributesRequest $attributes + * + * @return void + */ + public function setAttributes(CardAttributesRequest $attributes) + { + $this->attributes = $attributes; + } + + /** + * @return string + */ + public function getVaultId() + { + return $this->vault_id; + } + + /** + * @param string $vault_id + * + * @return void + */ + public function setVaultId($vault_id) + { + $this->vault_id = $vault_id; + } + + /** + * @return CardStoredCredentialsRequest + */ + public function getStoredCredentials() + { + return $this->stored_credentials; + } + + /** + * @param CardStoredCredentialsRequest $stored_credentials + * + * @return void + */ + public function setStoredCredentials(CardStoredCredentialsRequest $stored_credentials) + { + $this->stored_credentials = $stored_credentials; + } + + /** + * @return CardExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param CardExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(CardExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/CardResponse.php b/src/PayPal/Order/DTO/CardResponse.php new file mode 100644 index 000000000..9249a235e --- /dev/null +++ b/src/PayPal/Order/DTO/CardResponse.php @@ -0,0 +1,343 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardResponse +{ + /** + * The card holder's name as it appears on the card. + * + * @var string|null + */ + protected $name; + + /** + * The last digits of the payment card. + * + * @var string|null + */ + protected $last_digits; + + /** + * @var string|null + */ + protected $brand; + + /** + * Array of brands or networks associated with the card. + * + * @var string[]|null + */ + protected $available_networks; + + /** + * The payment card type. + * + * @var string|null + */ + protected $type; + + /** + * @var AuthenticationResponse|null + */ + protected $authentication_result; + + /** + * @var CardAttributesResponse|null + */ + protected $attributes; + + /** + * @var CardFromRequest|null + */ + protected $from_request; + + /** + * The year and month, in ISO-8601 `YYYY-MM` date format. See [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). + * + * @var string|null + */ + protected $expiry; + + /** + * @var BinDetails|null + */ + protected $bin_details; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->last_digits = isset($data['last_digits']) ? $data['last_digits'] : null; + $this->brand = isset($data['brand']) ? $data['brand'] : null; + $this->available_networks = isset($data['available_networks']) ? $data['available_networks'] : null; + $this->type = isset($data['type']) ? $data['type'] : null; + $this->authentication_result = isset($data['authentication_result']) ? $data['authentication_result'] : null; + $this->attributes = isset($data['attributes']) ? $data['attributes'] : null; + $this->from_request = isset($data['from_request']) ? $data['from_request'] : null; + $this->expiry = isset($data['expiry']) ? $data['expiry'] : null; + $this->bin_details = isset($data['bin_details']) ? $data['bin_details'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the card holder's name as it appears on the card + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets last_digits. + * + * @return string|null + */ + public function getLastDigits() + { + return $this->last_digits; + } + + /** + * Sets last_digits. + * + * @param string|null $last_digits the last digits of the payment card + * + * @return $this + */ + public function setLastDigits($last_digits = null) + { + $this->last_digits = $last_digits; + + return $this; + } + + /** + * Gets brand. + * + * @return string|null + */ + public function getBrand() + { + return $this->brand; + } + + /** + * Sets brand. + * + * @param string|null $brand + * + * @return $this + */ + public function setBrand($brand = null) + { + $this->brand = $brand; + + return $this; + } + + /** + * Gets available_networks. + * + * @return string[]|null + */ + public function getAvailableNetworks() + { + return $this->available_networks; + } + + /** + * Sets available_networks. + * + * @param string[]|null $available_networks array of brands or networks associated with the card + * + * @return $this + */ + public function setAvailableNetworks(array $available_networks = null) + { + $this->available_networks = $available_networks; + + return $this; + } + + /** + * Gets type. + * + * @return string|null + */ + public function getType() + { + return $this->type; + } + + /** + * Sets type. + * + * @param string|null $type the payment card type + * + * @return $this + */ + public function setType($type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Gets authentication_result. + * + * @return AuthenticationResponse|null + */ + public function getAuthenticationResult() + { + return $this->authentication_result; + } + + /** + * Sets authentication_result. + * + * @param AuthenticationResponse|null $authentication_result + * + * @return $this + */ + public function setAuthenticationResult(AuthenticationResponse $authentication_result = null) + { + $this->authentication_result = $authentication_result; + + return $this; + } + + /** + * Gets attributes. + * + * @return CardAttributesResponse|null + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Sets attributes. + * + * @param CardAttributesResponse|null $attributes + * + * @return $this + */ + public function setAttributes(CardAttributesResponse $attributes = null) + { + $this->attributes = $attributes; + + return $this; + } + + /** + * Gets from_request. + * + * @return CardFromRequest|null + */ + public function getFromRequest() + { + return $this->from_request; + } + + /** + * Sets from_request. + * + * @param CardFromRequest|null $from_request + * + * @return $this + */ + public function setFromRequest(CardFromRequest $from_request = null) + { + $this->from_request = $from_request; + + return $this; + } + + /** + * Gets expiry. + * + * @return string|null + */ + public function getExpiry() + { + return $this->expiry; + } + + /** + * Sets expiry. + * + * @param string|null $expiry The year and month, in ISO-8601 `YYYY-MM` date format. See [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). + * + * @return $this + */ + public function setExpiry($expiry = null) + { + $this->expiry = $expiry; + + return $this; + } + + /** + * Gets bin_details. + * + * @return BinDetails|null + */ + public function getBinDetails() + { + return $this->bin_details; + } + + /** + * Sets bin_details. + * + * @param BinDetails|null $bin_details + * + * @return $this + */ + public function setBinDetails(BinDetails $bin_details = null) + { + $this->bin_details = $bin_details; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CardStoredCredentialsRequest.php b/src/PayPal/Order/DTO/CardStoredCredentialsRequest.php new file mode 100644 index 000000000..03a54c15b --- /dev/null +++ b/src/PayPal/Order/DTO/CardStoredCredentialsRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardStoredCredentialsRequest +{ + /** + * @var string + */ + private $payment_initiator; + /** + * @var string + */ + private $payment_type; + /** + * @var string + */ + private $usage; + /** + * @var NetworkTransactionReference + */ + private $previous_network_transaction_reference; + + /** + * @return string + */ + public function getPaymentInitiator() + { + return $this->payment_initiator; + } + + /** + * @param string $payment_initiator + * + * @return void + */ + public function setPaymentInitiator($payment_initiator) + { + $this->payment_initiator = $payment_initiator; + } + + /** + * @return string + */ + public function getPaymentType() + { + return $this->payment_type; + } + + /** + * @param string $payment_type + * + * @return void + */ + public function setPaymentType($payment_type) + { + $this->payment_type = $payment_type; + } + + /** + * @return string + */ + public function getUsage() + { + return $this->usage; + } + + /** + * @param string $usage + * + * @return void + */ + public function setUsage($usage) + { + $this->usage = $usage; + } + + /** + * @return NetworkTransactionReference + */ + public function getPreviousNetworkTransactionReference() + { + return $this->previous_network_transaction_reference; + } + + /** + * @param NetworkTransactionReference $previous_network_transaction_reference + * + * @return void + */ + public function setPreviousNetworkTransactionReference(NetworkTransactionReference $previous_network_transaction_reference) + { + $this->previous_network_transaction_reference = $previous_network_transaction_reference; + } +} diff --git a/src/PayPal/Order/DTO/CardSupplementaryData.php b/src/PayPal/Order/DTO/CardSupplementaryData.php new file mode 100644 index 000000000..0842d313f --- /dev/null +++ b/src/PayPal/Order/DTO/CardSupplementaryData.php @@ -0,0 +1,92 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardSupplementaryData +{ + /** + * @var Level2CardProcessingData|null + */ + protected $level_2; + /** + * @var Level3CardProcessingData|null + */ + protected $level_3; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->level_2 = isset($data['level_2']) ? $data['level_2'] : null; + $this->level_3 = isset($data['level_3']) ? $data['level_3'] : null; + } + + /** + * Gets level_2. + * + * @return Level2CardProcessingData|null + */ + public function getLevel2() + { + return $this->level_2; + } + + /** + * Sets level_2. + * + * @param Level2CardProcessingData|null $level_2 + * + * @return $this + */ + public function setLevel2(Level2CardProcessingData $level_2 = null) + { + $this->level_2 = $level_2; + + return $this; + } + + /** + * Gets level_3. + * + * @return Level3CardProcessingData|null + */ + public function getLevel3() + { + return $this->level_3; + } + + /** + * Sets level_3. + * + * @param Level3CardProcessingData|null $level_3 + * + * @return $this + */ + public function setLevel3(Level3CardProcessingData $level_3 = null) + { + $this->level_3 = $level_3; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php b/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php new file mode 100644 index 000000000..04b76b9a5 --- /dev/null +++ b/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardSupplementaryDataRequest +{ + /** + * @var Level2CardProcessingDataRequest + */ + private $level_2; + /** + * @var Level3CardProcessingDataRequest + */ + private $level_3; + + /** + * @return Level2CardProcessingDataRequest + */ + public function getLevel2() + { + return $this->level_2; + } + + /** + * @param Level2CardProcessingDataRequest $level_2 + * + * @return void + */ + public function setLevel2(Level2CardProcessingDataRequest $level_2) + { + $this->level_2 = $level_2; + } + + /** + * @return Level3CardProcessingDataRequest + */ + public function getLevel3() + { + return $this->level_3; + } + + /** + * @param Level3CardProcessingDataRequest $level_3 + * + * @return void + */ + public function setLevel3(Level3CardProcessingDataRequest $level_3) + { + $this->level_3 = $level_3; + } +} diff --git a/src/PayPal/Order/DTO/CardVerification.php b/src/PayPal/Order/DTO/CardVerification.php new file mode 100644 index 000000000..8891eddac --- /dev/null +++ b/src/PayPal/Order/DTO/CardVerification.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CardVerification +{ + /** + * @var string + */ + private $method; + + /** + * @return string + */ + public function getMethod() + { + return $this->method; + } + + /** + * @param string $method + * + * @return void + */ + public function setMethod($method) + { + $this->method = $method; + } +} diff --git a/src/PayPal/Order/DTO/CobrandedCard.php b/src/PayPal/Order/DTO/CobrandedCard.php new file mode 100644 index 000000000..8ad1728ff --- /dev/null +++ b/src/PayPal/Order/DTO/CobrandedCard.php @@ -0,0 +1,123 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CobrandedCard +{ + /** + * Array of labels for the cobranded card. + * + * @var string[]|null + */ + protected $labels; + /** + * @var Payee|null + */ + protected $payee; + /** + * @var Amount|null + */ + protected $amount; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->labels = isset($data['labels']) ? $data['labels'] : null; + $this->payee = isset($data['payee']) ? $data['payee'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + } + + /** + * Gets labels. + * + * @return string[]|null + */ + public function getLabels() + { + return $this->labels; + } + + /** + * Sets labels. + * + * @param string[]|null $labels array of labels for the cobranded card + * + * @return $this + */ + public function setLabels(array $labels = null) + { + $this->labels = $labels; + + return $this; + } + + /** + * Gets payee. + * + * @return Payee|null + */ + public function getPayee() + { + return $this->payee; + } + + /** + * Sets payee. + * + * @param Payee|null $payee + * + * @return $this + */ + public function setPayee(Payee $payee = null) + { + $this->payee = $payee; + + return $this; + } + + /** + * Gets amount. + * + * @return Amount|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount|null $amount + * + * @return $this + */ + public function setAmount(Amount $amount = null) + { + $this->amount = $amount; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php new file mode 100644 index 000000000..491a1e1a7 --- /dev/null +++ b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php @@ -0,0 +1,135 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CreatePayPalOrderRequest +{ + /** + * @var string + */ + private $intent; + /** + * @var PurchaseUnitRequest[] + */ + private $purchase_units; + /** + * @var PaymentSourceRequest + */ + private $payment_source; + /** + * @var ApplicationContextRequest + */ + private $application_context; + /** + * @var string + */ + private $processing_instruction; + + /** + * @return string + */ + public function getIntent() + { + return $this->intent; + } + + /** + * @param string $intent + * + * @return void + */ + public function setIntent($intent) + { + $this->intent = $intent; + } + + /** + * @return PurchaseUnitRequest[] + */ + public function getPurchaseUnits() + { + return $this->purchase_units; + } + + /** + * @param PurchaseUnitRequest[] $purchase_units + * + * @return void + */ + public function setPurchaseUnits(array $purchase_units) + { + $this->purchase_units = $purchase_units; + } + + /** + * @return PaymentSourceRequest + */ + public function getPaymentSource() + { + return $this->payment_source; + } + + /** + * @param PaymentSourceRequest $payment_source + * + * @return void + */ + public function setPaymentSource(PaymentSourceRequest $payment_source) + { + $this->payment_source = $payment_source; + } + + /** + * @return ApplicationContextRequest + */ + public function getApplicationContext() + { + return $this->application_context; + } + + /** + * @param ApplicationContextRequest $application_context + * + * @return void + */ + public function setApplicationContext(ApplicationContextRequest $application_context) + { + $this->application_context = $application_context; + } + + /** + * @return string + */ + public function getProcessingInstruction() + { + return $this->processing_instruction; + } + + /** + * @param string $processing_instruction + * + * @return void + */ + public function setProcessingInstruction($processing_instruction) + { + $this->processing_instruction = $processing_instruction; + } +} diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php b/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php new file mode 100644 index 000000000..575375841 --- /dev/null +++ b/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php @@ -0,0 +1,226 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CreatePayPalOrderResponse +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $create_time; + /** + * @var string + */ + private $update_time; + /** + * @var PaymentSourceResponse + */ + private $payment_source; + /** + * @var string + */ + private $intent; + /** + * @var string + */ + private $processing_instruction; + /** + * @var Payer + */ + private $payer; + /** + * @var PurchaseUnit[] + */ + private $purchase_units; + /** + * @var string + */ + private $status; + /** + * @var LinkDescription[] + */ + private $links; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getCreateTime() + { + return $this->create_time; + } + + /** + * @param string $create_time + */ + public function setCreateTime($create_time) + { + $this->create_time = $create_time; + } + + /** + * @return string + */ + public function getUpdateTime() + { + return $this->update_time; + } + + /** + * @param string $update_time + */ + public function setUpdateTime($update_time) + { + $this->update_time = $update_time; + } + + /** + * @return PaymentSourceResponse|null + */ + public function getPaymentSource() + { + return $this->payment_source; + } + + /** + * @param PaymentSourceResponse $payment_source + */ + public function setPaymentSource($payment_source) + { + $this->payment_source = $payment_source; + } + + /** + * @return string + */ + public function getIntent() + { + return $this->intent; + } + + /** + * @param string $intent + */ + public function setIntent($intent) + { + $this->intent = $intent; + } + + /** + * @return string + */ + public function getProcessingInstruction() + { + return $this->processing_instruction; + } + + /** + * @param string $processing_instruction + */ + public function setProcessingInstruction($processing_instruction) + { + $this->processing_instruction = $processing_instruction; + } + + /** + * @return Payer + */ + public function getPayer() + { + return $this->payer; + } + + /** + * @param Payer $payer + */ + public function setPayer($payer) + { + $this->payer = $payer; + } + + /** + * @return PurchaseUnit[] + */ + public function getPurchaseUnits() + { + return $this->purchase_units; + } + + /** + * @param PurchaseUnit[] $purchase_units + */ + public function setPurchaseUnits($purchase_units) + { + $this->purchase_units = $purchase_units; + } + + /** + * @return string + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param string $status + */ + public function setStatus($status) + { + $this->status = $status; + } + + /** + * @return LinkDescription[] + */ + public function getLinks() + { + return $this->links; + } + + /** + * @param LinkDescription[] $links + */ + public function setLinks($links) + { + $this->links = $links; + } +} diff --git a/src/PayPal/Order/DTO/Customer.php b/src/PayPal/Order/DTO/Customer.php new file mode 100644 index 000000000..827c98be1 --- /dev/null +++ b/src/PayPal/Order/DTO/Customer.php @@ -0,0 +1,127 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Customer +{ + /** + * The unique ID for a customer generated by PayPal. + * + * @var string|null + */ + protected $id; + + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email_address; + + /** + * @var PhoneWithType|null + */ + protected $phone; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->email_address = isset($data['email_address']) ? $data['email_address'] : null; + $this->phone = isset($data['phone']) ? $data['phone'] : null; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the unique ID for a customer generated by PayPal + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets email_address. + * + * @return string|null + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * Sets email_address. + * + * @param string|null $email_address The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmailAddress($email_address = null) + { + $this->email_address = $email_address; + + return $this; + } + + /** + * Gets phone. + * + * @return PhoneWithType|null + */ + public function getPhone() + { + return $this->phone; + } + + /** + * Sets phone. + * + * @param PhoneWithType|null $phone + * + * @return $this + */ + public function setPhone(PhoneWithType $phone = null) + { + $this->phone = $phone; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/CustomerRequest.php b/src/PayPal/Order/DTO/CustomerRequest.php new file mode 100644 index 000000000..b764990ad --- /dev/null +++ b/src/PayPal/Order/DTO/CustomerRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class CustomerRequest +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $email_address; + /** + * @var PhoneWithType + */ + private $phone; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return PhoneWithType + */ + public function getPhone() + { + return $this->phone; + } + + /** + * @param PhoneWithType $phone + * + * @return void + */ + public function setPhone(PhoneWithType $phone) + { + $this->phone = $phone; + } +} diff --git a/src/PayPal/Order/DTO/Eps.php b/src/PayPal/Order/DTO/Eps.php new file mode 100644 index 000000000..213099ec1 --- /dev/null +++ b/src/PayPal/Order/DTO/Eps.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Eps +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/EpsRequest.php b/src/PayPal/Order/DTO/EpsRequest.php new file mode 100644 index 000000000..2d47fc765 --- /dev/null +++ b/src/PayPal/Order/DTO/EpsRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class EpsRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/ExchangeRate.php b/src/PayPal/Order/DTO/ExchangeRate.php new file mode 100644 index 000000000..974a5062e --- /dev/null +++ b/src/PayPal/Order/DTO/ExchangeRate.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ExchangeRate +{ + /** + * The [three-character ISO-4217 currency code](/api/rest/reference/currency-codes/) that identifies the currency. + * + * @var string|null + */ + protected $source_currency; + + /** + * The [three-character ISO-4217 currency code](/api/rest/reference/currency-codes/) that identifies the currency. + * + * @var string|null + */ + protected $target_currency; + + /** + * The target currency amount. Equivalent to one unit of the source currency. Formatted as integer or decimal value with one to 15 digits to the right of the decimal point. + * + * @var string|null + */ + protected $value; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->source_currency = isset($data['source_currency']) ? $data['source_currency'] : null; + $this->target_currency = isset($data['target_currency']) ? $data['target_currency'] : null; + $this->value = isset($data['value']) ? $data['value'] : null; + } + + /** + * Gets source_currency. + * + * @return string|null + */ + public function getSourceCurrency() + { + return $this->source_currency; + } + + /** + * Sets source_currency. + * + * @param string|null $source_currency the [three-character ISO-4217 currency code](/api/rest/reference/currency-codes/) that identifies the currency + * + * @return $this + */ + public function setSourceCurrency($source_currency = null) + { + $this->source_currency = $source_currency; + + return $this; + } + + /** + * Gets target_currency. + * + * @return string|null + */ + public function getTargetCurrency() + { + return $this->target_currency; + } + + /** + * Sets target_currency. + * + * @param string|null $target_currency the [three-character ISO-4217 currency code](/api/rest/reference/currency-codes/) that identifies the currency + * + * @return $this + */ + public function setTargetCurrency($target_currency = null) + { + $this->target_currency = $target_currency; + + return $this; + } + + /** + * Gets value. + * + * @return string|null + */ + public function getValue() + { + return $this->value; + } + + /** + * Sets value. + * + * @param string|null $value The target currency amount. Equivalent to one unit of the source currency. Formatted as integer or decimal value with one to 15 digits to the right of the decimal point. + * + * @return $this + */ + public function setValue($value = null) + { + $this->value = $value; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/ExperienceContextRequest.php b/src/PayPal/Order/DTO/ExperienceContextRequest.php new file mode 100644 index 000000000..09b89e4c4 --- /dev/null +++ b/src/PayPal/Order/DTO/ExperienceContextRequest.php @@ -0,0 +1,135 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ExperienceContextRequest +{ + /** + * @var string + */ + private $brand_name; + /** + * @var string + */ + private $locale; + /** + * @var string + */ + private $shipping_preference; + /** + * @var string + */ + private $return_url; + /** + * @var string + */ + private $cancel_url; + + /** + * @return string + */ + public function getBrandName() + { + return $this->brand_name; + } + + /** + * @param string $brand_name + * + * @return void + */ + public function setBrandName($brand_name) + { + $this->brand_name = $brand_name; + } + + /** + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * @param string $locale + * + * @return void + */ + public function setLocale($locale) + { + $this->locale = $locale; + } + + /** + * @return string + */ + public function getShippingPreference() + { + return $this->shipping_preference; + } + + /** + * @param string $shipping_preference + * + * @return void + */ + public function setShippingPreference($shipping_preference) + { + $this->shipping_preference = $shipping_preference; + } + + /** + * @return string + */ + public function getReturnUrl() + { + return $this->return_url; + } + + /** + * @param string $return_url + * + * @return void + */ + public function setReturnUrl($return_url) + { + $this->return_url = $return_url; + } + + /** + * @return string + */ + public function getCancelUrl() + { + return $this->cancel_url; + } + + /** + * @param string $cancel_url + * + * @return void + */ + public function setCancelUrl($cancel_url) + { + $this->cancel_url = $cancel_url; + } +} diff --git a/src/PayPal/Order/DTO/Giropay.php b/src/PayPal/Order/DTO/Giropay.php new file mode 100644 index 000000000..cb8360172 --- /dev/null +++ b/src/PayPal/Order/DTO/Giropay.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Giropay +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/GiropayRequest.php b/src/PayPal/Order/DTO/GiropayRequest.php new file mode 100644 index 000000000..b85255465 --- /dev/null +++ b/src/PayPal/Order/DTO/GiropayRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class GiropayRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/GooglePayRequest.php b/src/PayPal/Order/DTO/GooglePayRequest.php new file mode 100644 index 000000000..357468971 --- /dev/null +++ b/src/PayPal/Order/DTO/GooglePayRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class GooglePayRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $email_address; + /** + * @var Phone + */ + private $phone_number; + /** + * @var CardAttributesRequest + */ + private $attributes; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return Phone + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * @param Phone $phone_number + * + * @return void + */ + public function setPhoneNumber(Phone $phone_number) + { + $this->phone_number = $phone_number; + } + + /** + * @return CardAttributesRequest + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * @param CardAttributesRequest $attributes + * + * @return void + */ + public function setAttributes(CardAttributesRequest $attributes) + { + $this->attributes = $attributes; + } +} diff --git a/src/PayPal/Order/DTO/Ideal.php b/src/PayPal/Order/DTO/Ideal.php new file mode 100644 index 000000000..d0fb51824 --- /dev/null +++ b/src/PayPal/Order/DTO/Ideal.php @@ -0,0 +1,191 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Ideal +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * The last characters of the IBAN used to pay. + * + * @var string|null + */ + protected $iban_last_chars; + + /** + * @var mixed|null + */ + protected $attributes; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + $this->iban_last_chars = isset($data['iban_last_chars']) ? $data['iban_last_chars'] : null; + $this->attributes = isset($data['attributes']) ? $data['attributes'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } + + /** + * Gets iban_last_chars. + * + * @return string|null + */ + public function getIbanLastChars() + { + return $this->iban_last_chars; + } + + /** + * Sets iban_last_chars. + * + * @param string|null $iban_last_chars the last characters of the IBAN used to pay + * + * @return $this + */ + public function setIbanLastChars($iban_last_chars = null) + { + $this->iban_last_chars = $iban_last_chars; + + return $this; + } + + /** + * Gets attributes. + * + * @return mixed|null + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Sets attributes. + * + * @param mixed|null $attributes + * + * @return $this + */ + public function setAttributes($attributes = null) + { + $this->attributes = $attributes; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/IdealRequest.php b/src/PayPal/Order/DTO/IdealRequest.php new file mode 100644 index 000000000..ad7bea777 --- /dev/null +++ b/src/PayPal/Order/DTO/IdealRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class IdealRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var string + */ + private $bic; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return string + */ + public function getBic() + { + return $this->bic; + } + + /** + * @param string $bic + * + * @return void + */ + public function setBic($bic) + { + $this->bic = $bic; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/Item.php b/src/PayPal/Order/DTO/Item.php new file mode 100644 index 000000000..a0a916697 --- /dev/null +++ b/src/PayPal/Order/DTO/Item.php @@ -0,0 +1,253 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Item +{ + /** + * The item name or title. + * + * @var string + */ + protected $name; + + /** + * @var Amount + */ + protected $unit_amount; + + /** + * The item quantity. Must be a whole number. + * + * @var string + */ + protected $quantity; + + /** + * @var Amount|null + */ + protected $tax; + + /** + * The detailed item description. + * + * @var string|null + */ + protected $description; + + /** + * The stock keeping unit (SKU) for the item. + * + * @var string|null + */ + protected $sku; + + /** + * The item category type. + * + * @var string|null + */ + protected $category; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->unit_amount = isset($data['unit_amount']) ? $data['unit_amount'] : null; + $this->quantity = isset($data['quantity']) ? $data['quantity'] : null; + $this->tax = isset($data['tax']) ? $data['tax'] : null; + $this->description = isset($data['description']) ? $data['description'] : null; + $this->sku = isset($data['sku']) ? $data['sku'] : null; + $this->category = isset($data['category']) ? $data['category'] : null; + } + + /** + * Gets name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string $name the item name or title + * + * @return $this + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Gets unit_amount. + * + * @return Amount + */ + public function getUnitAmount() + { + return $this->unit_amount; + } + + /** + * Sets unit_amount. + * + * @param Amount $unit_amount + * + * @return $this + */ + public function setUnitAmount(Amount $unit_amount) + { + $this->unit_amount = $unit_amount; + + return $this; + } + + /** + * Gets quantity. + * + * @return string + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * Sets quantity. + * + * @param string $quantity The item quantity. Must be a whole number. + * + * @return $this + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + + return $this; + } + + /** + * Gets tax. + * + * @return Amount|null + */ + public function getTax() + { + return $this->tax; + } + + /** + * Sets tax. + * + * @param Amount|null $tax + * + * @return $this + */ + public function setTax(Amount $tax = null) + { + $this->tax = $tax; + + return $this; + } + + /** + * Gets description. + * + * @return string|null + */ + public function getDescription() + { + return $this->description; + } + + /** + * Sets description. + * + * @param string|null $description the detailed item description + * + * @return $this + */ + public function setDescription($description = null) + { + $this->description = $description; + + return $this; + } + + /** + * Gets sku. + * + * @return string|null + */ + public function getSku() + { + return $this->sku; + } + + /** + * Sets sku. + * + * @param string|null $sku the stock keeping unit (SKU) for the item + * + * @return $this + */ + public function setSku($sku = null) + { + $this->sku = $sku; + + return $this; + } + + /** + * Gets category. + * + * @return string|null + */ + public function getCategory() + { + return $this->category; + } + + /** + * Sets category. + * + * @param string|null $category the item category type + * + * @return $this + */ + public function setCategory($category = null) + { + $this->category = $category; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/ItemRequest.php b/src/PayPal/Order/DTO/ItemRequest.php new file mode 100644 index 000000000..fe50e7ded --- /dev/null +++ b/src/PayPal/Order/DTO/ItemRequest.php @@ -0,0 +1,179 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ItemRequest +{ + /** + * @var string + */ + private $name; + /** + * @var Amount + */ + private $unit_amount; + /** + * @var Amount + */ + private $tax; + /** + * @var string + */ + private $quantity; + /** + * @var string + */ + private $description; + /** + * @var string + */ + private $sku; + /** + * @var string + */ + private $category; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return Amount + */ + public function getUnitAmount() + { + return $this->unit_amount; + } + + /** + * @param Amount $unit_amount + * + * @return void + */ + public function setUnitAmount(Amount $unit_amount) + { + $this->unit_amount = $unit_amount; + } + + /** + * @return Amount + */ + public function getTax() + { + return $this->tax; + } + + /** + * @param Amount $tax + * + * @return void + */ + public function setTax(Amount $tax) + { + $this->tax = $tax; + } + + /** + * @return string + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * @param string $quantity + * + * @return void + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $description + * + * @return void + */ + public function setDescription($description) + { + $this->description = $description; + } + + /** + * @return string + */ + public function getSku() + { + return $this->sku; + } + + /** + * @param string $sku + * + * @return void + */ + public function setSku($sku) + { + $this->sku = $sku; + } + + /** + * @return string + */ + public function getCategory() + { + return $this->category; + } + + /** + * @param string $category + * + * @return void + */ + public function setCategory($category) + { + $this->category = $category; + } +} diff --git a/src/PayPal/Order/DTO/Level2CardProcessingData.php b/src/PayPal/Order/DTO/Level2CardProcessingData.php new file mode 100644 index 000000000..1e118207e --- /dev/null +++ b/src/PayPal/Order/DTO/Level2CardProcessingData.php @@ -0,0 +1,94 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Level2CardProcessingData +{ + /** + * Use this field to pass a purchase identification value of up to 12 ASCII characters for AIB and 17 ASCII characters for all other processors. + * + * @var string|null + */ + protected $invoice_id; + /** + * @var Amount|null + */ + protected $tax_total; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->invoice_id = isset($data['invoice_id']) ? $data['invoice_id'] : null; + $this->tax_total = isset($data['tax_total']) ? $data['tax_total'] : null; + } + + /** + * Gets invoice_id. + * + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * Sets invoice_id. + * + * @param string|null $invoice_id use this field to pass a purchase identification value of up to 12 ASCII characters for AIB and 17 ASCII characters for all other processors + * + * @return $this + */ + public function setInvoiceId($invoice_id = null) + { + $this->invoice_id = $invoice_id; + + return $this; + } + + /** + * Gets tax_total. + * + * @return Amount|null + */ + public function getTaxTotal() + { + return $this->tax_total; + } + + /** + * Sets tax_total. + * + * @param Amount|null $tax_total + * + * @return $this + */ + public function setTaxTotal(Amount $tax_total = null) + { + $this->tax_total = $tax_total; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php b/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php new file mode 100644 index 000000000..755d53217 --- /dev/null +++ b/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Level2CardProcessingDataRequest +{ + /** + * @var string + */ + private $invoice_id; + /** + * @var Amount + */ + private $tax_total; + + /** + * @return string + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * @param string $invoice_id + * + * @return void + */ + public function setInvoiceId($invoice_id) + { + $this->invoice_id = $invoice_id; + } + + /** + * @return Amount + */ + public function getTaxTotal() + { + return $this->tax_total; + } + + /** + * @param Amount $tax_total + * + * @return void + */ + public function setTaxTotal(Amount $tax_total) + { + $this->tax_total = $tax_total; + } +} diff --git a/src/PayPal/Order/DTO/Level3CardProcessingData.php b/src/PayPal/Order/DTO/Level3CardProcessingData.php new file mode 100644 index 000000000..d06cd9ed7 --- /dev/null +++ b/src/PayPal/Order/DTO/Level3CardProcessingData.php @@ -0,0 +1,212 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Level3CardProcessingData +{ + /** + * @var Amount|null + */ + protected $shipping_amount; + /** + * @var Amount|null + */ + protected $duty_amount; + /** + * @var Amount|null + */ + protected $discount_amount; + /** + * @var AddressRequest|null + */ + protected $shipping_address; + /** + * Use this field to specify the postal code of the shipping location. + * + * @var string|null + */ + protected $ships_from_postal_code; + /** + * A list of the items that were purchased with this payment. If your merchant account has been configured for Level 3 processing this field will be passed to the processor on your behalf. + * + * @var LineItem[]|null + */ + protected $line_items; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->shipping_amount = isset($data['shipping_amount']) ? $data['shipping_amount'] : null; + $this->duty_amount = isset($data['duty_amount']) ? $data['duty_amount'] : null; + $this->discount_amount = isset($data['discount_amount']) ? $data['discount_amount'] : null; + $this->shipping_address = isset($data['shipping_address']) ? $data['shipping_address'] : null; + $this->ships_from_postal_code = isset($data['ships_from_postal_code']) ? $data['ships_from_postal_code'] : null; + $this->line_items = isset($data['line_items']) ? $data['line_items'] : null; + } + + /** + * Gets shipping_amount. + * + * @return Amount|null + */ + public function getShippingAmount() + { + return $this->shipping_amount; + } + + /** + * Sets shipping_amount. + * + * @param Amount|null $shipping_amount + * + * @return $this + */ + public function setShippingAmount(Amount $shipping_amount = null) + { + $this->shipping_amount = $shipping_amount; + + return $this; + } + + /** + * Gets duty_amount. + * + * @return Amount|null + */ + public function getDutyAmount() + { + return $this->duty_amount; + } + + /** + * Sets duty_amount. + * + * @param Amount|null $duty_amount + * + * @return $this + */ + public function setDutyAmount(Amount $duty_amount = null) + { + $this->duty_amount = $duty_amount; + + return $this; + } + + /** + * Gets discount_amount. + * + * @return Amount|null + */ + public function getDiscountAmount() + { + return $this->discount_amount; + } + + /** + * Sets discount_amount. + * + * @param Amount|null $discount_amount + * + * @return $this + */ + public function setDiscountAmount(Amount $discount_amount = null) + { + $this->discount_amount = $discount_amount; + + return $this; + } + + /** + * Gets shipping_address. + * + * @return AddressRequest|null + */ + public function getShippingAddress() + { + return $this->shipping_address; + } + + /** + * Sets shipping_address. + * + * @param AddressRequest|null $shipping_address + * + * @return $this + */ + public function setShippingAddress(AddressRequest $shipping_address = null) + { + $this->shipping_address = $shipping_address; + + return $this; + } + + /** + * Gets ships_from_postal_code. + * + * @return string|null + */ + public function getShipsFromPostalCode() + { + return $this->ships_from_postal_code; + } + + /** + * Sets ships_from_postal_code. + * + * @param string|null $ships_from_postal_code use this field to specify the postal code of the shipping location + * + * @return $this + */ + public function setShipsFromPostalCode($ships_from_postal_code = null) + { + $this->ships_from_postal_code = $ships_from_postal_code; + + return $this; + } + + /** + * Gets line_items. + * + * @return LineItem[]|null + */ + public function getLineItems() + { + return $this->line_items; + } + + /** + * Sets line_items. + * + * @param LineItem[]|null $line_items A list of the items that were purchased with this payment. If your merchant account has been configured for Level 3 processing this field will be passed to the processor on your behalf. + * + * @return $this + */ + public function setLineItems(array $line_items = null) + { + $this->line_items = $line_items; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php b/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php new file mode 100644 index 000000000..606cfe58d --- /dev/null +++ b/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php @@ -0,0 +1,157 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Level3CardProcessingDataRequest +{ + /** + * @var Amount + */ + private $shipping_amount; + /** + * @var Amount + */ + private $duty_amount; + /** + * @var Amount + */ + private $discount_amount; + /** + * @var AddressRequest + */ + private $shipping_address; + /** + * @var string + */ + private $ships_from_postal_code; + /** + * @var LineItemRequest[] + */ + private $line_items; + + /** + * @return Amount + */ + public function getShippingAmount() + { + return $this->shipping_amount; + } + + /** + * @param Amount $shipping_amount + * + * @return void + */ + public function setShippingAmount(Amount $shipping_amount) + { + $this->shipping_amount = $shipping_amount; + } + + /** + * @return Amount + */ + public function getDutyAmount() + { + return $this->duty_amount; + } + + /** + * @param Amount $duty_amount + * + * @return void + */ + public function setDutyAmount(Amount $duty_amount) + { + $this->duty_amount = $duty_amount; + } + + /** + * @return Amount + */ + public function getDiscountAmount() + { + return $this->discount_amount; + } + + /** + * @param Amount $discount_amount + * + * @return void + */ + public function setDiscountAmount(Amount $discount_amount) + { + $this->discount_amount = $discount_amount; + } + + /** + * @return AddressRequest + */ + public function getShippingAddress() + { + return $this->shipping_address; + } + + /** + * @param AddressRequest $shipping_address + * + * @return void + */ + public function setShippingAddress(AddressRequest $shipping_address) + { + $this->shipping_address = $shipping_address; + } + + /** + * @return string + */ + public function getShipsFromPostalCode() + { + return $this->ships_from_postal_code; + } + + /** + * @param string $ships_from_postal_code + * + * @return void + */ + public function setShipsFromPostalCode($ships_from_postal_code) + { + $this->ships_from_postal_code = $ships_from_postal_code; + } + + /** + * @return LineItemRequest[] + */ + public function getLineItems() + { + return $this->line_items; + } + + /** + * @param LineItemRequest[] $line_items + * + * @return void + */ + public function setLineItems(array $line_items) + { + $this->line_items = $line_items; + } +} diff --git a/src/PayPal/Order/DTO/LineItem.php b/src/PayPal/Order/DTO/LineItem.php new file mode 100644 index 000000000..bee9c0fbb --- /dev/null +++ b/src/PayPal/Order/DTO/LineItem.php @@ -0,0 +1,367 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class LineItem +{ + /** + * The item name or title. + * + * @var string + */ + protected $name; + /** + * @var Amount + */ + protected $unit_amount; + /** + * The item quantity. Must be a whole number. + * + * @var string + */ + protected $quantity; + /** + * @var Amount|null + */ + protected $tax; + /** + * The detailed item description. + * + * @var string|null + */ + protected $description; + /** + * The stock keeping unit (SKU) for the item. + * + * @var string|null + */ + protected $sku; + /** + * The item category type. + * + * @var string|null + */ + protected $category; + /** + * Code used to classify items purchased and track the total amount spent across various categories of products and services. Different corporate purchasing organizations may use different standards, but the United Nations Standard Products and Services Code (UNSPSC) is frequently used. + * + * @var string|null + */ + protected $commodity_code; + /** + * @var Amount|null + */ + protected $discount_amount; + /** + * @var Amount|null + */ + protected $total_amount; + /** + * Unit of measure is a standard used to express the magnitude of a quantity in international trade. Most commonly used (but not limited to) examples are: Acre (ACR), Ampere (AMP), Centigram (CGM), Centimetre (CMT), Cubic inch (INQ), Cubic metre (MTQ), Fluid ounce (OZA), Foot (FOT), Hour (HUR), Item (ITM), Kilogram (KGM), Kilometre (KMT), Kilowatt (KWT), Liquid gallon (GLL), Liter (LTR), Pounds (LBS), Square foot (FTK). + * + * @var string|null + */ + protected $unit_of_measure; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->unit_amount = isset($data['unit_amount']) ? $data['unit_amount'] : null; + $this->quantity = isset($data['quantity']) ? $data['quantity'] : null; + $this->tax = isset($data['tax']) ? $data['tax'] : null; + $this->description = isset($data['description']) ? $data['description'] : null; + $this->sku = isset($data['sku']) ? $data['sku'] : null; + $this->category = isset($data['category']) ? $data['category'] : null; + $this->commodity_code = isset($data['commodity_code']) ? $data['commodity_code'] : null; + $this->discount_amount = isset($data['discount_amount']) ? $data['discount_amount'] : null; + $this->total_amount = isset($data['total_amount']) ? $data['total_amount'] : null; + $this->unit_of_measure = isset($data['unit_of_measure']) ? $data['unit_of_measure'] : null; + } + + /** + * Gets name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string $name the item name or title + * + * @return $this + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Gets unit_amount. + * + * @return Amount + */ + public function getUnitAmount() + { + return $this->unit_amount; + } + + /** + * Sets unit_amount. + * + * @param Amount $unit_amount + * + * @return $this + */ + public function setUnitAmount(Amount $unit_amount) + { + $this->unit_amount = $unit_amount; + + return $this; + } + + /** + * Gets quantity. + * + * @return string + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * Sets quantity. + * + * @param string $quantity The item quantity. Must be a whole number. + * + * @return $this + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + + return $this; + } + + /** + * Gets tax. + * + * @return Amount|null + */ + public function getTax() + { + return $this->tax; + } + + /** + * Sets tax. + * + * @param Amount|null $tax + * + * @return $this + */ + public function setTax(Amount $tax = null) + { + $this->tax = $tax; + + return $this; + } + + /** + * Gets description. + * + * @return string|null + */ + public function getDescription() + { + return $this->description; + } + + /** + * Sets description. + * + * @param string|null $description the detailed item description + * + * @return $this + */ + public function setDescription($description = null) + { + $this->description = $description; + + return $this; + } + + /** + * Gets sku. + * + * @return string|null + */ + public function getSku() + { + return $this->sku; + } + + /** + * Sets sku. + * + * @param string|null $sku the stock keeping unit (SKU) for the item + * + * @return $this + */ + public function setSku($sku = null) + { + $this->sku = $sku; + + return $this; + } + + /** + * Gets category. + * + * @return string|null + */ + public function getCategory() + { + return $this->category; + } + + /** + * Sets category. + * + * @param string|null $category the item category type + * + * @return $this + */ + public function setCategory($category = null) + { + $this->category = $category; + + return $this; + } + + /** + * Gets commodity_code. + * + * @return string|null + */ + public function getCommodityCode() + { + return $this->commodity_code; + } + + /** + * Sets commodity_code. + * + * @param string|null $commodity_code Code used to classify items purchased and track the total amount spent across various categories of products and services. Different corporate purchasing organizations may use different standards, but the United Nations Standard Products and Services Code (UNSPSC) is frequently used. + * + * @return $this + */ + public function setCommodityCode($commodity_code = null) + { + $this->commodity_code = $commodity_code; + + return $this; + } + + /** + * Gets discount_amount. + * + * @return Amount|null + */ + public function getDiscountAmount() + { + return $this->discount_amount; + } + + /** + * Sets discount_amount. + * + * @param Amount|null $discount_amount + * + * @return $this + */ + public function setDiscountAmount(Amount $discount_amount = null) + { + $this->discount_amount = $discount_amount; + + return $this; + } + + /** + * Gets total_amount. + * + * @return Amount|null + */ + public function getTotalAmount() + { + return $this->total_amount; + } + + /** + * Sets total_amount. + * + * @param Amount|null $total_amount + * + * @return $this + */ + public function setTotalAmount(Amount $total_amount = null) + { + $this->total_amount = $total_amount; + + return $this; + } + + /** + * Gets unit_of_measure. + * + * @return string|null + */ + public function getUnitOfMeasure() + { + return $this->unit_of_measure; + } + + /** + * Sets unit_of_measure. + * + * @param string|null $unit_of_measure Unit of measure is a standard used to express the magnitude of a quantity in international trade. Most commonly used (but not limited to) examples are: Acre (ACR), Ampere (AMP), Centigram (CGM), Centimetre (CMT), Cubic inch (INQ), Cubic metre (MTQ), Fluid ounce (OZA), Foot (FOT), Hour (HUR), Item (ITM), Kilogram (KGM), Kilometre (KMT), Kilowatt (KWT), Liquid gallon (GLL), Liter (LTR), Pounds (LBS), Square foot (FTK). + * + * @return $this + */ + public function setUnitOfMeasure($unit_of_measure = null) + { + $this->unit_of_measure = $unit_of_measure; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/LineItemRequest.php b/src/PayPal/Order/DTO/LineItemRequest.php new file mode 100644 index 000000000..dec30d352 --- /dev/null +++ b/src/PayPal/Order/DTO/LineItemRequest.php @@ -0,0 +1,267 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class LineItemRequest +{ + /** + * @var string + */ + private $name; + /** + * @var Amount + */ + private $unit_amount; + /** + * @var Amount + */ + private $tax; + /** + * @var string + */ + private $quantity; + /** + * @var string + */ + private $description; + /** + * @var string + */ + private $sku; + /** + * @var string + */ + private $category; + /** + * @var string + */ + private $commodity_code; + /** + * @var Amount + */ + private $discount_amount; + /** + * @var Amount + */ + private $total_amount; + /** + * @var string + */ + private $unit_of_measure; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return Amount + */ + public function getUnitAmount() + { + return $this->unit_amount; + } + + /** + * @param Amount $unit_amount + * + * @return void + */ + public function setUnitAmount(Amount $unit_amount) + { + $this->unit_amount = $unit_amount; + } + + /** + * @return Amount + */ + public function getTax() + { + return $this->tax; + } + + /** + * @param Amount $tax + * + * @return void + */ + public function setTax(Amount $tax) + { + $this->tax = $tax; + } + + /** + * @return string + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * @param string $quantity + * + * @return void + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $description + * + * @return void + */ + public function setDescription($description) + { + $this->description = $description; + } + + /** + * @return string + */ + public function getSku() + { + return $this->sku; + } + + /** + * @param string $sku + * + * @return void + */ + public function setSku($sku) + { + $this->sku = $sku; + } + + /** + * @return string + */ + public function getCategory() + { + return $this->category; + } + + /** + * @param string $category + * + * @return void + */ + public function setCategory($category) + { + $this->category = $category; + } + + /** + * @return string + */ + public function getCommodityCode() + { + return $this->commodity_code; + } + + /** + * @param string $commodity_code + * + * @return void + */ + public function setCommodityCode($commodity_code) + { + $this->commodity_code = $commodity_code; + } + + /** + * @return Amount + */ + public function getDiscountAmount() + { + return $this->discount_amount; + } + + /** + * @param Amount $discount_amount + * + * @return void + */ + public function setDiscountAmount(Amount $discount_amount) + { + $this->discount_amount = $discount_amount; + } + + /** + * @return Amount + */ + public function getTotalAmount() + { + return $this->total_amount; + } + + /** + * @param Amount $total_amount + * + * @return void + */ + public function setTotalAmount(Amount $total_amount) + { + $this->total_amount = $total_amount; + } + + /** + * @return string + */ + public function getUnitOfMeasure() + { + return $this->unit_of_measure; + } + + /** + * @param string $unit_of_measure + * + * @return void + */ + public function setUnitOfMeasure($unit_of_measure) + { + $this->unit_of_measure = $unit_of_measure; + } +} diff --git a/src/PayPal/Order/DTO/LinkDescription.php b/src/PayPal/Order/DTO/LinkDescription.php new file mode 100644 index 000000000..656785bac --- /dev/null +++ b/src/PayPal/Order/DTO/LinkDescription.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class LinkDescription +{ + /** + * The complete target URL. To make the related call, combine the method with this [URI Template-formatted](https://tools.ietf.org/html/rfc6570) link. For pre-processing, include the `$`, `(`, and `)` characters. The `href` is the key HATEOAS component that links a completed call with a subsequent call. + * + * @var string + */ + protected $href; + + /** + * The [link relation type](https://tools.ietf.org/html/rfc5988#section-4), which serves as an ID for a link that unambiguously describes the semantics of the link. See [Link Relations](https://www.iana.org/assignments/link-relations/link-relations.xhtml). + * + * @var string + */ + protected $rel; + + /** + * The HTTP method required to make the related call. + * + * @var string|null + */ + protected $method; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->href = isset($data['href']) ? $data['href'] : null; + $this->rel = isset($data['rel']) ? $data['rel'] : null; + $this->method = isset($data['method']) ? $data['method'] : null; + } + + /** + * Gets href. + * + * @return string + */ + public function getHref() + { + return $this->href; + } + + /** + * Sets href. + * + * @param string $href The complete target URL. To make the related call, combine the method with this [URI Template-formatted](https://tools.ietf.org/html/rfc6570) link. For pre-processing, include the `$`, `(`, and `)` characters. The `href` is the key HATEOAS component that links a completed call with a subsequent call. + * + * @return $this + */ + public function setHref($href) + { + $this->href = $href; + + return $this; + } + + /** + * Gets rel. + * + * @return string + */ + public function getRel() + { + return $this->rel; + } + + /** + * Sets rel. + * + * @param string $rel The [link relation type](https://tools.ietf.org/html/rfc5988#section-4), which serves as an ID for a link that unambiguously describes the semantics of the link. See [Link Relations](https://www.iana.org/assignments/link-relations/link-relations.xhtml). + * + * @return $this + */ + public function setRel($rel) + { + $this->rel = $rel; + + return $this; + } + + /** + * Gets method. + * + * @return string|null + */ + public function getMethod() + { + return $this->method; + } + + /** + * Sets method. + * + * @param string|null $method the HTTP method required to make the related call + * + * @return $this + */ + public function setMethod($method = null) + { + $this->method = $method; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/MerchantPayableBreakdown.php b/src/PayPal/Order/DTO/MerchantPayableBreakdown.php new file mode 100644 index 000000000..cfdd794df --- /dev/null +++ b/src/PayPal/Order/DTO/MerchantPayableBreakdown.php @@ -0,0 +1,277 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class MerchantPayableBreakdown +{ + /** + * @var Amount|null + */ + protected $gross_amount; + + /** + * @var Amount|null + */ + protected $paypal_fee; + + /** + * @var Amount|null + */ + protected $paypal_fee_in_receivable_currency; + + /** + * @var Amount|null + */ + protected $net_amount; + + /** + * @var Amount|null + */ + protected $net_amount_in_receivable_currency; + + /** + * An array of platform or partner fees, commissions, or brokerage fees for the refund. + * + * @var PlatformFee[]|null + */ + protected $platform_fees; + + /** + * An array of breakdown values for the net amount. Returned when the currency of the refund is different from the currency of the PayPal account where the payee holds their funds. + * + * @var NetAmountBreakdownItem[]|null + */ + protected $net_amount_breakdown; + + /** + * @var Amount|null + */ + protected $total_refunded_amount; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->gross_amount = isset($data['gross_amount']) ? $data['gross_amount'] : null; + $this->paypal_fee = isset($data['paypal_fee']) ? $data['paypal_fee'] : null; + $this->paypal_fee_in_receivable_currency = isset($data['paypal_fee_in_receivable_currency']) ? $data['paypal_fee_in_receivable_currency'] : null; + $this->net_amount = isset($data['net_amount']) ? $data['net_amount'] : null; + $this->net_amount_in_receivable_currency = isset($data['net_amount_in_receivable_currency']) ? $data['net_amount_in_receivable_currency'] : null; + $this->platform_fees = isset($data['platform_fees']) ? $data['platform_fees'] : null; + $this->net_amount_breakdown = isset($data['net_amount_breakdown']) ? $data['net_amount_breakdown'] : null; + $this->total_refunded_amount = isset($data['total_refunded_amount']) ? $data['total_refunded_amount'] : null; + } + + /** + * Gets gross_amount. + * + * @return Amount|null + */ + public function getGrossAmount() + { + return $this->gross_amount; + } + + /** + * Sets gross_amount. + * + * @param Amount|null $gross_amount + * + * @return $this + */ + public function setGrossAmount(Amount $gross_amount = null) + { + $this->gross_amount = $gross_amount; + + return $this; + } + + /** + * Gets paypal_fee. + * + * @return Amount|null + */ + public function getPaypalFee() + { + return $this->paypal_fee; + } + + /** + * Sets paypal_fee. + * + * @param Amount|null $paypal_fee + * + * @return $this + */ + public function setPaypalFee(Amount $paypal_fee = null) + { + $this->paypal_fee = $paypal_fee; + + return $this; + } + + /** + * Gets paypal_fee_in_receivable_currency. + * + * @return Amount|null + */ + public function getPaypalFeeInReceivableCurrency() + { + return $this->paypal_fee_in_receivable_currency; + } + + /** + * Sets paypal_fee_in_receivable_currency. + * + * @param Amount|null $paypal_fee_in_receivable_currency + * + * @return $this + */ + public function setPaypalFeeInReceivableCurrency(Amount $paypal_fee_in_receivable_currency = null) + { + $this->paypal_fee_in_receivable_currency = $paypal_fee_in_receivable_currency; + + return $this; + } + + /** + * Gets net_amount. + * + * @return Amount|null + */ + public function getNetAmount() + { + return $this->net_amount; + } + + /** + * Sets net_amount. + * + * @param Amount|null $net_amount + * + * @return $this + */ + public function setNetAmount(Amount $net_amount = null) + { + $this->net_amount = $net_amount; + + return $this; + } + + /** + * Gets net_amount_in_receivable_currency. + * + * @return Amount|null + */ + public function getNetAmountInReceivableCurrency() + { + return $this->net_amount_in_receivable_currency; + } + + /** + * Sets net_amount_in_receivable_currency. + * + * @param Amount|null $net_amount_in_receivable_currency + * + * @return $this + */ + public function setNetAmountInReceivableCurrency(Amount $net_amount_in_receivable_currency = null) + { + $this->net_amount_in_receivable_currency = $net_amount_in_receivable_currency; + + return $this; + } + + /** + * Gets platform_fees. + * + * @return PlatformFee[]|null + */ + public function getPlatformFees() + { + return $this->platform_fees; + } + + /** + * Sets platform_fees. + * + * @param PlatformFee[]|null $platform_fees an array of platform or partner fees, commissions, or brokerage fees for the refund + * + * @return $this + */ + public function setPlatformFees(array $platform_fees = null) + { + $this->platform_fees = $platform_fees; + + return $this; + } + + /** + * Gets net_amount_breakdown. + * + * @return NetAmountBreakdownItem[]|null + */ + public function getNetAmountBreakdown() + { + return $this->net_amount_breakdown; + } + + /** + * Sets net_amount_breakdown. + * + * @param NetAmountBreakdownItem[]|null $net_amount_breakdown An array of breakdown values for the net amount. Returned when the currency of the refund is different from the currency of the PayPal account where the payee holds their funds. + * + * @return $this + */ + public function setNetAmountBreakdown(array $net_amount_breakdown = null) + { + $this->net_amount_breakdown = $net_amount_breakdown; + + return $this; + } + + /** + * Gets total_refunded_amount. + * + * @return Amount|null + */ + public function getTotalRefundedAmount() + { + return $this->total_refunded_amount; + } + + /** + * Sets total_refunded_amount. + * + * @param Amount|null $total_refunded_amount + * + * @return $this + */ + public function setTotalRefundedAmount(Amount $total_refunded_amount = null) + { + $this->total_refunded_amount = $total_refunded_amount; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/MyBankRequest.php b/src/PayPal/Order/DTO/MyBankRequest.php new file mode 100644 index 000000000..282d5a364 --- /dev/null +++ b/src/PayPal/Order/DTO/MyBankRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class MyBankRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/Mybank.php b/src/PayPal/Order/DTO/Mybank.php new file mode 100644 index 000000000..f79946321 --- /dev/null +++ b/src/PayPal/Order/DTO/Mybank.php @@ -0,0 +1,161 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Mybank +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * The last characters of the IBAN used to pay. + * + * @var string|null + */ + protected $iban_last_chars; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + $this->iban_last_chars = isset($data['iban_last_chars']) ? $data['iban_last_chars'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } + + /** + * Gets iban_last_chars. + * + * @return string|null + */ + public function getIbanLastChars() + { + return $this->iban_last_chars; + } + + /** + * Sets iban_last_chars. + * + * @param string|null $iban_last_chars the last characters of the IBAN used to pay + * + * @return $this + */ + public function setIbanLastChars($iban_last_chars = null) + { + $this->iban_last_chars = $iban_last_chars; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Name.php b/src/PayPal/Order/DTO/Name.php new file mode 100644 index 000000000..2ef3b62c7 --- /dev/null +++ b/src/PayPal/Order/DTO/Name.php @@ -0,0 +1,179 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Name +{ + /** + * @var string + */ + private $prefix; + /** + * @var string + */ + private $given_name; + /** + * @var string + */ + private $surname; + /** + * @var string + */ + private $middle_name; + /** + * @var string + */ + private $suffix; + /** + * @var string + */ + private $alternate_full_name; + /** + * @var string + */ + private $full_name; + + /** + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * @param string $prefix + * + * @return void + */ + public function setPrefix($prefix) + { + $this->prefix = $prefix; + } + + /** + * @return string + */ + public function getGivenName() + { + return $this->given_name; + } + + /** + * @param string $given_name + * + * @return void + */ + public function setGivenName($given_name) + { + $this->given_name = $given_name; + } + + /** + * @return string + */ + public function getSurname() + { + return $this->surname; + } + + /** + * @param string $surname + * + * @return void + */ + public function setSurname($surname) + { + $this->surname = $surname; + } + + /** + * @return string + */ + public function getMiddleName() + { + return $this->middle_name; + } + + /** + * @param string $middle_name + * + * @return void + */ + public function setMiddleName($middle_name) + { + $this->middle_name = $middle_name; + } + + /** + * @return string + */ + public function getSuffix() + { + return $this->suffix; + } + + /** + * @param string $suffix + * + * @return void + */ + public function setSuffix($suffix) + { + $this->suffix = $suffix; + } + + /** + * @return string + */ + public function getAlternateFullName() + { + return $this->alternate_full_name; + } + + /** + * @param string $alternate_full_name + * + * @return void + */ + public function setAlternateFullName($alternate_full_name) + { + $this->alternate_full_name = $alternate_full_name; + } + + /** + * @return string + */ + public function getFullName() + { + return $this->full_name; + } + + /** + * @param string $full_name + * + * @return void + */ + public function setFullName($full_name) + { + $this->full_name = $full_name; + } +} diff --git a/src/PayPal/Order/DTO/NetAmountBreakdownItem.php b/src/PayPal/Order/DTO/NetAmountBreakdownItem.php new file mode 100644 index 000000000..8914d5de1 --- /dev/null +++ b/src/PayPal/Order/DTO/NetAmountBreakdownItem.php @@ -0,0 +1,123 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class NetAmountBreakdownItem +{ + /** + * @var Amount|null + */ + protected $payable_amount; + + /** + * @var Amount|null + */ + protected $converted_amount; + + /** + * @var ExchangeRate|null + */ + protected $exchange_rate; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->payable_amount = isset($data['payable_amount']) ? $data['payable_amount'] : null; + $this->converted_amount = isset($data['converted_amount']) ? $data['converted_amount'] : null; + $this->exchange_rate = isset($data['exchange_rate']) ? $data['exchange_rate'] : null; + } + + /** + * Gets payable_amount. + * + * @return Amount|null + */ + public function getPayableAmount() + { + return $this->payable_amount; + } + + /** + * Sets payable_amount. + * + * @param Amount|null $payable_amount + * + * @return $this + */ + public function setPayableAmount(Amount $payable_amount = null) + { + $this->payable_amount = $payable_amount; + + return $this; + } + + /** + * Gets converted_amount. + * + * @return Amount|null + */ + public function getConvertedAmount() + { + return $this->converted_amount; + } + + /** + * Sets converted_amount. + * + * @param Amount|null $converted_amount + * + * @return $this + */ + public function setConvertedAmount(Amount $converted_amount = null) + { + $this->converted_amount = $converted_amount; + + return $this; + } + + /** + * Gets exchange_rate. + * + * @return ExchangeRate|null + */ + public function getExchangeRate() + { + return $this->exchange_rate; + } + + /** + * Sets exchange_rate. + * + * @param ExchangeRate|null $exchange_rate + * + * @return $this + */ + public function setExchangeRate(ExchangeRate $exchange_rate = null) + { + $this->exchange_rate = $exchange_rate; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/NetworkTransactionReference.php b/src/PayPal/Order/DTO/NetworkTransactionReference.php new file mode 100644 index 000000000..fd9301651 --- /dev/null +++ b/src/PayPal/Order/DTO/NetworkTransactionReference.php @@ -0,0 +1,159 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class NetworkTransactionReference +{ + /** + * Transaction reference id returned by the scheme. For Visa and Amex, this is the \"Tran id\" field in response. For MasterCard, this is the \"BankNet reference id\" field in response. For Discover, this is the \"NRID\" field in response. The pattern we expect for this field from Visa/Amex/CB/Discover is numeric, Mastercard/BNPP is alphanumeric and Paysecure is alphanumeric with special character -. + * + * @var string + */ + protected $id; + + /** + * The date that the transaction was authorized by the scheme. This field may not be returned for all networks. MasterCard refers to this field as \"BankNet reference date. + * + * @var string|null + */ + protected $date; + + /** + * @var string|null + */ + protected $network; + + /** + * Reference ID issued for the card transaction. This ID can be used to track the transaction across processors, card brands and issuing banks. + * + * @var string|null + */ + protected $acquirer_reference_number; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->date = isset($data['date']) ? $data['date'] : null; + $this->network = isset($data['network']) ? $data['network'] : null; + $this->acquirer_reference_number = isset($data['acquirer_reference_number']) ? $data['acquirer_reference_number'] : null; + } + + /** + * Gets id. + * + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string $id Transaction reference id returned by the scheme. For Visa and Amex, this is the \"Tran id\" field in response. For MasterCard, this is the \"BankNet reference id\" field in response. For Discover, this is the \"NRID\" field in response. The pattern we expect for this field from Visa/Amex/CB/Discover is numeric, Mastercard/BNPP is alphanumeric and Paysecure is alphanumeric with special character -. + * + * @return $this + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * Gets date. + * + * @return string|null + */ + public function getDate() + { + return $this->date; + } + + /** + * Sets date. + * + * @param string|null $date The date that the transaction was authorized by the scheme. This field may not be returned for all networks. MasterCard refers to this field as \"BankNet reference date. + * + * @return $this + */ + public function setDate($date = null) + { + $this->date = $date; + + return $this; + } + + /** + * Gets network. + * + * @return string|null + */ + public function getNetwork() + { + return $this->network; + } + + /** + * Sets network. + * + * @param string|null $network + * + * @return $this + */ + public function setNetwork($network = null) + { + $this->network = $network; + + return $this; + } + + /** + * Gets acquirer_reference_number. + * + * @return string|null + */ + public function getAcquirerReferenceNumber() + { + return $this->acquirer_reference_number; + } + + /** + * Sets acquirer_reference_number. + * + * @param string|null $acquirer_reference_number Reference ID issued for the card transaction. This ID can be used to track the transaction across processors, card brands and issuing banks. + * + * @return $this + */ + public function setAcquirerReferenceNumber($acquirer_reference_number = null) + { + $this->acquirer_reference_number = $acquirer_reference_number; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/P24.php b/src/PayPal/Order/DTO/P24.php new file mode 100644 index 000000000..4a1821a07 --- /dev/null +++ b/src/PayPal/Order/DTO/P24.php @@ -0,0 +1,225 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class P24 +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * P24 generated payment description. + * + * @var string|null + */ + protected $payment_descriptor; + + /** + * Numeric identifier of the payment scheme or bank used for the payment. + * + * @var string|null + */ + protected $method_id; + + /** + * Friendly name of the payment scheme or bank used for the payment. + * + * @var string|null + */ + protected $method_description; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->email = isset($data['email']) ? $data['email'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->payment_descriptor = isset($data['payment_descriptor']) ? $data['payment_descriptor'] : null; + $this->method_id = isset($data['method_id']) ? $data['method_id'] : null; + $this->method_description = isset($data['method_description']) ? $data['method_description'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets email. + * + * @return string|null + */ + public function getEmail() + { + return $this->email; + } + + /** + * Sets email. + * + * @param string|null $email The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmail($email = null) + { + $this->email = $email; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets payment_descriptor. + * + * @return string|null + */ + public function getPaymentDescriptor() + { + return $this->payment_descriptor; + } + + /** + * Sets payment_descriptor. + * + * @param string|null $payment_descriptor P24 generated payment description + * + * @return $this + */ + public function setPaymentDescriptor($payment_descriptor = null) + { + $this->payment_descriptor = $payment_descriptor; + + return $this; + } + + /** + * Gets method_id. + * + * @return string|null + */ + public function getMethodId() + { + return $this->method_id; + } + + /** + * Sets method_id. + * + * @param string|null $method_id numeric identifier of the payment scheme or bank used for the payment + * + * @return $this + */ + public function setMethodId($method_id = null) + { + $this->method_id = $method_id; + + return $this; + } + + /** + * Gets method_description. + * + * @return string|null + */ + public function getMethodDescription() + { + return $this->method_description; + } + + /** + * Sets method_description. + * + * @param string|null $method_description friendly name of the payment scheme or bank used for the payment + * + * @return $this + */ + public function setMethodDescription($method_description = null) + { + $this->method_description = $method_description; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/P24Request.php b/src/PayPal/Order/DTO/P24Request.php new file mode 100644 index 000000000..192f32c8d --- /dev/null +++ b/src/PayPal/Order/DTO/P24Request.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class P24Request +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var string + */ + private $email; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return string + */ + public function getEmail() + { + return $this->email; + } + + /** + * @param string $email + * + * @return void + */ + public function setEmail($email) + { + $this->email = $email; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/PayPalRequest.php b/src/PayPal/Order/DTO/PayPalRequest.php new file mode 100644 index 000000000..6ef76aa4c --- /dev/null +++ b/src/PayPal/Order/DTO/PayPalRequest.php @@ -0,0 +1,245 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PayPalRequest +{ + /** + * @var string + */ + private $vault_id; + /** + * @var string + */ + private $email_address; + /** + * @var Name + */ + private $name; + /** + * @var PhoneWithType + */ + private $phone; + /** + * @var string + */ + private $bith_date; + /** + * @var TaxInfo + */ + private $tax_info; + /** + * @var AddressRequest + */ + private $address; + /** + * @var PayPalWalletAttributesRequest + */ + private $attributes; + /** + * @var PayPalWalletExperienceContext + */ + private $experience_context; + /** + * @var string + */ + private $billing_agreement_id; + + /** + * @return string + */ + public function getVaultId() + { + return $this->vault_id; + } + + /** + * @param string $vault_id + * + * @return void + */ + public function setVaultId($vault_id) + { + $this->vault_id = $vault_id; + } + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return Name + */ + public function getName() + { + return $this->name; + } + + /** + * @param Name $name + * + * @return void + */ + public function setName(Name $name) + { + $this->name = $name; + } + + /** + * @return PhoneWithType + */ + public function getPhone() + { + return $this->phone; + } + + /** + * @param PhoneWithType $phone + * + * @return void + */ + public function setPhone(PhoneWithType $phone) + { + $this->phone = $phone; + } + + /** + * @return string + */ + public function getBithDate() + { + return $this->bith_date; + } + + /** + * @param string $bith_date + * + * @return void + */ + public function setBithDate($bith_date) + { + $this->bith_date = $bith_date; + } + + /** + * @return TaxInfo + */ + public function getTaxInfo() + { + return $this->tax_info; + } + + /** + * @param TaxInfo $tax_info + * + * @return void + */ + public function setTaxInfo(TaxInfo $tax_info) + { + $this->tax_info = $tax_info; + } + + /** + * @return AddressRequest + */ + public function getAddress() + { + return $this->address; + } + + /** + * @param AddressRequest $address + * + * @return void + */ + public function setAddress(AddressRequest $address) + { + $this->address = $address; + } + + /** + * @return PayPalWalletAttributesRequest + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * @param PayPalWalletAttributesRequest $attributes + * + * @return void + */ + public function setAttributes(PayPalWalletAttributesRequest $attributes) + { + $this->attributes = $attributes; + } + + /** + * @return PayPalWalletExperienceContext + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param PayPalWalletExperienceContext $experience_context + * + * @return void + */ + public function setExperienceContext(PayPalWalletExperienceContext $experience_context) + { + $this->experience_context = $experience_context; + } + + /** + * @return string + */ + public function getBillingAgreementId() + { + return $this->billing_agreement_id; + } + + /** + * @param string $billing_agreement_id + * + * @return void + */ + public function setBillingAgreementId($billing_agreement_id) + { + $this->billing_agreement_id = $billing_agreement_id; + } +} diff --git a/src/PayPal/Order/DTO/PayPalWalletAttributesRequest.php b/src/PayPal/Order/DTO/PayPalWalletAttributesRequest.php new file mode 100644 index 000000000..af45844f4 --- /dev/null +++ b/src/PayPal/Order/DTO/PayPalWalletAttributesRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PayPalWalletAttributesRequest +{ + /** + * @var CustomerRequest + */ + private $customer; + /** + * @var PayPalWalletVaultAttributesRequest + */ + private $vault; + + /** + * @return CustomerRequest + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * @param CustomerRequest $customer + * + * @return void + */ + public function setCustomer(CustomerRequest $customer) + { + $this->customer = $customer; + } + + /** + * @return PayPalWalletVaultAttributesRequest + */ + public function getVault() + { + return $this->vault; + } + + /** + * @param PayPalWalletVaultAttributesRequest $vault + * + * @return void + */ + public function setVault(PayPalWalletVaultAttributesRequest $vault) + { + $this->vault = $vault; + } +} diff --git a/src/PayPal/Order/DTO/PayPalWalletExperienceContext.php b/src/PayPal/Order/DTO/PayPalWalletExperienceContext.php new file mode 100644 index 000000000..38a9d422e --- /dev/null +++ b/src/PayPal/Order/DTO/PayPalWalletExperienceContext.php @@ -0,0 +1,201 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PayPalWalletExperienceContext +{ + /** + * @var string + */ + private $brand_name; + /** + * @var string + */ + private $locale; + /** + * @var string + */ + private $shipping_preference; + /** + * @var string + */ + private $return_url; + /** + * @var string + */ + private $cancel_url; + /** + * @var string + */ + private $landing_page; + /** + * @var string + */ + private $user_action; + /** + * @var string + */ + private $payment_method_preference; + + /** + * @return string + */ + public function getBrandName() + { + return $this->brand_name; + } + + /** + * @param string $brand_name + * + * @return void + */ + public function setBrandName($brand_name) + { + $this->brand_name = $brand_name; + } + + /** + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * @param string $locale + * + * @return void + */ + public function setLocale($locale) + { + $this->locale = $locale; + } + + /** + * @return string + */ + public function getShippingPreference() + { + return $this->shipping_preference; + } + + /** + * @param string $shipping_preference + * + * @return void + */ + public function setShippingPreference($shipping_preference) + { + $this->shipping_preference = $shipping_preference; + } + + /** + * @return string + */ + public function getReturnUrl() + { + return $this->return_url; + } + + /** + * @param string $return_url + * + * @return void + */ + public function setReturnUrl($return_url) + { + $this->return_url = $return_url; + } + + /** + * @return string + */ + public function getCancelUrl() + { + return $this->cancel_url; + } + + /** + * @param string $cancel_url + * + * @return void + */ + public function setCancelUrl($cancel_url) + { + $this->cancel_url = $cancel_url; + } + + /** + * @return string + */ + public function getLandingPage() + { + return $this->landing_page; + } + + /** + * @param string $landing_page + * + * @return void + */ + public function setLandingPage($landing_page) + { + $this->landing_page = $landing_page; + } + + /** + * @return string + */ + public function getUserAction() + { + return $this->user_action; + } + + /** + * @param string $user_action + * + * @return void + */ + public function setUserAction($user_action) + { + $this->user_action = $user_action; + } + + /** + * @return string + */ + public function getPaymentMethodPreference() + { + return $this->payment_method_preference; + } + + /** + * @param string $payment_method_preference + * + * @return void + */ + public function setPaymentMethodPreference($payment_method_preference) + { + $this->payment_method_preference = $payment_method_preference; + } +} diff --git a/src/PayPal/Order/DTO/PayPalWalletVaultAttributesRequest.php b/src/PayPal/Order/DTO/PayPalWalletVaultAttributesRequest.php new file mode 100644 index 000000000..fbfc416c9 --- /dev/null +++ b/src/PayPal/Order/DTO/PayPalWalletVaultAttributesRequest.php @@ -0,0 +1,179 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PayPalWalletVaultAttributesRequest +{ + /** + * @var string + */ + private $store_in_vault; + /** + * @var string + */ + private $description; + /** + * @var string + */ + private $usage_pattern; + /** + * @var ShippingRequest + */ + private $shipping; + /** + * @var string + */ + private $usage_type = 'MERCHANT'; + /** + * @var string + */ + private $customer_type; + /** + * @var bool + */ + private $permit_multiple_payment_tokens; + + /** + * @return string + */ + public function getStoreInVault() + { + return $this->store_in_vault; + } + + /** + * @param string $store_in_vault + * + * @return void + */ + public function setStoreInVault($store_in_vault) + { + $this->store_in_vault = $store_in_vault; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $description + * + * @return void + */ + public function setDescription($description) + { + $this->description = $description; + } + + /** + * @return string + */ + public function getUsagePattern() + { + return $this->usage_pattern; + } + + /** + * @param string $usage_pattern + * + * @return void + */ + public function setUsagePattern($usage_pattern) + { + $this->usage_pattern = $usage_pattern; + } + + /** + * @return ShippingRequest + */ + public function getShipping() + { + return $this->shipping; + } + + /** + * @param ShippingRequest $shipping + * + * @return void + */ + public function setShipping(ShippingRequest $shipping) + { + $this->shipping = $shipping; + } + + /** + * @return string + */ + public function getUsageType() + { + return $this->usage_type; + } + + /** + * @param string $usage_type + * + * @return void + */ + public function setUsageType($usage_type) + { + $this->usage_type = $usage_type; + } + + /** + * @return string + */ + public function getCustomerType() + { + return $this->customer_type; + } + + /** + * @param string $customer_type + * + * @return void + */ + public function setCustomerType($customer_type) + { + $this->customer_type = $customer_type; + } + + /** + * @return bool + */ + public function isPermitMultiplePaymentTokens() + { + return $this->permit_multiple_payment_tokens; + } + + /** + * @param bool $permit_multiple_payment_tokens + * + * @return void + */ + public function setPermitMultiplePaymentTokens($permit_multiple_payment_tokens) + { + $this->permit_multiple_payment_tokens = $permit_multiple_payment_tokens; + } +} diff --git a/src/PayPal/Order/DTO/Payee.php b/src/PayPal/Order/DTO/Payee.php new file mode 100644 index 000000000..3276c8ad7 --- /dev/null +++ b/src/PayPal/Order/DTO/Payee.php @@ -0,0 +1,97 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Payee +{ + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email_address; + + /** + * The account identifier for a PayPal account. + * + * @var string|null + */ + protected $merchant_id; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->email_address = isset($data['email_address']) ? $data['email_address'] : null; + $this->merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : null; + } + + /** + * Gets email_address. + * + * @return string|null + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * Sets email_address. + * + * @param string|null $email_address The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmailAddress($email_address = null) + { + $this->email_address = $email_address; + + return $this; + } + + /** + * Gets merchant_id. + * + * @return string|null + */ + public function getMerchantId() + { + return $this->merchant_id; + } + + /** + * Sets merchant_id. + * + * @param string|null $merchant_id the account identifier for a PayPal account + * + * @return $this + */ + public function setMerchantId($merchant_id = null) + { + $this->merchant_id = $merchant_id; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PayeeRequest.php b/src/PayPal/Order/DTO/PayeeRequest.php new file mode 100644 index 000000000..b854f98aa --- /dev/null +++ b/src/PayPal/Order/DTO/PayeeRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PayeeRequest +{ + /** + * @var string + */ + private $email_address; + /** + * @var string + */ + private $merchant_id; + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return string + */ + public function getMerchantId() + { + return $this->merchant_id; + } + + /** + * @param string $merchant_id + * + * @return void + */ + public function setMerchantId($merchant_id) + { + $this->merchant_id = $merchant_id; + } +} diff --git a/src/PayPal/Order/DTO/Payer.php b/src/PayPal/Order/DTO/Payer.php new file mode 100644 index 000000000..9702a12b7 --- /dev/null +++ b/src/PayPal/Order/DTO/Payer.php @@ -0,0 +1,165 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Payer +{ + /** + * @var string + */ + private $email_address; + /** + * @var string + */ + private $payer_id; + /** + * @var Name + */ + private $name; + /** + * @var PhoneWithType + */ + private $phone; + /** + * @var string + */ + private $birth_date; + /** + * @var TaxInfo + */ + private $tax_info; + /** + * @var AddressRequest + */ + private $address; + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return string + */ + public function getPayerId() + { + return $this->payer_id; + } + + /** + * @param string $payer_id + */ + public function setPayerId($payer_id) + { + $this->payer_id = $payer_id; + } + + /** + * @return Name + */ + public function getName() + { + return $this->name; + } + + /** + * @param Name $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return PhoneWithType + */ + public function getPhone() + { + return $this->phone; + } + + /** + * @param PhoneWithType $phone + */ + public function setPhone($phone) + { + $this->phone = $phone; + } + + /** + * @return string + */ + public function getBirthDate() + { + return $this->birth_date; + } + + /** + * @param string $birth_date + */ + public function setBirthDate($birth_date) + { + $this->birth_date = $birth_date; + } + + /** + * @return TaxInfo + */ + public function getTaxInfo() + { + return $this->tax_info; + } + + /** + * @param TaxInfo $tax_info + */ + public function setTaxInfo($tax_info) + { + $this->tax_info = $tax_info; + } + + /** + * @return AddressRequest + */ + public function getAddress() + { + return $this->address; + } + + /** + * @param AddressRequest $address + */ + public function setAddress($address) + { + $this->address = $address; + } +} diff --git a/src/PayPal/Order/DTO/PaymentCollection.php b/src/PayPal/Order/DTO/PaymentCollection.php new file mode 100644 index 000000000..e3f84592c --- /dev/null +++ b/src/PayPal/Order/DTO/PaymentCollection.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaymentCollection +{ + /** + * An array of authorized payments for a purchase unit. A purchase unit can have zero or more authorized payments. + * + * @var AuthorizationWithAdditionalData[]|null + */ + protected $authorizations; + + /** + * An array of captured payments for a purchase unit. A purchase unit can have zero or more captured payments. + * + * @var Capture[]|null + */ + protected $captures; + + /** + * An array of refunds for a purchase unit. A purchase unit can have zero or more refunds. + * + * @var Refund[]|null + */ + protected $refunds; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->authorizations = isset($data['authorizations']) ? $data['authorizations'] : null; + $this->captures = isset($data['captures']) ? $data['captures'] : null; + $this->refunds = isset($data['refunds']) ? $data['refunds'] : null; + } + + /** + * Gets authorizations. + * + * @return AuthorizationWithAdditionalData[]|null + */ + public function getAuthorizations() + { + return $this->authorizations; + } + + /** + * Sets authorizations. + * + * @param AuthorizationWithAdditionalData[]|null $authorizations An array of authorized payments for a purchase unit. A purchase unit can have zero or more authorized payments. + * + * @return $this + */ + public function setAuthorizations(array $authorizations = null) + { + $this->authorizations = $authorizations; + + return $this; + } + + /** + * Gets captures. + * + * @return Capture[]|null + */ + public function getCaptures() + { + return $this->captures; + } + + /** + * Sets captures. + * + * @param Capture[]|null $captures An array of captured payments for a purchase unit. A purchase unit can have zero or more captured payments. + * + * @return $this + */ + public function setCaptures(array $captures = null) + { + $this->captures = $captures; + + return $this; + } + + /** + * Gets refunds. + * + * @return Refund[]|null + */ + public function getRefunds() + { + return $this->refunds; + } + + /** + * Sets refunds. + * + * @param Refund[]|null $refunds An array of refunds for a purchase unit. A purchase unit can have zero or more refunds. + * + * @return $this + */ + public function setRefunds(array $refunds = null) + { + $this->refunds = $refunds; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PaymentInstruction.php b/src/PayPal/Order/DTO/PaymentInstruction.php new file mode 100644 index 000000000..e6640a3c1 --- /dev/null +++ b/src/PayPal/Order/DTO/PaymentInstruction.php @@ -0,0 +1,159 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaymentInstruction +{ + /** + * An array of various fees, commissions, tips, or donations. This field is only applicable to merchants that been enabled for PayPal Commerce Platform for Marketplaces and Platforms capability. + * + * @var PlatformFee[]|null + */ + protected $platform_fees; + + /** + * @var string|null + */ + protected $disbursement_mode; + + /** + * This field is only enabled for selected merchants/partners to use and provides the ability to trigger a specific pricing rate/plan for a payment transaction. The list of eligible 'payee_pricing_tier_id' would be provided to you by your Account Manager. Specifying values other than the one provided to you by your account manager would result in an error. + * + * @var string|null + */ + protected $payee_pricing_tier_id; + + /** + * FX identifier generated returned by PayPal to be used for payment processing in order to honor FX rate (for eligible integrations) to be used when amount is settled/received into the payee account. + * + * @var string|null + */ + protected $payee_receivable_fx_rate_id; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->platform_fees = isset($data['platform_fees']) ? $data['platform_fees'] : null; + $this->disbursement_mode = isset($data['disbursement_mode']) ? $data['disbursement_mode'] : null; + $this->payee_pricing_tier_id = isset($data['payee_pricing_tier_id']) ? $data['payee_pricing_tier_id'] : null; + $this->payee_receivable_fx_rate_id = isset($data['payee_receivable_fx_rate_id']) ? $data['payee_receivable_fx_rate_id'] : null; + } + + /** + * Gets platform_fees. + * + * @return PlatformFee[]|null + */ + public function getPlatformFees() + { + return $this->platform_fees; + } + + /** + * Sets platform_fees. + * + * @param PlatformFee[]|null $platform_fees An array of various fees, commissions, tips, or donations. This field is only applicable to merchants that been enabled for PayPal Commerce Platform for Marketplaces and Platforms capability. + * + * @return $this + */ + public function setPlatformFees(array $platform_fees = null) + { + $this->platform_fees = $platform_fees; + + return $this; + } + + /** + * Gets disbursement_mode. + * + * @return string|null + */ + public function getDisbursementMode() + { + return $this->disbursement_mode; + } + + /** + * Sets disbursement_mode. + * + * @param string|null $disbursement_mode + * + * @return $this + */ + public function setDisbursementMode($disbursement_mode = null) + { + $this->disbursement_mode = $disbursement_mode; + + return $this; + } + + /** + * Gets payee_pricing_tier_id. + * + * @return string|null + */ + public function getPayeePricingTierId() + { + return $this->payee_pricing_tier_id; + } + + /** + * Sets payee_pricing_tier_id. + * + * @param string|null $payee_pricing_tier_id This field is only enabled for selected merchants/partners to use and provides the ability to trigger a specific pricing rate/plan for a payment transaction. The list of eligible 'payee_pricing_tier_id' would be provided to you by your Account Manager. Specifying values other than the one provided to you by your account manager would result in an error. + * + * @return $this + */ + public function setPayeePricingTierId($payee_pricing_tier_id = null) + { + $this->payee_pricing_tier_id = $payee_pricing_tier_id; + + return $this; + } + + /** + * Gets payee_receivable_fx_rate_id. + * + * @return string|null + */ + public function getPayeeReceivableFxRateId() + { + return $this->payee_receivable_fx_rate_id; + } + + /** + * Sets payee_receivable_fx_rate_id. + * + * @param string|null $payee_receivable_fx_rate_id FX identifier generated returned by PayPal to be used for payment processing in order to honor FX rate (for eligible integrations) to be used when amount is settled/received into the payee account + * + * @return $this + */ + public function setPayeeReceivableFxRateId($payee_receivable_fx_rate_id = null) + { + $this->payee_receivable_fx_rate_id = $payee_receivable_fx_rate_id; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PaymentSourceRequest.php b/src/PayPal/Order/DTO/PaymentSourceRequest.php new file mode 100644 index 000000000..691a6f444 --- /dev/null +++ b/src/PayPal/Order/DTO/PaymentSourceRequest.php @@ -0,0 +1,333 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaymentSourceRequest +{ + /** + * @var CardRequest + */ + private $card; + /** + * @var TokenRequest + */ + private $token; + /** + * @var PayPalRequest + */ + private $paypal; + /** + * @var BancontactRequest + */ + private $bancontact; + /** + * @var BlikRequest + */ + private $blik; + /** + * @var EpsRequest + */ + private $eps; + /** + * @var GiropayRequest + */ + private $giropay; + /** + * @var IdealRequest + */ + private $ideal; + /** + * @var MyBankRequest + */ + private $mybank; + /** + * @var P24Request + */ + private $p24; + /** + * @var SofortRequest + */ + private $sofort; + /** + * @var ApplePayRequest + */ + private $apple_pay; + /** + * @var GooglePayRequest + */ + private $google_pay; + /** + * @var VenmoRequest + */ + private $venmo; + + /** + * @return CardRequest + */ + public function getCard() + { + return $this->card; + } + + /** + * @param CardRequest $card + * + * @return void + */ + public function setCard(CardRequest $card) + { + $this->card = $card; + } + + /** + * @return TokenRequest + */ + public function getToken() + { + return $this->token; + } + + /** + * @param TokenRequest $token + * + * @return void + */ + public function setToken(TokenRequest $token) + { + $this->token = $token; + } + + /** + * @return PayPalRequest + */ + public function getPaypal() + { + return $this->paypal; + } + + /** + * @param PayPalRequest $paypal + * + * @return void + */ + public function setPaypal(PayPalRequest $paypal) + { + $this->paypal = $paypal; + } + + /** + * @return BancontactRequest + */ + public function getBancontact() + { + return $this->bancontact; + } + + /** + * @param BancontactRequest $bancontact + * + * @return void + */ + public function setBancontact(BancontactRequest $bancontact) + { + $this->bancontact = $bancontact; + } + + /** + * @return BlikRequest + */ + public function getBlik() + { + return $this->blik; + } + + /** + * @param BlikRequest $blik + * + * @return void + */ + public function setBlik(BlikRequest $blik) + { + $this->blik = $blik; + } + + /** + * @return EpsRequest + */ + public function getEps() + { + return $this->eps; + } + + /** + * @param EpsRequest $eps + * + * @return void + */ + public function setEps(EpsRequest $eps) + { + $this->eps = $eps; + } + + /** + * @return GiropayRequest + */ + public function getGiropay() + { + return $this->giropay; + } + + /** + * @param GiropayRequest $giropay + * + * @return void + */ + public function setGiropay(GiropayRequest $giropay) + { + $this->giropay = $giropay; + } + + /** + * @return IdealRequest + */ + public function getIdeal() + { + return $this->ideal; + } + + /** + * @param IdealRequest $ideal + * + * @return void + */ + public function setIdeal(IdealRequest $ideal) + { + $this->ideal = $ideal; + } + + /** + * @return MyBankRequest + */ + public function getMybank() + { + return $this->mybank; + } + + /** + * @param MyBankRequest $mybank + * + * @return void + */ + public function setMybank(MyBankRequest $mybank) + { + $this->mybank = $mybank; + } + + /** + * @return P24Request + */ + public function getP24() + { + return $this->p24; + } + + /** + * @param P24Request $p24 + * + * @return void + */ + public function setP24(P24Request $p24) + { + $this->p24 = $p24; + } + + /** + * @return SofortRequest + */ + public function getSofort() + { + return $this->sofort; + } + + /** + * @param SofortRequest $sofort + * + * @return void + */ + public function setSofort(SofortRequest $sofort) + { + $this->sofort = $sofort; + } + + /** + * @return ApplePayRequest + */ + public function getApplePay() + { + return $this->apple_pay; + } + + /** + * @param ApplePayRequest $apple_pay + * + * @return void + */ + public function setApplePay(ApplePayRequest $apple_pay) + { + $this->apple_pay = $apple_pay; + } + + /** + * @return GooglePayRequest + */ + public function getGooglePay() + { + return $this->google_pay; + } + + /** + * @param GooglePayRequest $google_pay + * + * @return void + */ + public function setGooglePay(GooglePayRequest $google_pay) + { + $this->google_pay = $google_pay; + } + + /** + * @return VenmoRequest + */ + public function getVenmo() + { + return $this->venmo; + } + + /** + * @param VenmoRequest $venmo + * + * @return void + */ + public function setVenmo(VenmoRequest $venmo) + { + $this->venmo = $venmo; + } +} diff --git a/src/PayPal/Order/DTO/PaymentSourceResponse.php b/src/PayPal/Order/DTO/PaymentSourceResponse.php new file mode 100644 index 000000000..b13dcbb6e --- /dev/null +++ b/src/PayPal/Order/DTO/PaymentSourceResponse.php @@ -0,0 +1,393 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaymentSourceResponse +{ + /** + * @var CardResponse|null + */ + protected $card; + + /** + * @var PaypalWalletResponse|null + */ + protected $paypal; + + /** + * @var Bancontact|null + */ + protected $bancontact; + + /** + * @var Blik|null + */ + protected $blik; + + /** + * @var Eps|null + */ + protected $eps; + + /** + * @var Giropay|null + */ + protected $giropay; + + /** + * @var Ideal|null + */ + protected $ideal; + + /** + * @var Mybank|null + */ + protected $mybank; + + /** + * @var P24|null + */ + protected $p24; + + /** + * @var Sofort|null + */ + protected $sofort; + + /** + * @var Trustly|null + */ + protected $trustly; + + /** + * @var VenmoWalletResponse|null + */ + protected $venmo; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->card = isset($data['card']) ? $data['card'] : null; + $this->paypal = isset($data['paypal']) ? $data['paypal'] : null; + $this->bancontact = isset($data['bancontact']) ? $data['bancontact'] : null; + $this->blik = isset($data['blik']) ? $data['blik'] : null; + $this->eps = isset($data['eps']) ? $data['eps'] : null; + $this->giropay = isset($data['giropay']) ? $data['giropay'] : null; + $this->ideal = isset($data['ideal']) ? $data['ideal'] : null; + $this->mybank = isset($data['mybank']) ? $data['mybank'] : null; + $this->p24 = isset($data['p24']) ? $data['p24'] : null; + $this->sofort = isset($data['sofort']) ? $data['sofort'] : null; + $this->trustly = isset($data['trustly']) ? $data['trustly'] : null; + $this->venmo = isset($data['venmo']) ? $data['venmo'] : null; + } + + /** + * Gets card. + * + * @return CardResponse|null + */ + public function getCard() + { + return $this->card; + } + + /** + * Sets card. + * + * @param CardResponse|null $card + * + * @return $this + */ + public function setCard(CardResponse $card = null) + { + $this->card = $card; + + return $this; + } + + /** + * Gets paypal. + * + * @return PaypalWalletResponse|null + */ + public function getPaypal() + { + return $this->paypal; + } + + /** + * Sets paypal. + * + * @param PaypalWalletResponse|null $paypal + * + * @return $this + */ + public function setPaypal(PaypalWalletResponse $paypal = null) + { + $this->paypal = $paypal; + + return $this; + } + + /** + * Gets bancontact. + * + * @return Bancontact|null + */ + public function getBancontact() + { + return $this->bancontact; + } + + /** + * Sets bancontact. + * + * @param Bancontact|null $bancontact + * + * @return $this + */ + public function setBancontact(Bancontact $bancontact = null) + { + $this->bancontact = $bancontact; + + return $this; + } + + /** + * Gets blik. + * + * @return Blik|null + */ + public function getBlik() + { + return $this->blik; + } + + /** + * Sets blik. + * + * @param Blik|null $blik + * + * @return $this + */ + public function setBlik(Blik $blik = null) + { + $this->blik = $blik; + + return $this; + } + + /** + * Gets eps. + * + * @return Eps|null + */ + public function getEps() + { + return $this->eps; + } + + /** + * Sets eps. + * + * @param Eps|null $eps + * + * @return $this + */ + public function setEps(Eps $eps = null) + { + $this->eps = $eps; + + return $this; + } + + /** + * Gets giropay. + * + * @return Giropay|null + */ + public function getGiropay() + { + return $this->giropay; + } + + /** + * Sets giropay. + * + * @param Giropay|null $giropay + * + * @return $this + */ + public function setGiropay(Giropay $giropay = null) + { + $this->giropay = $giropay; + + return $this; + } + + /** + * Gets ideal. + * + * @return Ideal|null + */ + public function getIdeal() + { + return $this->ideal; + } + + /** + * Sets ideal. + * + * @param Ideal|null $ideal + * + * @return $this + */ + public function setIdeal(Ideal $ideal = null) + { + $this->ideal = $ideal; + + return $this; + } + + /** + * Gets mybank. + * + * @return Mybank|null + */ + public function getMybank() + { + return $this->mybank; + } + + /** + * Sets mybank. + * + * @param Mybank|null $mybank + * + * @return $this + */ + public function setMybank(Mybank $mybank = null) + { + $this->mybank = $mybank; + + return $this; + } + + /** + * Gets p24. + * + * @return P24|null + */ + public function getP24() + { + return $this->p24; + } + + /** + * Sets p24. + * + * @param P24|null $p24 + * + * @return $this + */ + public function setP24(P24 $p24 = null) + { + $this->p24 = $p24; + + return $this; + } + + /** + * Gets sofort. + * + * @return Sofort|null + */ + public function getSofort() + { + return $this->sofort; + } + + /** + * Sets sofort. + * + * @param Sofort|null $sofort + * + * @return $this + */ + public function setSofort(Sofort $sofort = null) + { + $this->sofort = $sofort; + + return $this; + } + + /** + * Gets trustly. + * + * @return Trustly|null + */ + public function getTrustly() + { + return $this->trustly; + } + + /** + * Sets trustly. + * + * @param Trustly|null $trustly + * + * @return $this + */ + public function setTrustly(Trustly $trustly = null) + { + $this->trustly = $trustly; + + return $this; + } + + /** + * Gets venmo. + * + * @return VenmoWalletResponse|null + */ + public function getVenmo() + { + return $this->venmo; + } + + /** + * Sets venmo. + * + * @param VenmoWalletResponse|null $venmo + * + * @return $this + */ + public function setVenmo(VenmoWalletResponse $venmo = null) + { + $this->venmo = $venmo; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PaypalWalletAttributesResponse.php b/src/PayPal/Order/DTO/PaypalWalletAttributesResponse.php new file mode 100644 index 000000000..677cbe43a --- /dev/null +++ b/src/PayPal/Order/DTO/PaypalWalletAttributesResponse.php @@ -0,0 +1,94 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaypalWalletAttributesResponse +{ + /** + * @var VaultResponse|null + */ + protected $vault; + /** + * An array of merchant cobranded cards used by buyer to complete an order. This array will be present if a merchant has onboarded their cobranded card with PayPal and provided corresponding label(s). + * + * @var CobrandedCard[]|null + */ + protected $cobranded_cards; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->vault = isset($data['vault']) ? $data['vault'] : null; + $this->cobranded_cards = isset($data['cobranded_cards']) ? $data['cobranded_cards'] : null; + } + + /** + * Gets vault. + * + * @return VaultResponse|null + */ + public function getVault() + { + return $this->vault; + } + + /** + * Sets vault. + * + * @param VaultResponse|null $vault + * + * @return $this + */ + public function setVault(VaultResponse $vault = null) + { + $this->vault = $vault; + + return $this; + } + + /** + * Gets cobranded_cards. + * + * @return CobrandedCard[]|null + */ + public function getCobrandedCards() + { + return $this->cobranded_cards; + } + + /** + * Sets cobranded_cards. + * + * @param CobrandedCard[]|null $cobranded_cards An array of merchant cobranded cards used by buyer to complete an order. This array will be present if a merchant has onboarded their cobranded card with PayPal and provided corresponding label(s). + * + * @return $this + */ + public function setCobrandedCards(array $cobranded_cards = null) + { + $this->cobranded_cards = $cobranded_cards; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PaypalWalletResponse.php b/src/PayPal/Order/DTO/PaypalWalletResponse.php new file mode 100644 index 000000000..3db9cb634 --- /dev/null +++ b/src/PayPal/Order/DTO/PaypalWalletResponse.php @@ -0,0 +1,309 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PaypalWalletResponse +{ + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email_address; + + /** + * The PayPal payer ID, which is a masked version of the PayPal account number intended for use with third parties. The account number is reversibly encrypted and a proprietary variant of Base32 is used to encode the result. + * + * @var string|null + */ + protected $account_id; + + /** + * @var Name|null + */ + protected $name; + + /** + * @var string|null + */ + protected $phone_type; + + /** + * @var Phone|null + */ + protected $phone_number; + + /** + * The stand-alone date, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). To represent special legal values, such as a date of birth, you should use dates with no associated time or time-zone data. Whenever possible, use the standard `date_time` type. This regular expression does not validate all dates. For example, February 31 is valid and nothing is known about leap years. + * + * @var string|null + */ + protected $birth_date; + + /** + * @var TaxInfo|null + */ + protected $tax_info; + + /** + * @var AddressPortable2|null + */ + protected $address; + + /** + * @var PaypalWalletAttributesResponse|null + */ + protected $attributes; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->email_address = isset($data['email_address']) ? $data['email_address'] : null; + $this->account_id = isset($data['account_id']) ? $data['account_id'] : null; + $this->name = isset($data['name']) ? $data['name'] : null; + $this->phone_type = isset($data['phone_type']) ? $data['phone_type'] : null; + $this->phone_number = isset($data['phone_number']) ? $data['phone_number'] : null; + $this->birth_date = isset($data['birth_date']) ? $data['birth_date'] : null; + $this->tax_info = isset($data['tax_info']) ? $data['tax_info'] : null; + $this->address = isset($data['address']) ? $data['address'] : null; + $this->attributes = isset($data['attributes']) ? $data['attributes'] : null; + } + + /** + * Gets email_address. + * + * @return string|null + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * Sets email_address. + * + * @param string|null $email_address The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmailAddress($email_address = null) + { + $this->email_address = $email_address; + + return $this; + } + + /** + * Gets account_id. + * + * @return string|null + */ + public function getAccountId() + { + return $this->account_id; + } + + /** + * Sets account_id. + * + * @param string|null $account_id The PayPal payer ID, which is a masked version of the PayPal account number intended for use with third parties. The account number is reversibly encrypted and a proprietary variant of Base32 is used to encode the result. + * + * @return $this + */ + public function setAccountId($account_id = null) + { + $this->account_id = $account_id; + + return $this; + } + + /** + * Gets name. + * + * @return Name|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param Name|null $name + * + * @return $this + */ + public function setName(Name $name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets phone_type. + * + * @return string|null + */ + public function getPhoneType() + { + return $this->phone_type; + } + + /** + * Sets phone_type. + * + * @param string|null $phone_type + * + * @return $this + */ + public function setPhoneType($phone_type = null) + { + $this->phone_type = $phone_type; + + return $this; + } + + /** + * Gets phone_number. + * + * @return Phone|null + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * Sets phone_number. + * + * @param Phone|null $phone_number + * + * @return $this + */ + public function setPhoneNumber(Phone $phone_number = null) + { + $this->phone_number = $phone_number; + + return $this; + } + + /** + * Gets birth_date. + * + * @return string|null + */ + public function getBirthDate() + { + return $this->birth_date; + } + + /** + * Sets birth_date. + * + * @param string|null $birth_date The stand-alone date, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). To represent special legal values, such as a date of birth, you should use dates with no associated time or time-zone data. Whenever possible, use the standard `date_time` type. This regular expression does not validate all dates. For example, February 31 is valid and nothing is known about leap years. + * + * @return $this + */ + public function setBirthDate($birth_date = null) + { + $this->birth_date = $birth_date; + + return $this; + } + + /** + * Gets tax_info. + * + * @return TaxInfo|null + */ + public function getTaxInfo() + { + return $this->tax_info; + } + + /** + * Sets tax_info. + * + * @param TaxInfo|null $tax_info + * + * @return $this + */ + public function setTaxInfo(TaxInfo $tax_info = null) + { + $this->tax_info = $tax_info; + + return $this; + } + + /** + * Gets address. + * + * @return AddressPortable2|null + */ + public function getAddress() + { + return $this->address; + } + + /** + * Sets address. + * + * @param AddressPortable2|null $address + * + * @return $this + */ + public function setAddress(AddressPortable2 $address = null) + { + $this->address = $address; + + return $this; + } + + /** + * Gets attributes. + * + * @return PaypalWalletAttributesResponse|null + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Sets attributes. + * + * @param PaypalWalletAttributesResponse|null $attributes + * + * @return $this + */ + public function setAttributes(PaypalWalletAttributesResponse $attributes = null) + { + $this->attributes = $attributes; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Phone.php b/src/PayPal/Order/DTO/Phone.php new file mode 100644 index 000000000..c13e7d0e5 --- /dev/null +++ b/src/PayPal/Order/DTO/Phone.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Phone +{ + /** + * @var string + */ + private $country_code; + /** + * @var string + */ + private $national_number; + /** + * @var string + */ + private $extension_number; + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return string + */ + public function getNationalNumber() + { + return $this->national_number; + } + + /** + * @param string $national_number + * + * @return void + */ + public function setNationalNumber($national_number) + { + $this->national_number = $national_number; + } + + /** + * @return string + */ + public function getExtensionNumber() + { + return $this->extension_number; + } + + /** + * @param string $extension_number + * + * @return void + */ + public function setExtensionNumber($extension_number) + { + $this->extension_number = $extension_number; + } +} diff --git a/src/PayPal/Order/DTO/PhoneWithType.php b/src/PayPal/Order/DTO/PhoneWithType.php new file mode 100644 index 000000000..9049f0f32 --- /dev/null +++ b/src/PayPal/Order/DTO/PhoneWithType.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PhoneWithType +{ + /** + * @var Phone + */ + private $phone_number; + /** + * @var string + */ + private $phone_type; + + /** + * @return Phone + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * @param Phone $phone_number + * + * @return void + */ + public function setPhoneNumber(Phone $phone_number) + { + $this->phone_number = $phone_number; + } + + /** + * @return string + */ + public function getPhoneType() + { + return $this->phone_type; + } + + /** + * @param string $phone_type + * + * @return void + */ + public function setPhoneType($phone_type) + { + $this->phone_type = $phone_type; + } +} diff --git a/src/PayPal/Order/DTO/PlatformFee.php b/src/PayPal/Order/DTO/PlatformFee.php new file mode 100644 index 000000000..c01a43e98 --- /dev/null +++ b/src/PayPal/Order/DTO/PlatformFee.php @@ -0,0 +1,93 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PlatformFee +{ + /** + * @var Amount + */ + protected $amount; + + /** + * @var Payee|null + */ + protected $payee; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->amount = isset($data['amount']) ? $data['amount'] : null; + $this->payee = isset($data['payee']) ? $data['payee'] : null; + } + + /** + * Gets amount. + * + * @return Amount + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount $amount + * + * @return $this + */ + public function setAmount(Amount $amount) + { + $this->amount = $amount; + + return $this; + } + + /** + * Gets payee. + * + * @return Payee|null + */ + public function getPayee() + { + return $this->payee; + } + + /** + * Sets payee. + * + * @param Payee|null $payee + * + * @return $this + */ + public function setPayee(Payee $payee = null) + { + $this->payee = $payee; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PreviousNetworkTransactionReferenceRequest.php b/src/PayPal/Order/DTO/PreviousNetworkTransactionReferenceRequest.php new file mode 100644 index 000000000..4c72d9005 --- /dev/null +++ b/src/PayPal/Order/DTO/PreviousNetworkTransactionReferenceRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PreviousNetworkTransactionReferenceRequest +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $date; + /** + * @var string + */ + private $network; + /** + * @var string + */ + private $acquirer_reference_number; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getDate() + { + return $this->date; + } + + /** + * @param string $date + * + * @return void + */ + public function setDate($date) + { + $this->date = $date; + } + + /** + * @return string + */ + public function getNetwork() + { + return $this->network; + } + + /** + * @param string $network + * + * @return void + */ + public function setNetwork($network) + { + $this->network = $network; + } + + /** + * @return string + */ + public function getAcquirerReferenceNumber() + { + return $this->acquirer_reference_number; + } + + /** + * @param string $acquirer_reference_number + * + * @return void + */ + public function setAcquirerReferenceNumber($acquirer_reference_number) + { + $this->acquirer_reference_number = $acquirer_reference_number; + } +} diff --git a/src/PayPal/Order/DTO/ProcessorResponse.php b/src/PayPal/Order/DTO/ProcessorResponse.php new file mode 100644 index 000000000..e7393f0f1 --- /dev/null +++ b/src/PayPal/Order/DTO/ProcessorResponse.php @@ -0,0 +1,161 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ProcessorResponse +{ + /** + * The address verification code for Visa, Discover, Mastercard, or American Express transactions. + * + * @var string|null + */ + protected $avs_code; + + /** + * The card verification value code for for Visa, Discover, Mastercard, or American Express. + * + * @var string|null + */ + protected $cvv_code; + + /** + * Processor response code for the non-PayPal payment processor errors. + * + * @var string|null + */ + protected $response_code; + + /** + * The declined payment transactions might have payment advice codes. The card networks, like Visa and Mastercard, return payment advice codes. + * + * @var string|null + */ + protected $payment_advice_code; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->avs_code = isset($data['avs_code']) ? $data['avs_code'] : null; + $this->cvv_code = isset($data['cvv_code']) ? $data['cvv_code'] : null; + $this->response_code = isset($data['response_code']) ? $data['response_code'] : null; + $this->payment_advice_code = isset($data['payment_advice_code']) ? $data['payment_advice_code'] : null; + } + + /** + * Gets avs_code. + * + * @return string|null + */ + public function getAvsCode() + { + return $this->avs_code; + } + + /** + * Sets avs_code. + * + * @param string|null $avs_code the address verification code for Visa, Discover, Mastercard, or American Express transactions + * + * @return $this + */ + public function setAvsCode($avs_code = null) + { + $this->avs_code = $avs_code; + + return $this; + } + + /** + * Gets cvv_code. + * + * @return string|null + */ + public function getCvvCode() + { + return $this->cvv_code; + } + + /** + * Sets cvv_code. + * + * @param string|null $cvv_code the card verification value code for Visa, Discover, Mastercard, or American Express + * + * @return $this + */ + public function setCvvCode($cvv_code = null) + { + $this->cvv_code = $cvv_code; + + return $this; + } + + /** + * Gets response_code. + * + * @return string|null + */ + public function getResponseCode() + { + return $this->response_code; + } + + /** + * Sets response_code. + * + * @param string|null $response_code processor response code for the non-PayPal payment processor errors + * + * @return $this + */ + public function setResponseCode($response_code = null) + { + $this->response_code = $response_code; + + return $this; + } + + /** + * Gets payment_advice_code. + * + * @return string|null + */ + public function getPaymentAdviceCode() + { + return $this->payment_advice_code; + } + + /** + * Sets payment_advice_code. + * + * @param string|null $payment_advice_code The declined payment transactions might have payment advice codes. The card networks, like Visa and Mastercard, return payment advice codes. + * + * @return $this + */ + public function setPaymentAdviceCode($payment_advice_code = null) + { + $this->payment_advice_code = $payment_advice_code; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PurchaseUnit.php b/src/PayPal/Order/DTO/PurchaseUnit.php new file mode 100644 index 000000000..211f215ae --- /dev/null +++ b/src/PayPal/Order/DTO/PurchaseUnit.php @@ -0,0 +1,444 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +/** + * Class representing the PurchaseUnit model. + * + * The purchase unit details. Used to capture required information for the payment contract. + * + * @author OpenAPI Generator team + */ +class PurchaseUnit +{ + /** + * The API caller-provided external ID for the purchase unit. Required for multiple purchase units when you must update the order through `PATCH`. If you omit this value and the order contains only one purchase unit, PayPal sets this value to `default`. <blockquote><strong>Note:</strong> If there are multiple purchase units, <code>reference_id</code> is required for each purchase unit.</blockquote> + * + * @var string|null + */ + protected $reference_id; + + /** + * @var AmountWithBreakdown|null + */ + protected $amount; + + /** + * @var Payee|null + */ + protected $payee; + + /** + * @var PaymentInstruction|null + */ + protected $payment_instruction; + + /** + * The purchase description. + * + * @var string|null + */ + protected $description; + + /** + * The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @var string|null + */ + protected $custom_id; + + /** + * The API caller-provided external invoice ID for this order. + * + * @var string|null + */ + protected $invoice_id; + + /** + * The PayPal-generated ID for the purchase unit. This ID appears in both the payer's transaction history and the emails that the payer receives. In addition, this ID is available in transaction and settlement reports that merchants and API callers can use to reconcile transactions. This ID is only available when an order is saved by calling <code>v2/checkout/orders/id/save</code>. + * + * @var string|null + */ + protected $id; + + /** + * The payment descriptor on account transactions on the customer's credit card statement, that PayPal sends to processors. The maximum length of the soft descriptor information that you can pass in the API field is 22 characters, in the following format:<code>22 - len(PAYPAL * (8)) - len(<var>Descriptor in Payment Receiving Preferences of Merchant account</var> + 1)</code>The PAYPAL prefix uses 8 characters.<br/><br/>The soft descriptor supports the following ASCII characters:<ul><li>Alphanumeric characters</li><li>Dashes</li><li>Asterisks</li><li>Periods (.)</li><li>Spaces</li></ul>For Wallet payments marketplace integrations:<ul><li>The merchant descriptor in the Payment Receiving Preferences must be the marketplace name.</li><li>You can't use the remaining space to show the customer service number.</li><li>The remaining spaces can be a combination of seller name and country.</li></ul><br/>For unbranded payments (Direct Card) marketplace integrations, use a combination of the seller name and phone number. + * + * @var string|null + */ + protected $soft_descriptor; + + /** + * An array of items that the customer purchases from the merchant. + * + * @var Item[]|null + */ + protected $items; + + /** + * @var ShippingWithTrackingDetails|null + */ + protected $shipping; + + /** + * @var SupplementaryData|null + */ + protected $supplementary_data; + + /** + * @var PaymentCollection|null + */ + protected $payments; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->reference_id = isset($data['reference_id']) ? $data['reference_id'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + $this->payee = isset($data['payee']) ? $data['payee'] : null; + $this->payment_instruction = isset($data['payment_instruction']) ? $data['payment_instruction'] : null; + $this->description = isset($data['description']) ? $data['description'] : null; + $this->custom_id = isset($data['custom_id']) ? $data['custom_id'] : null; + $this->invoice_id = isset($data['invoice_id']) ? $data['invoice_id'] : null; + $this->id = isset($data['id']) ? $data['id'] : null; + $this->soft_descriptor = isset($data['soft_descriptor']) ? $data['soft_descriptor'] : null; + $this->items = isset($data['items']) ? $data['items'] : null; + $this->shipping = isset($data['shipping']) ? $data['shipping'] : null; + $this->supplementary_data = isset($data['supplementary_data']) ? $data['supplementary_data'] : null; + $this->payments = isset($data['payments']) ? $data['payments'] : null; + } + + /** + * Gets reference_id. + * + * @return string|null + */ + public function getReferenceId() + { + return $this->reference_id; + } + + /** + * Sets reference_id. + * + * @param string|null $reference_id The API caller-provided external ID for the purchase unit. Required for multiple purchase units when you must update the order through `PATCH`. If you omit this value and the order contains only one purchase unit, PayPal sets this value to `default`.
Note: If there are multiple purchase units, reference_id is required for each purchase unit.
+ * + * @return $this + */ + public function setReferenceId($reference_id = null) + { + $this->reference_id = $reference_id; + + return $this; + } + + /** + * Gets amount. + * + * @return AmountWithBreakdown|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param AmountWithBreakdown|null $amount + * + * @return $this + */ + public function setAmount(AmountWithBreakdown $amount = null) + { + $this->amount = $amount; + + return $this; + } + + /** + * Gets payee. + * + * @return Payee|null + */ + public function getPayee() + { + return $this->payee; + } + + /** + * Sets payee. + * + * @param Payee|null $payee + * + * @return $this + */ + public function setPayee(Payee $payee = null) + { + $this->payee = $payee; + + return $this; + } + + /** + * Gets payment_instruction. + * + * @return PaymentInstruction|null + */ + public function getPaymentInstruction() + { + return $this->payment_instruction; + } + + /** + * Sets payment_instruction. + * + * @param PaymentInstruction|null $payment_instruction + * + * @return $this + */ + public function setPaymentInstruction(PaymentInstruction $payment_instruction = null) + { + $this->payment_instruction = $payment_instruction; + + return $this; + } + + /** + * Gets description. + * + * @return string|null + */ + public function getDescription() + { + return $this->description; + } + + /** + * Sets description. + * + * @param string|null $description the purchase description + * + * @return $this + */ + public function setDescription($description = null) + { + $this->description = $description; + + return $this; + } + + /** + * Gets custom_id. + * + * @return string|null + */ + public function getCustomId() + { + return $this->custom_id; + } + + /** + * Sets custom_id. + * + * @param string|null $custom_id The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @return $this + */ + public function setCustomId($custom_id = null) + { + $this->custom_id = $custom_id; + + return $this; + } + + /** + * Gets invoice_id. + * + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * Sets invoice_id. + * + * @param string|null $invoice_id the API caller-provided external invoice ID for this order + * + * @return $this + */ + public function setInvoiceId($invoice_id = null) + { + $this->invoice_id = $invoice_id; + + return $this; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id The PayPal-generated ID for the purchase unit. This ID appears in both the payer's transaction history and the emails that the payer receives. In addition, this ID is available in transaction and settlement reports that merchants and API callers can use to reconcile transactions. This ID is only available when an order is saved by calling v2/checkout/orders/id/save. + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets soft_descriptor. + * + * @return string|null + */ + public function getSoftDescriptor() + { + return $this->soft_descriptor; + } + + /** + * Sets soft_descriptor. + * + * @param string|null $soft_descriptor The payment descriptor on account transactions on the customer's credit card statement, that PayPal sends to processors. The maximum length of the soft descriptor information that you can pass in the API field is 22 characters, in the following format:22 - len(PAYPAL * (8)) - len(Descriptor in Payment Receiving Preferences of Merchant account + 1)The PAYPAL prefix uses 8 characters.

The soft descriptor supports the following ASCII characters:
  • Alphanumeric characters
  • Dashes
  • Asterisks
  • Periods (.)
  • Spaces
For Wallet payments marketplace integrations:
  • The merchant descriptor in the Payment Receiving Preferences must be the marketplace name.
  • You can't use the remaining space to show the customer service number.
  • The remaining spaces can be a combination of seller name and country.

For unbranded payments (Direct Card) marketplace integrations, use a combination of the seller name and phone number. + * + * @return $this + */ + public function setSoftDescriptor($soft_descriptor = null) + { + $this->soft_descriptor = $soft_descriptor; + + return $this; + } + + /** + * Gets items. + * + * @return Item[]|null + */ + public function getItems() + { + return $this->items; + } + + /** + * Sets items. + * + * @param Item[]|null $items an array of items that the customer purchases from the merchant + * + * @return $this + */ + public function setItems(array $items = null) + { + $this->items = $items; + + return $this; + } + + /** + * Gets shipping. + * + * @return ShippingWithTrackingDetails|null + */ + public function getShipping() + { + return $this->shipping; + } + + /** + * Sets shipping. + * + * @param ShippingWithTrackingDetails|null $shipping + * + * @return $this + */ + public function setShipping(ShippingWithTrackingDetails $shipping = null) + { + $this->shipping = $shipping; + + return $this; + } + + /** + * Gets supplementary_data. + * + * @return SupplementaryData|null + */ + public function getSupplementaryData() + { + return $this->supplementary_data; + } + + /** + * Sets supplementary_data. + * + * @param SupplementaryData|null $supplementary_data + * + * @return $this + */ + public function setSupplementaryData(SupplementaryData $supplementary_data = null) + { + $this->supplementary_data = $supplementary_data; + + return $this; + } + + /** + * Gets payments. + * + * @return PaymentCollection|null + */ + public function getPayments() + { + return $this->payments; + } + + /** + * Sets payments. + * + * @param PaymentCollection|null $payments + * + * @return $this + */ + public function setPayments(PaymentCollection $payments = null) + { + $this->payments = $payments; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/PurchaseUnitRequest.php b/src/PayPal/Order/DTO/PurchaseUnitRequest.php new file mode 100644 index 000000000..e8ce815a9 --- /dev/null +++ b/src/PayPal/Order/DTO/PurchaseUnitRequest.php @@ -0,0 +1,245 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class PurchaseUnitRequest +{ + /** + * @var string + */ + private $reference_id; + /** + * @var AmountWithBreakdown + */ + private $amount; + /** + * @var PayeeRequest + */ + private $payee; + /** + * @var string + */ + private $description; + /** + * @var string + */ + private $custom_id; + /** + * @var string + */ + private $invoice_id; + /** + * @var string + */ + private $soft_descriptor; + /** + * @var ItemRequest[] + */ + private $items; + /** + * @var ShippingRequest + */ + private $shipping; + /** + * @var SupplementaryDataRequest + */ + private $supplementary_data; + + /** + * @return string + */ + public function getReferenceId() + { + return $this->reference_id; + } + + /** + * @param string $reference_id + * + * @return void + */ + public function setReferenceId($reference_id) + { + $this->reference_id = $reference_id; + } + + /** + * @return AmountWithBreakdown + */ + public function getAmount() + { + return $this->amount; + } + + /** + * @param AmountWithBreakdown $amount + * + * @return void + */ + public function setAmount(AmountWithBreakdown $amount) + { + $this->amount = $amount; + } + + /** + * @return PayeeRequest + */ + public function getPayee() + { + return $this->payee; + } + + /** + * @param PayeeRequest $payee + * + * @return void + */ + public function setPayee(PayeeRequest $payee) + { + $this->payee = $payee; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $description + * + * @return void + */ + public function setDescription($description) + { + $this->description = $description; + } + + /** + * @return string + */ + public function getCustomId() + { + return $this->custom_id; + } + + /** + * @param string $custom_id + * + * @return void + */ + public function setCustomId($custom_id) + { + $this->custom_id = $custom_id; + } + + /** + * @return string + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * @param string $invoice_id + * + * @return void + */ + public function setInvoiceId($invoice_id) + { + $this->invoice_id = $invoice_id; + } + + /** + * @return string + */ + public function getSoftDescriptor() + { + return $this->soft_descriptor; + } + + /** + * @param string $soft_descriptor + * + * @return void + */ + public function setSoftDescriptor($soft_descriptor) + { + $this->soft_descriptor = $soft_descriptor; + } + + /** + * @return ItemRequest[] + */ + public function getItems() + { + return $this->items; + } + + /** + * @param ItemRequest[] $items + * + * @return void + */ + public function setItems(array $items) + { + $this->items = $items; + } + + /** + * @return ShippingRequest + */ + public function getShipping() + { + return $this->shipping; + } + + /** + * @param ShippingRequest $shipping + * + * @return void + */ + public function setShipping(ShippingRequest $shipping) + { + $this->shipping = $shipping; + } + + /** + * @return SupplementaryDataRequest + */ + public function getSupplementaryData() + { + return $this->supplementary_data; + } + + /** + * @param SupplementaryDataRequest $supplementary_data + * + * @return void + */ + public function setSupplementaryData(SupplementaryDataRequest $supplementary_data) + { + $this->supplementary_data = $supplementary_data; + } +} diff --git a/src/PayPal/Order/DTO/Reason.php b/src/PayPal/Order/DTO/Reason.php new file mode 100644 index 000000000..80bf798fe --- /dev/null +++ b/src/PayPal/Order/DTO/Reason.php @@ -0,0 +1,65 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Reason +{ + /** + * The reason why the captured payment status is `PENDING` or `DENIED`. + * + * @var string|null + */ + protected $reason; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->reason = isset($data['reason']) ? $data['reason'] : null; + } + + /** + * Gets reason. + * + * @return string|null + */ + public function getReason() + { + return $this->reason; + } + + /** + * Sets reason. + * + * @param string|null $reason the reason why the captured payment status is `PENDING` or `DENIED` + * + * @return $this + */ + public function setReason($reason = null) + { + $this->reason = $reason; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Refund.php b/src/PayPal/Order/DTO/Refund.php new file mode 100644 index 000000000..dc0f6bffe --- /dev/null +++ b/src/PayPal/Order/DTO/Refund.php @@ -0,0 +1,441 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Refund +{ + /** + * The status of the refund. + * + * @var string|null + */ + protected $status; + + /** + * @var Reason|null + */ + protected $status_details; + + /** + * The PayPal-generated ID for the refund. + * + * @var string|null + */ + protected $id; + + /** + * @var Amount|null + */ + protected $amount; + + /** + * The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @var string|null + */ + protected $invoice_id; + + /** + * The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @var string|null + */ + protected $custom_id; + + /** + * Reference ID issued for the card transaction. This ID can be used to track the transaction across processors, card brands and issuing banks. + * + * @var string|null + */ + protected $acquirer_reference_number; + + /** + * The reason for the refund. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @var string|null + */ + protected $note_to_payer; + + /** + * @var MerchantPayableBreakdown|null + */ + protected $seller_payable_breakdown; + + /** + * @var Payee|null + */ + protected $payer; + + /** + * An array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links). + * + * @var LinkDescription[]|null + */ + protected $links; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $create_time; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $update_time; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->status = isset($data['status']) ? $data['status'] : null; + $this->status_details = isset($data['status_details']) ? $data['status_details'] : null; + $this->id = isset($data['id']) ? $data['id'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + $this->invoice_id = isset($data['invoice_id']) ? $data['invoice_id'] : null; + $this->custom_id = isset($data['custom_id']) ? $data['custom_id'] : null; + $this->acquirer_reference_number = isset($data['acquirer_reference_number']) ? $data['acquirer_reference_number'] : null; + $this->note_to_payer = isset($data['note_to_payer']) ? $data['note_to_payer'] : null; + $this->seller_payable_breakdown = isset($data['seller_payable_breakdown']) ? $data['seller_payable_breakdown'] : null; + $this->payer = isset($data['payer']) ? $data['payer'] : null; + $this->links = isset($data['links']) ? $data['links'] : null; + $this->create_time = isset($data['create_time']) ? $data['create_time'] : null; + $this->update_time = isset($data['update_time']) ? $data['update_time'] : null; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status the status of the refund + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets status_details. + * + * @return Reason|null + */ + public function getStatusDetails() + { + return $this->status_details; + } + + /** + * Sets status_details. + * + * @param Reason|null $status_details + * + * @return $this + */ + public function setStatusDetails(Reason $status_details = null) + { + $this->status_details = $status_details; + + return $this; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the PayPal-generated ID for the refund + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets amount. + * + * @return Amount|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount|null $amount + * + * @return $this + */ + public function setAmount(Amount $amount = null) + { + $this->amount = $amount; + + return $this; + } + + /** + * Gets invoice_id. + * + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoice_id; + } + + /** + * Sets invoice_id. + * + * @param string|null $invoice_id The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @return $this + */ + public function setInvoiceId($invoice_id = null) + { + $this->invoice_id = $invoice_id; + + return $this; + } + + /** + * Gets custom_id. + * + * @return string|null + */ + public function getCustomId() + { + return $this->custom_id; + } + + /** + * Sets custom_id. + * + * @param string|null $custom_id The API caller-provided external ID. Used to reconcile API caller-initiated transactions with PayPal transactions. Appears in transaction and settlement reports. + * + * @return $this + */ + public function setCustomId($custom_id = null) + { + $this->custom_id = $custom_id; + + return $this; + } + + /** + * Gets acquirer_reference_number. + * + * @return string|null + */ + public function getAcquirerReferenceNumber() + { + return $this->acquirer_reference_number; + } + + /** + * Sets acquirer_reference_number. + * + * @param string|null $acquirer_reference_number Reference ID issued for the card transaction. This ID can be used to track the transaction across processors, card brands and issuing banks. + * + * @return $this + */ + public function setAcquirerReferenceNumber($acquirer_reference_number = null) + { + $this->acquirer_reference_number = $acquirer_reference_number; + + return $this; + } + + /** + * Gets note_to_payer. + * + * @return string|null + */ + public function getNoteToPayer() + { + return $this->note_to_payer; + } + + /** + * Sets note_to_payer. + * + * @param string|null $note_to_payer The reason for the refund. Appears in both the payer's transaction history and the emails that the payer receives. + * + * @return $this + */ + public function setNoteToPayer($note_to_payer = null) + { + $this->note_to_payer = $note_to_payer; + + return $this; + } + + /** + * Gets seller_payable_breakdown. + * + * @return MerchantPayableBreakdown|null + */ + public function getSellerPayableBreakdown() + { + return $this->seller_payable_breakdown; + } + + /** + * Sets seller_payable_breakdown. + * + * @param MerchantPayableBreakdown|null $seller_payable_breakdown + * + * @return $this + */ + public function setSellerPayableBreakdown(MerchantPayableBreakdown $seller_payable_breakdown = null) + { + $this->seller_payable_breakdown = $seller_payable_breakdown; + + return $this; + } + + /** + * Gets payer. + * + * @return Payee|null + */ + public function getPayer() + { + return $this->payer; + } + + /** + * Sets payer. + * + * @param Payee|null $payer + * + * @return $this + */ + public function setPayer(Payee $payer = null) + { + $this->payer = $payer; + + return $this; + } + + /** + * Gets links. + * + * @return LinkDescription[]|null + */ + public function getLinks() + { + return $this->links; + } + + /** + * Sets links. + * + * @param LinkDescription[]|null $links an array of related [HATEOAS links](/docs/api/reference/api-responses/#hateoas-links) + * + * @return $this + */ + public function setLinks(array $links = null) + { + $this->links = $links; + + return $this; + } + + /** + * Gets create_time. + * + * @return string|null + */ + public function getCreateTime() + { + return $this->create_time; + } + + /** + * Sets create_time. + * + * @param string|null $create_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setCreateTime($create_time = null) + { + $this->create_time = $create_time; + + return $this; + } + + /** + * Gets update_time. + * + * @return string|null + */ + public function getUpdateTime() + { + return $this->update_time; + } + + /** + * Sets update_time. + * + * @param string|null $update_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setUpdateTime($update_time = null) + { + $this->update_time = $update_time; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/SellerProtection.php b/src/PayPal/Order/DTO/SellerProtection.php new file mode 100644 index 000000000..5b8b6f2b7 --- /dev/null +++ b/src/PayPal/Order/DTO/SellerProtection.php @@ -0,0 +1,97 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class SellerProtection +{ + /** + * Indicates whether the transaction is eligible for seller protection. For information, see [PayPal Seller Protection for Merchants](https://www.paypal.com/us/webapps/mpp/security/seller-protection). + * + * @var string|null + */ + protected $status; + + /** + * An array of conditions that are covered for the transaction. + * + * @var string[]|null + */ + protected $dispute_categories; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->status = isset($data['status']) ? $data['status'] : null; + $this->dispute_categories = isset($data['dispute_categories']) ? $data['dispute_categories'] : null; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status Indicates whether the transaction is eligible for seller protection. For information, see [PayPal Seller Protection for Merchants](https://www.paypal.com/us/webapps/mpp/security/seller-protection). + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets dispute_categories. + * + * @return string[]|null + */ + public function getDisputeCategories() + { + return $this->dispute_categories; + } + + /** + * Sets dispute_categories. + * + * @param string[]|null $dispute_categories an array of conditions that are covered for the transaction + * + * @return $this + */ + public function setDisputeCategories(array $dispute_categories = null) + { + $this->dispute_categories = $dispute_categories; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/SellerReceivableBreakdown.php b/src/PayPal/Order/DTO/SellerReceivableBreakdown.php new file mode 100644 index 000000000..4b231a41d --- /dev/null +++ b/src/PayPal/Order/DTO/SellerReceivableBreakdown.php @@ -0,0 +1,245 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class SellerReceivableBreakdown +{ + /** + * @var Amount + */ + protected $gross_amount; + + /** + * @var Amount|null + */ + protected $paypal_fee; + + /** + * @var Amount|null + */ + protected $paypal_fee_in_receivable_currency; + + /** + * @var Amount|null + */ + protected $net_amount; + + /** + * @var Amount|null + */ + protected $receivable_amount; + + /** + * @var ExchangeRate|null + */ + protected $exchange_rate; + + /** + * An array of platform or partner fees, commissions, or brokerage fees that associated with the captured payment. + * + * @var PlatformFee[]|null + */ + protected $platform_fees; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->gross_amount = isset($data['gross_amount']) ? $data['gross_amount'] : null; + $this->paypal_fee = isset($data['paypal_fee']) ? $data['paypal_fee'] : null; + $this->paypal_fee_in_receivable_currency = isset($data['paypal_fee_in_receivable_currency']) ? $data['paypal_fee_in_receivable_currency'] : null; + $this->net_amount = isset($data['net_amount']) ? $data['net_amount'] : null; + $this->receivable_amount = isset($data['receivable_amount']) ? $data['receivable_amount'] : null; + $this->exchange_rate = isset($data['exchange_rate']) ? $data['exchange_rate'] : null; + $this->platform_fees = isset($data['platform_fees']) ? $data['platform_fees'] : null; + } + + /** + * Gets gross_amount. + * + * @return Amount + */ + public function getGrossAmount() + { + return $this->gross_amount; + } + + /** + * Sets gross_amount. + * + * @param Amount $gross_amount + * + * @return $this + */ + public function setGrossAmount(Amount $gross_amount) + { + $this->gross_amount = $gross_amount; + + return $this; + } + + /** + * Gets paypal_fee. + * + * @return Amount|null + */ + public function getPaypalFee() + { + return $this->paypal_fee; + } + + /** + * Sets paypal_fee. + * + * @param Amount|null $paypal_fee + * + * @return $this + */ + public function setPaypalFee(Amount $paypal_fee = null) + { + $this->paypal_fee = $paypal_fee; + + return $this; + } + + /** + * Gets paypal_fee_in_receivable_currency. + * + * @return Amount|null + */ + public function getPaypalFeeInReceivableCurrency() + { + return $this->paypal_fee_in_receivable_currency; + } + + /** + * Sets paypal_fee_in_receivable_currency. + * + * @param Amount|null $paypal_fee_in_receivable_currency + * + * @return $this + */ + public function setPaypalFeeInReceivableCurrency(Amount $paypal_fee_in_receivable_currency = null) + { + $this->paypal_fee_in_receivable_currency = $paypal_fee_in_receivable_currency; + + return $this; + } + + /** + * Gets net_amount. + * + * @return Amount|null + */ + public function getNetAmount() + { + return $this->net_amount; + } + + /** + * Sets net_amount. + * + * @param Amount|null $net_amount + * + * @return $this + */ + public function setNetAmount(Amount $net_amount = null) + { + $this->net_amount = $net_amount; + + return $this; + } + + /** + * Gets receivable_amount. + * + * @return Amount|null + */ + public function getReceivableAmount() + { + return $this->receivable_amount; + } + + /** + * Sets receivable_amount. + * + * @param Amount|null $receivable_amount + * + * @return $this + */ + public function setReceivableAmount(Amount $receivable_amount = null) + { + $this->receivable_amount = $receivable_amount; + + return $this; + } + + /** + * Gets exchange_rate. + * + * @return ExchangeRate|null + */ + public function getExchangeRate() + { + return $this->exchange_rate; + } + + /** + * Sets exchange_rate. + * + * @param ExchangeRate|null $exchange_rate + * + * @return $this + */ + public function setExchangeRate(ExchangeRate $exchange_rate = null) + { + $this->exchange_rate = $exchange_rate; + + return $this; + } + + /** + * Gets platform_fees. + * + * @return PlatformFee[]|null + */ + public function getPlatformFees() + { + return $this->platform_fees; + } + + /** + * Sets platform_fees. + * + * @param PlatformFee[]|null $platform_fees an array of platform or partner fees, commissions, or brokerage fees that associated with the captured payment + * + * @return $this + */ + public function setPlatformFees(array $platform_fees = null) + { + $this->platform_fees = $platform_fees; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/ShippingOption.php b/src/PayPal/Order/DTO/ShippingOption.php new file mode 100644 index 000000000..0b0f18bc0 --- /dev/null +++ b/src/PayPal/Order/DTO/ShippingOption.php @@ -0,0 +1,189 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ShippingOption +{ + /** + * A unique ID that identifies a payer-selected shipping option. + * + * @var string + */ + protected $id; + + /** + * A description that the payer sees, which helps them choose an appropriate shipping option. For example, `Free Shipping`, `USPS Priority Shipping`, `Expédition prioritaire USPS`, or `USPS yōuxiān fā huò`. Localize this description to the payer's locale. + * + * @var string + */ + protected $label; + + /** + * If the API request sets `selected = true`, it represents the shipping option that the payee or merchant expects to be pre-selected for the payer when they first view the `shipping.options` in the PayPal Checkout experience. As part of the response if a `shipping.option` contains `selected=true`, it represents the shipping option that the payer selected during the course of checkout with PayPal. Only one `shipping.option` can be set to `selected=true`. + * + * @var bool + */ + protected $selected; + + /** + * @var string|null + */ + protected $type; + + /** + * @var Amount|null + */ + protected $amount; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->label = isset($data['label']) ? $data['label'] : null; + $this->selected = isset($data['selected']) ? $data['selected'] : null; + $this->type = isset($data['type']) ? $data['type'] : null; + $this->amount = isset($data['amount']) ? $data['amount'] : null; + } + + /** + * Gets id. + * + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string $id a unique ID that identifies a payer-selected shipping option + * + * @return $this + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * Gets label. + * + * @return string + */ + public function getLabel() + { + return $this->label; + } + + /** + * Sets label. + * + * @param string $label A description that the payer sees, which helps them choose an appropriate shipping option. For example, `Free Shipping`, `USPS Priority Shipping`, `Expédition prioritaire USPS`, or `USPS yōuxiān fā huò`. Localize this description to the payer's locale. + * + * @return $this + */ + public function setLabel($label) + { + $this->label = $label; + + return $this; + } + + /** + * Gets selected. + * + * @return bool + */ + public function isSelected() + { + return $this->selected; + } + + /** + * Sets selected. + * + * @param bool $selected If the API request sets `selected = true`, it represents the shipping option that the payee or merchant expects to be pre-selected for the payer when they first view the `shipping.options` in the PayPal Checkout experience. As part of the response if a `shipping.option` contains `selected=true`, it represents the shipping option that the payer selected during the course of checkout with PayPal. Only one `shipping.option` can be set to `selected=true`. + * + * @return $this + */ + public function setSelected($selected) + { + $this->selected = $selected; + + return $this; + } + + /** + * Gets type. + * + * @return string|null + */ + public function getType() + { + return $this->type; + } + + /** + * Sets type. + * + * @param string|null $type + * + * @return $this + */ + public function setType($type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Gets amount. + * + * @return Amount|null + */ + public function getAmount() + { + return $this->amount; + } + + /** + * Sets amount. + * + * @param Amount|null $amount + * + * @return $this + */ + public function setAmount(Amount $amount = null) + { + $this->amount = $amount; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/ShippingOptionRequest.php b/src/PayPal/Order/DTO/ShippingOptionRequest.php new file mode 100644 index 000000000..ca15231e8 --- /dev/null +++ b/src/PayPal/Order/DTO/ShippingOptionRequest.php @@ -0,0 +1,135 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ShippingOptionRequest +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $label; + /** + * @var string + */ + private $type; + /** + * @var Amount + */ + private $amount; + /** + * @var bool + */ + private $selected; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getLabel() + { + return $this->label; + } + + /** + * @param string $label + * + * @return void + */ + public function setLabel($label) + { + $this->label = $label; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * + * @return void + */ + public function setType($type) + { + $this->type = $type; + } + + /** + * @return Amount + */ + public function getAmount() + { + return $this->amount; + } + + /** + * @param Amount $amount + * + * @return void + */ + public function setAmount(Amount $amount) + { + $this->amount = $amount; + } + + /** + * @return bool + */ + public function isSelected() + { + return $this->selected; + } + + /** + * @param bool $selected + * + * @return void + */ + public function setSelected($selected) + { + $this->selected = $selected; + } +} diff --git a/src/PayPal/Order/DTO/ShippingRequest.php b/src/PayPal/Order/DTO/ShippingRequest.php new file mode 100644 index 000000000..92061c8e5 --- /dev/null +++ b/src/PayPal/Order/DTO/ShippingRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ShippingRequest +{ + /** + * @var Name + */ + private $name; + /** + * @var string + */ + private $type; + /** + * @var ShippingOptionRequest[] + */ + private $options; + /** + * @var AddressRequest + */ + private $address; + + /** + * @return Name + */ + public function getName() + { + return $this->name; + } + + /** + * @param Name $name + * + * @return void + */ + public function setName(Name $name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * + * @return void + */ + public function setType($type) + { + $this->type = $type; + } + + /** + * @return ShippingOptionRequest[] + */ + public function getOptions() + { + return $this->options; + } + + /** + * @param ShippingOptionRequest[] $options + * + * @return void + */ + public function setOptions(array $options) + { + $this->options = $options; + } + + /** + * @return AddressRequest + */ + public function getAddress() + { + return $this->address; + } + + /** + * @param AddressRequest $address + * + * @return void + */ + public function setAddress(AddressRequest $address) + { + $this->address = $address; + } +} diff --git a/src/PayPal/Order/DTO/ShippingWithTrackingDetails.php b/src/PayPal/Order/DTO/ShippingWithTrackingDetails.php new file mode 100644 index 000000000..e854871fe --- /dev/null +++ b/src/PayPal/Order/DTO/ShippingWithTrackingDetails.php @@ -0,0 +1,189 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ShippingWithTrackingDetails +{ + /** + * @var Name|null + */ + protected $name; + + /** + * The method by which the payer wants to get their items from the payee e.g shipping, in-person pickup. Either type or options but not both may be present. + * + * @var string|null + */ + protected $type; + + /** + * An array of shipping options that the payee or merchant offers to the payer to ship or pick up their items. + * + * @var ShippingOption[]|null + */ + protected $options; + + /** + * @var AddressRequest|null + */ + protected $address; + + /** + * An array of trackers for a transaction. + * + * @var Tracker[]|null + */ + protected $trackers; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->type = isset($data['type']) ? $data['type'] : null; + $this->options = isset($data['options']) ? $data['options'] : null; + $this->address = isset($data['address']) ? $data['address'] : null; + $this->trackers = isset($data['trackers']) ? $data['trackers'] : null; + } + + /** + * Gets name. + * + * @return Name|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param Name|null $name + * + * @return $this + */ + public function setName(Name $name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets type. + * + * @return string|null + */ + public function getType() + { + return $this->type; + } + + /** + * Sets type. + * + * @param string|null $type The method by which the payer wants to get their items from the payee e.g shipping, in-person pickup. Either type or options but not both may be present. + * + * @return $this + */ + public function setType($type = null) + { + $this->type = $type; + + return $this; + } + + /** + * Gets options. + * + * @return ShippingOption[]|null + */ + public function getOptions() + { + return $this->options; + } + + /** + * Sets options. + * + * @param ShippingOption[]|null $options an array of shipping options that the payee or merchant offers to the payer to ship or pick up their items + * + * @return $this + */ + public function setOptions(array $options = null) + { + $this->options = $options; + + return $this; + } + + /** + * Gets address. + * + * @return AddressRequest|null + */ + public function getAddress() + { + return $this->address; + } + + /** + * Sets address. + * + * @param AddressRequest|null $address + * + * @return $this + */ + public function setAddress(AddressRequest $address = null) + { + $this->address = $address; + + return $this; + } + + /** + * Gets trackers. + * + * @return Tracker[]|null + */ + public function getTrackers() + { + return $this->trackers; + } + + /** + * Sets trackers. + * + * @param Tracker[]|null $trackers an array of trackers for a transaction + * + * @return $this + */ + public function setTrackers(array $trackers = null) + { + $this->trackers = $trackers; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Sofort.php b/src/PayPal/Order/DTO/Sofort.php new file mode 100644 index 000000000..253f13dbc --- /dev/null +++ b/src/PayPal/Order/DTO/Sofort.php @@ -0,0 +1,161 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Sofort +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * The last characters of the IBAN used to pay. + * + * @var string|null + */ + protected $iban_last_chars; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + $this->iban_last_chars = isset($data['iban_last_chars']) ? $data['iban_last_chars'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } + + /** + * Gets iban_last_chars. + * + * @return string|null + */ + public function getIbanLastChars() + { + return $this->iban_last_chars; + } + + /** + * Sets iban_last_chars. + * + * @param string|null $iban_last_chars the last characters of the IBAN used to pay + * + * @return $this + */ + public function setIbanLastChars($iban_last_chars = null) + { + $this->iban_last_chars = $iban_last_chars; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/SofortRequest.php b/src/PayPal/Order/DTO/SofortRequest.php new file mode 100644 index 000000000..b2bf26508 --- /dev/null +++ b/src/PayPal/Order/DTO/SofortRequest.php @@ -0,0 +1,91 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class SofortRequest +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $country_code; + /** + * @var ExperienceContextRequest + */ + private $experience_context; + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + * + * @return void + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * @param string $country_code + * + * @return void + */ + public function setCountryCode($country_code) + { + $this->country_code = $country_code; + } + + /** + * @return ExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param ExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(ExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } +} diff --git a/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php b/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php new file mode 100644 index 000000000..c194d77eb --- /dev/null +++ b/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class StoredPaymentSourceRequest +{ + /** + * @var string + */ + private $payment_initiator; + /** + * @var string + */ + private $payment_type; + /** + * @var string + */ + private $usage; + /** + * @var PreviousNetworkTransactionReferenceRequest + */ + private $previous_network_transaction_reference; + + /** + * @return string + */ + public function getPaymentInitiator() + { + return $this->payment_initiator; + } + + /** + * @param string $payment_initiator + * + * @return void + */ + public function setPaymentInitiator($payment_initiator) + { + $this->payment_initiator = $payment_initiator; + } + + /** + * @return string + */ + public function getPaymentType() + { + return $this->payment_type; + } + + /** + * @param string $payment_type + * + * @return void + */ + public function setPaymentType($payment_type) + { + $this->payment_type = $payment_type; + } + + /** + * @return string + */ + public function getUsage() + { + return $this->usage; + } + + /** + * @param string $usage + * + * @return void + */ + public function setUsage($usage) + { + $this->usage = $usage; + } + + /** + * @return PreviousNetworkTransactionReferenceRequest + */ + public function getPreviousNetworkTransactionReference() + { + return $this->previous_network_transaction_reference; + } + + /** + * @param PreviousNetworkTransactionReferenceRequest $previous_network_transaction_reference + * + * @return void + */ + public function setPreviousNetworkTransactionReference(PreviousNetworkTransactionReferenceRequest $previous_network_transaction_reference) + { + $this->previous_network_transaction_reference = $previous_network_transaction_reference; + } +} diff --git a/src/PayPal/Order/DTO/SupplementaryData.php b/src/PayPal/Order/DTO/SupplementaryData.php new file mode 100644 index 000000000..a1122f49f --- /dev/null +++ b/src/PayPal/Order/DTO/SupplementaryData.php @@ -0,0 +1,63 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class SupplementaryData +{ + /** + * @var CardSupplementaryData|null + */ + protected $card; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->card = isset($data['card']) ? $data['card'] : null; + } + + /** + * Gets card. + * + * @return CardSupplementaryData|null + */ + public function getCard() + { + return $this->card; + } + + /** + * Sets card. + * + * @param CardSupplementaryData|null $card + * + * @return $this + */ + public function setCard(CardSupplementaryData $card = null) + { + $this->card = $card; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/SupplementaryDataRequest.php b/src/PayPal/Order/DTO/SupplementaryDataRequest.php new file mode 100644 index 000000000..5e848be5a --- /dev/null +++ b/src/PayPal/Order/DTO/SupplementaryDataRequest.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class SupplementaryDataRequest +{ + /** + * @var CardSupplementaryDataRequest + */ + private $card; + + /** + * @return CardSupplementaryDataRequest + */ + public function getCard() + { + return $this->card; + } + + /** + * @param CardSupplementaryDataRequest $card + * + * @return void + */ + public function setCard(CardSupplementaryDataRequest $card) + { + $this->card = $card; + } +} diff --git a/src/PayPal/Order/DTO/TaxInfo.php b/src/PayPal/Order/DTO/TaxInfo.php new file mode 100644 index 000000000..63547ecb5 --- /dev/null +++ b/src/PayPal/Order/DTO/TaxInfo.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class TaxInfo +{ + /** + * @var string + */ + private $tax_id; + /** + * @var string + */ + private $tax_id_type; + + /** + * @return string + */ + public function getTaxId() + { + return $this->tax_id; + } + + /** + * @param string $tax_id + * + * @return void + */ + public function setTaxId($tax_id) + { + $this->tax_id = $tax_id; + } + + /** + * @return string + */ + public function getTaxIdType() + { + return $this->tax_id_type; + } + + /** + * @param string $tax_id_type + * + * @return void + */ + public function setTaxIdType($tax_id_type) + { + $this->tax_id_type = $tax_id_type; + } +} diff --git a/src/PayPal/Order/DTO/ThreeDSecureAuthenticationResponse.php b/src/PayPal/Order/DTO/ThreeDSecureAuthenticationResponse.php new file mode 100644 index 000000000..05ccb3d5d --- /dev/null +++ b/src/PayPal/Order/DTO/ThreeDSecureAuthenticationResponse.php @@ -0,0 +1,93 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class ThreeDSecureAuthenticationResponse +{ + /** + * @var string|null + */ + protected $authentication_status; + + /** + * @var string|null + */ + protected $enrollment_status; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->authentication_status = isset($data['authentication_status']) ? $data['authentication_status'] : null; + $this->enrollment_status = isset($data['enrollment_status']) ? $data['enrollment_status'] : null; + } + + /** + * Gets authentication_status. + * + * @return string|null + */ + public function getAuthenticationStatus() + { + return $this->authentication_status; + } + + /** + * Sets authentication_status. + * + * @param string|null $authentication_status + * + * @return $this + */ + public function setAuthenticationStatus($authentication_status = null) + { + $this->authentication_status = $authentication_status; + + return $this; + } + + /** + * Gets enrollment_status. + * + * @return string|null + */ + public function getEnrollmentStatus() + { + return $this->enrollment_status; + } + + /** + * Sets enrollment_status. + * + * @param string|null $enrollment_status + * + * @return $this + */ + public function setEnrollmentStatus($enrollment_status = null) + { + $this->enrollment_status = $enrollment_status; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/TokenRequest.php b/src/PayPal/Order/DTO/TokenRequest.php new file mode 100644 index 000000000..3fd7c13c6 --- /dev/null +++ b/src/PayPal/Order/DTO/TokenRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class TokenRequest +{ + /** + * @var string + */ + private $id; + /** + * @var string + */ + private $type; + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * + * @return void + */ + public function setType($type) + { + $this->type = $type; + } +} diff --git a/src/PayPal/Order/DTO/Tracker.php b/src/PayPal/Order/DTO/Tracker.php new file mode 100644 index 000000000..3261332d4 --- /dev/null +++ b/src/PayPal/Order/DTO/Tracker.php @@ -0,0 +1,223 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Tracker +{ + /** + * The tracker id. + * + * @var string|null + */ + protected $id; + + /** + * @var mixed|null + */ + protected $status; + + /** + * An array of details of items in the shipment. + * + * @var TrackerItem[]|null + */ + protected $items; + + /** + * An array of request-related HATEOAS links. + * + * @var LinkDescription[]|null + */ + protected $links; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $create_time; + + /** + * The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.<blockquote><strong>Note:</strong> The regular expression provides guidance but does not reject all invalid dates.</blockquote> + * + * @var string|null + */ + protected $update_time; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->status = isset($data['status']) ? $data['status'] : null; + $this->items = isset($data['items']) ? $data['items'] : null; + $this->links = isset($data['links']) ? $data['links'] : null; + $this->create_time = isset($data['create_time']) ? $data['create_time'] : null; + $this->update_time = isset($data['update_time']) ? $data['update_time'] : null; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the tracker id + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets status. + * + * @return mixed|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param mixed|null $status + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets items. + * + * @return TrackerItem[]|null + */ + public function getItems() + { + return $this->items; + } + + /** + * Sets items. + * + * @param TrackerItem[]|null $items an array of details of items in the shipment + * + * @return $this + */ + public function setItems(array $items = null) + { + $this->items = $items; + + return $this; + } + + /** + * Gets links. + * + * @return LinkDescription[]|null + */ + public function getLinks() + { + return $this->links; + } + + /** + * Sets links. + * + * @param LinkDescription[]|null $links an array of request-related HATEOAS links + * + * @return $this + */ + public function setLinks(array $links = null) + { + $this->links = $links; + + return $this; + } + + /** + * Gets create_time. + * + * @return string|null + */ + public function getCreateTime() + { + return $this->create_time; + } + + /** + * Sets create_time. + * + * @param string|null $create_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setCreateTime($create_time = null) + { + $this->create_time = $create_time; + + return $this; + } + + /** + * Gets update_time. + * + * @return string|null + */ + public function getUpdateTime() + { + return $this->update_time; + } + + /** + * Sets update_time. + * + * @param string|null $update_time The date and time, in [Internet date and time format](https://tools.ietf.org/html/rfc3339#section-5.6). Seconds are required while fractional seconds are optional.
Note: The regular expression provides guidance but does not reject all invalid dates.
+ * + * @return $this + */ + public function setUpdateTime($update_time = null) + { + $this->update_time = $update_time; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/TrackerItem.php b/src/PayPal/Order/DTO/TrackerItem.php new file mode 100644 index 000000000..67165d4a7 --- /dev/null +++ b/src/PayPal/Order/DTO/TrackerItem.php @@ -0,0 +1,187 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class TrackerItem +{ + /** + * The item name or title. + * + * @var string|null + */ + protected $name; + /** + * The item quantity. Must be a whole number. + * + * @var string|null + */ + protected $quantity; + /** + * The stock keeping unit (SKU) for the item. This can contain unicode characters. + * + * @var string|null + */ + protected $sku; + /** + * The URL of the item's image. File type and size restrictions apply. An image that violates these restrictions will not be honored. + * + * @var string|null + */ + protected $image_url; + /** + * @var mixed|null + */ + protected $upc; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->quantity = isset($data['quantity']) ? $data['quantity'] : null; + $this->sku = isset($data['sku']) ? $data['sku'] : null; + $this->image_url = isset($data['image_url']) ? $data['image_url'] : null; + $this->upc = isset($data['upc']) ? $data['upc'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the item name or title + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets quantity. + * + * @return string|null + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * Sets quantity. + * + * @param string|null $quantity The item quantity. Must be a whole number. + * + * @return $this + */ + public function setQuantity($quantity = null) + { + $this->quantity = $quantity; + + return $this; + } + + /** + * Gets sku. + * + * @return string|null + */ + public function getSku() + { + return $this->sku; + } + + /** + * Sets sku. + * + * @param string|null $sku The stock keeping unit (SKU) for the item. This can contain unicode characters. + * + * @return $this + */ + public function setSku($sku = null) + { + $this->sku = $sku; + + return $this; + } + + /** + * Gets image_url. + * + * @return string|null + */ + public function getImageUrl() + { + return $this->image_url; + } + + /** + * Sets image_url. + * + * @param string|null $image_url The URL of the item's image. File type and size restrictions apply. An image that violates these restrictions will not be honored. + * + * @return $this + */ + public function setImageUrl($image_url = null) + { + $this->image_url = $image_url; + + return $this; + } + + /** + * Gets upc. + * + * @return mixed|null + */ + public function getUpc() + { + return $this->upc; + } + + /** + * Sets upc. + * + * @param mixed|null $upc + * + * @return $this + */ + public function setUpc($upc = null) + { + $this->upc = $upc; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/Trustly.php b/src/PayPal/Order/DTO/Trustly.php new file mode 100644 index 000000000..07dc6d00e --- /dev/null +++ b/src/PayPal/Order/DTO/Trustly.php @@ -0,0 +1,161 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class Trustly +{ + /** + * The full name representation like Mr J Smith. + * + * @var string|null + */ + protected $name; + + /** + * The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.<blockquote><strong>Note:</strong> The country code for Great Britain is <code>GB</code> and not <code>UK</code> as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.</blockquote> + * + * @var string|null + */ + protected $country_code; + + /** + * The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @var string|null + */ + protected $bic; + + /** + * The last characters of the IBAN used to pay. + * + * @var string|null + */ + protected $iban_last_chars; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->name = isset($data['name']) ? $data['name'] : null; + $this->country_code = isset($data['country_code']) ? $data['country_code'] : null; + $this->bic = isset($data['bic']) ? $data['bic'] : null; + $this->iban_last_chars = isset($data['iban_last_chars']) ? $data['iban_last_chars'] : null; + } + + /** + * Gets name. + * + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param string|null $name the full name representation like Mr J Smith + * + * @return $this + */ + public function setName($name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets country_code. + * + * @return string|null + */ + public function getCountryCode() + { + return $this->country_code; + } + + /** + * Sets country_code. + * + * @param string|null $country_code The [two-character ISO 3166-1 code](/api/rest/reference/country-codes/) that identifies the country or region.
Note: The country code for Great Britain is GB and not UK as used in the top-level domain names for that country. Use the `C2` country code for China worldwide for comparable uncontrolled price (CUP) method, bank card, and cross-border transactions.
+ * + * @return $this + */ + public function setCountryCode($country_code = null) + { + $this->country_code = $country_code; + + return $this; + } + + /** + * Gets bic. + * + * @return string|null + */ + public function getBic() + { + return $this->bic; + } + + /** + * Sets bic. + * + * @param string|null $bic The business identification code (BIC). In payments systems, a BIC is used to identify a specific business, most commonly a bank. + * + * @return $this + */ + public function setBic($bic = null) + { + $this->bic = $bic; + + return $this; + } + + /** + * Gets iban_last_chars. + * + * @return string|null + */ + public function getIbanLastChars() + { + return $this->iban_last_chars; + } + + /** + * Sets iban_last_chars. + * + * @param string|null $iban_last_chars the last characters of the IBAN used to pay + * + * @return $this + */ + public function setIbanLastChars($iban_last_chars = null) + { + $this->iban_last_chars = $iban_last_chars; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/VaultAttributesRequest.php b/src/PayPal/Order/DTO/VaultAttributesRequest.php new file mode 100644 index 000000000..4e201217f --- /dev/null +++ b/src/PayPal/Order/DTO/VaultAttributesRequest.php @@ -0,0 +1,47 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VaultAttributesRequest +{ + /** + * @var string + */ + public $store_in_vault; + + /** + * @return string + */ + public function getStoreInVault() + { + return $this->store_in_vault; + } + + /** + * @param string $store_in_vault + * + * @return void + */ + public function setStoreInVault($store_in_vault) + { + $this->store_in_vault = $store_in_vault; + } +} diff --git a/src/PayPal/Order/DTO/VaultResponse.php b/src/PayPal/Order/DTO/VaultResponse.php new file mode 100644 index 000000000..7432a4d41 --- /dev/null +++ b/src/PayPal/Order/DTO/VaultResponse.php @@ -0,0 +1,159 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VaultResponse +{ + /** + * The PayPal-generated ID for the saved payment source. + * + * @var string|null + */ + protected $id; + + /** + * The vault status. + * + * @var string|null + */ + protected $status; + + /** + * @var Customer|null + */ + protected $customer; + + /** + * An array of request-related HATEOAS links. + * + * @var LinkDescription[]|null + */ + protected $links; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->id = isset($data['id']) ? $data['id'] : null; + $this->status = isset($data['status']) ? $data['status'] : null; + $this->customer = isset($data['customer']) ? $data['customer'] : null; + $this->links = isset($data['links']) ? $data['links'] : null; + } + + /** + * Gets id. + * + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * Sets id. + * + * @param string|null $id the PayPal-generated ID for the saved payment source + * + * @return $this + */ + public function setId($id = null) + { + $this->id = $id; + + return $this; + } + + /** + * Gets status. + * + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * Sets status. + * + * @param string|null $status the vault status + * + * @return $this + */ + public function setStatus($status = null) + { + $this->status = $status; + + return $this; + } + + /** + * Gets customer. + * + * @return Customer|null + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * Sets customer. + * + * @param Customer|null $customer + * + * @return $this + */ + public function setCustomer(Customer $customer = null) + { + $this->customer = $customer; + + return $this; + } + + /** + * Gets links. + * + * @return LinkDescription[]|null + */ + public function getLinks() + { + return $this->links; + } + + /** + * Sets links. + * + * @param LinkDescription[]|null $links an array of request-related HATEOAS links + * + * @return $this + */ + public function setLinks(array $links = null) + { + $this->links = $links; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/VenmoExperienceContextRequest.php b/src/PayPal/Order/DTO/VenmoExperienceContextRequest.php new file mode 100644 index 000000000..d68da7fde --- /dev/null +++ b/src/PayPal/Order/DTO/VenmoExperienceContextRequest.php @@ -0,0 +1,69 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VenmoExperienceContextRequest +{ + /** + * @var string + */ + private $brand_name; + /** + * @var string + */ + private $shipping_preference; + + /** + * @return string + */ + public function getBrandName() + { + return $this->brand_name; + } + + /** + * @param string $brand_name + * + * @return void + */ + public function setBrandName($brand_name) + { + $this->brand_name = $brand_name; + } + + /** + * @return string + */ + public function getShippingPreference() + { + return $this->shipping_preference; + } + + /** + * @param string $shipping_preference + * + * @return void + */ + public function setShippingPreference($shipping_preference) + { + $this->shipping_preference = $shipping_preference; + } +} diff --git a/src/PayPal/Order/DTO/VenmoRequest.php b/src/PayPal/Order/DTO/VenmoRequest.php new file mode 100644 index 000000000..7976829da --- /dev/null +++ b/src/PayPal/Order/DTO/VenmoRequest.php @@ -0,0 +1,113 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VenmoRequest +{ + /** + * @var string + */ + private $vault_id; + /** + * @var string + */ + private $email_address; + /** + * @var VenmoExperienceContextRequest + */ + private $experience_context; + /** + * @var PayPalWalletAttributesRequest + */ + private $attributes; + + /** + * @return string + */ + public function getVaultId() + { + return $this->vault_id; + } + + /** + * @param string $vault_id + * + * @return void + */ + public function setVaultId($vault_id) + { + $this->vault_id = $vault_id; + } + + /** + * @return string + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * @param string $email_address + * + * @return void + */ + public function setEmailAddress($email_address) + { + $this->email_address = $email_address; + } + + /** + * @return VenmoExperienceContextRequest + */ + public function getExperienceContext() + { + return $this->experience_context; + } + + /** + * @param VenmoExperienceContextRequest $experience_context + * + * @return void + */ + public function setExperienceContext(VenmoExperienceContextRequest $experience_context) + { + $this->experience_context = $experience_context; + } + + /** + * @return PayPalWalletAttributesRequest + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * @param PayPalWalletAttributesRequest $attributes + * + * @return void + */ + public function setAttributes(PayPalWalletAttributesRequest $attributes) + { + $this->attributes = $attributes; + } +} diff --git a/src/PayPal/Order/DTO/VenmoWalletAttributesResponse.php b/src/PayPal/Order/DTO/VenmoWalletAttributesResponse.php new file mode 100644 index 000000000..95f106e6f --- /dev/null +++ b/src/PayPal/Order/DTO/VenmoWalletAttributesResponse.php @@ -0,0 +1,63 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VenmoWalletAttributesResponse +{ + /** + * @var VaultResponse|null + */ + protected $vault; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->vault = isset($data['vault']) ? $data['vault'] : null; + } + + /** + * Gets vault. + * + * @return VaultResponse|null + */ + public function getVault() + { + return $this->vault; + } + + /** + * Sets vault. + * + * @param VaultResponse|null $vault + * + * @return $this + */ + public function setVault(VaultResponse $vault = null) + { + $this->vault = $vault; + + return $this; + } +} diff --git a/src/PayPal/Order/DTO/VenmoWalletResponse.php b/src/PayPal/Order/DTO/VenmoWalletResponse.php new file mode 100644 index 000000000..27eafa2cf --- /dev/null +++ b/src/PayPal/Order/DTO/VenmoWalletResponse.php @@ -0,0 +1,249 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; + +class VenmoWalletResponse +{ + /** + * The internationalized email address.<blockquote><strong>Note:</strong> Up to 64 characters are allowed before and 255 characters are allowed after the <code>@</code> sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted <code>@</code> sign exists.</blockquote> + * + * @var string|null + */ + protected $email_address; + + /** + * The PayPal payer ID, which is a masked version of the PayPal account number intended for use with third parties. The account number is reversibly encrypted and a proprietary variant of Base32 is used to encode the result. + * + * @var string|null + */ + protected $account_id; + + /** + * The Venmo user name chosen by the user, also know as a Venmo handle. + * + * @var string|null + */ + protected $user_name; + + /** + * @var Name|null + */ + protected $name; + + /** + * @var Phone|null + */ + protected $phone_number; + + /** + * @var AddressPortable2|null + */ + protected $address; + + /** + * @var VenmoWalletAttributesResponse|null + */ + protected $attributes; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->email_address = isset($data['email_address']) ? $data['email_address'] : null; + $this->account_id = isset($data['account_id']) ? $data['account_id'] : null; + $this->user_name = isset($data['user_name']) ? $data['user_name'] : null; + $this->name = isset($data['name']) ? $data['name'] : null; + $this->phone_number = isset($data['phone_number']) ? $data['phone_number'] : null; + $this->address = isset($data['address']) ? $data['address'] : null; + $this->attributes = isset($data['attributes']) ? $data['attributes'] : null; + } + + /** + * Gets email_address. + * + * @return string|null + */ + public function getEmailAddress() + { + return $this->email_address; + } + + /** + * Sets email_address. + * + * @param string|null $email_address The internationalized email address.
Note: Up to 64 characters are allowed before and 255 characters are allowed after the @ sign. However, the generally accepted maximum length for an email address is 254 characters. The pattern verifies that an unquoted @ sign exists.
+ * + * @return $this + */ + public function setEmailAddress($email_address = null) + { + $this->email_address = $email_address; + + return $this; + } + + /** + * Gets account_id. + * + * @return string|null + */ + public function getAccountId() + { + return $this->account_id; + } + + /** + * Sets account_id. + * + * @param string|null $account_id The PayPal payer ID, which is a masked version of the PayPal account number intended for use with third parties. The account number is reversibly encrypted and a proprietary variant of Base32 is used to encode the result. + * + * @return $this + */ + public function setAccountId($account_id = null) + { + $this->account_id = $account_id; + + return $this; + } + + /** + * Gets user_name. + * + * @return string|null + */ + public function getUserName() + { + return $this->user_name; + } + + /** + * Sets user_name. + * + * @param string|null $user_name the Venmo user name chosen by the user, also know as a Venmo handle + * + * @return $this + */ + public function setUserName($user_name = null) + { + $this->user_name = $user_name; + + return $this; + } + + /** + * Gets name. + * + * @return Name|null + */ + public function getName() + { + return $this->name; + } + + /** + * Sets name. + * + * @param Name|null $name + * + * @return $this + */ + public function setName(Name $name = null) + { + $this->name = $name; + + return $this; + } + + /** + * Gets phone_number. + * + * @return Phone|null + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * Sets phone_number. + * + * @param Phone|null $phone_number + * + * @return $this + */ + public function setPhoneNumber(Phone $phone_number = null) + { + $this->phone_number = $phone_number; + + return $this; + } + + /** + * Gets address. + * + * @return AddressPortable2|null + */ + public function getAddress() + { + return $this->address; + } + + /** + * Sets address. + * + * @param AddressPortable2|null $address + * + * @return $this + */ + public function setAddress(AddressPortable2 $address = null) + { + $this->address = $address; + + return $this; + } + + /** + * Gets attributes. + * + * @return VenmoWalletAttributesResponse|null + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Sets attributes. + * + * @param VenmoWalletAttributesResponse|null $attributes + * + * @return $this + */ + public function setAttributes(VenmoWalletAttributesResponse $attributes = null) + { + $this->attributes = $attributes; + + return $this; + } +} diff --git a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php index a4d5328c7..475a9b452 100644 --- a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php +++ b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php @@ -83,6 +83,10 @@ class PayPalOrderEventSubscriber implements EventSubscriberInterface * @var CommandBusInterface */ private $commandBus; + /** + * @var PayPalConfiguration + */ + private $payPalConfiguration; public function __construct( Ps_checkout $module, @@ -90,7 +94,8 @@ public function __construct( CacheInterface $orderPayPalCache, CheckoutChecker $checkoutChecker, CheckTransitionPayPalOrderStatusService $checkTransitionPayPalOrderStatusService, - OrderStateMapper $orderStateMapper + OrderStateMapper $orderStateMapper, + PayPalConfiguration $payPalConfiguration ) { $this->module = $module; $this->psCheckoutCartRepository = $psCheckoutCartRepository; @@ -99,6 +104,7 @@ public function __construct( $this->checkTransitionPayPalOrderStatusService = $checkTransitionPayPalOrderStatusService; $this->orderStateMapper = $orderStateMapper; $this->commandBus = $this->module->getService('ps_checkout.bus.command'); + $this->payPalConfiguration = $payPalConfiguration; } /** @@ -133,8 +139,6 @@ public static function getSubscribedEvents() public function saveCreatedPayPalOrder(PayPalOrderCreatedEvent $event) { - /** @var PayPalConfiguration $configuration */ - $configuration = $this->module->getService('ps_checkout.paypal.configuration'); $order = $event->getOrderPayPal(); $this->commandBus->handle(new SaveCheckoutCommand( @@ -145,7 +149,7 @@ public function saveCreatedPayPalOrder(PayPalOrderCreatedEvent $event) $event->getFundingSource(), $event->isExpressCheckout(), $event->isHostedFields(), - $configuration->getPaymentMode() + $this->payPalConfiguration->getPaymentMode() )); } diff --git a/src/PayPal/Order/PayPalOrderHttpClientInterface.php b/src/PayPal/Order/PayPalOrderHttpClientInterface.php new file mode 100644 index 000000000..17393d94d --- /dev/null +++ b/src/PayPal/Order/PayPalOrderHttpClientInterface.php @@ -0,0 +1,37 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order; + +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderResponse; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Exception\PayPalOrderException; + +interface PayPalOrderHttpClientInterface +{ + /** + * @param CreatePayPalOrderRequest $payload + * + * @return CreatePayPalOrderResponse + * + * @throws PayPalOrderException + */ + public function createOrder(CreatePayPalOrderRequest $payload); +} diff --git a/src/PayPal/Order/Query/GetPayPalOrderQuery.php b/src/PayPal/Order/Query/GetPayPalOrderQuery.php new file mode 100644 index 000000000..7e8ec33f0 --- /dev/null +++ b/src/PayPal/Order/Query/GetPayPalOrderQuery.php @@ -0,0 +1,59 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query; + +use PrestaShop\Module\PrestashopCheckout\Cart\ValueObject\CartId; +use PrestaShop\PrestaShop\Core\Domain\Order\ValueObject\OrderId; + +class GetPayPalOrderQuery +{ + /** + * @var OrderId|null + */ + private $orderId; + /** + * @var CartId|null + */ + private $cartId; + + public function __construct(OrderId $orderId = null, CartId $cartId = null) + { + $this->orderId = $orderId; + $this->cartId = $cartId; + } + + /** + * @return OrderId + */ + public function getOrderId() + { + return $this->orderId; + } + + /** + * @return CartId|null + */ + public function getCartId() + { + return $this->cartId; + } +} diff --git a/src/PayPal/Order/Query/GetPayPalOrderQueryResult.php b/src/PayPal/Order/Query/GetPayPalOrderQueryResult.php new file mode 100644 index 000000000..5c59f4f07 --- /dev/null +++ b/src/PayPal/Order/Query/GetPayPalOrderQueryResult.php @@ -0,0 +1,46 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query; + +class GetPayPalOrderQueryResult +{ + /** + * @var array + */ + private $order; + + /** + * @param array{id: string, status: string, intent: string, payment_source: array, purchase_units: array, payer: array, create_time: string, links: array} $order + */ + public function __construct($order) + { + $this->order = $order; + } + + /** + * @return array + */ + public function getOrder() + { + return $this->order; + } +} diff --git a/src/PayPal/Order/QueryHandler/GetPayPalOrderQueryHandler.php b/src/PayPal/Order/QueryHandler/GetPayPalOrderQueryHandler.php new file mode 100644 index 000000000..2b1df02a4 --- /dev/null +++ b/src/PayPal/Order/QueryHandler/GetPayPalOrderQueryHandler.php @@ -0,0 +1,64 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\QueryHandler; + +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderQuery; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderQueryResult; +use PrestaShop\Module\PrestashopCheckout\Repository\PsCheckoutCartRepository; +use Psr\SimpleCache\CacheInterface; + +class GetPayPalOrderQueryHandler +{ + /** + * @var CacheInterface + */ + private $orderCache; + /** + * @var PsCheckoutCartRepository + */ + private $checkoutCartRepository; + + public function __construct(CacheInterface $orderCache, PsCheckoutCartRepository $checkoutCartRepository) + { + $this->orderCache = $orderCache; + $this->checkoutCartRepository = $checkoutCartRepository; + } + + /** + * @param GetPayPalOrderQuery $query + * + * @return GetPayPalOrderQueryResult + * + * @throws \PrestaShopException + */ + public function handle(GetPayPalOrderQuery $query) + { + $orderId = !$query->getOrderId()->getValue() ? null : $query->getOrderId()->getValue(); + + if (!$orderId) { + $psCheckoutCart = $this->checkoutCartRepository->findOneByCartId($query->getCartId()->getValue()); + $orderId = $psCheckoutCart->paypal_order; + } + + return new GetPayPalOrderQueryResult($this->orderCache->get($orderId)); + } +} diff --git a/src/PaymentMethodToken/PaymentMethodTokenRepository.php b/src/PaymentMethodToken/PaymentMethodTokenRepository.php new file mode 100644 index 000000000..236955b4c --- /dev/null +++ b/src/PaymentMethodToken/PaymentMethodTokenRepository.php @@ -0,0 +1,131 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PaymentMethodToken; + +use Db; +use DbQuery; +use Exception; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\ValueObject\PayPalCustomerId; +use PrestaShop\Module\PrestashopCheckout\Vault\ValueObject\PaymentMethodTokenId; + +class PaymentMethodTokenRepository +{ + /** + * @var Db + */ + private $db; + + /** + * @param Db $db + */ + public function __construct(Db $db) + { + $this->db = $db; + } + + /** + * @param PayPalCustomerId $customerId + * @param int $pageSize + * @param int $pageNumber + * + * @return array + * + * @throws Exception + */ + public function findByCustomerId(PayPalCustomerId $customerId, $pageSize, $pageNumber) + { + try { + $query = new DbQuery(); + $query->from('pscheckout_payment_token'); + $query->where('`paypal_customer_id` = ' . (int) $customerId->getValue()); + $query->limit($pageSize, ($pageNumber - 1) * $pageSize); + $results = $this->db->executeS($query); + + if (false === $results) { + throw new Exception('Failed to get PayPal Payment Method tokens from database.'); + } + + $paymentMethodTokens = []; + + foreach ($results as $result) { + $paymentMethodTokens[] = [ + 'id' => $result['id'], + 'paypal_customer_id' => $result['paypal_customer_id'], + 'payment_source' => $result['payment_source'], + 'data' => json_decode($result['data'], true), + ]; + } + + return $paymentMethodTokens; + } catch (Exception $exception) { + throw new Exception('Failed to get PayPal Payment Method tokens.', 0, $exception); + } + } + + /** + * @param PaymentMethodTokenId $id + * @param PayPalCustomerId $paypalCustomerId + * @param string $paymentSource + * @param array $data + * + * @return void + * + * @throws Exception + */ + public function save(PaymentMethodTokenId $id, PayPalCustomerId $paypalCustomerId, $paymentSource, array $data) + { + try { + $this->db->insert( + 'pscheckout_payment_token', + [ + 'id' => pSQL($id->getValue()), + 'paypal_customer_id' => pSQL($paypalCustomerId->getValue()), + 'payment_source' => pSQL($paymentSource), + 'data' => pSQL(json_encode($data)), + ] + ); + } catch (Exception $exception) { + throw new Exception('Failed to save PayPal Payment Method token.', 0, $exception); + } + } + + /** + * @param PayPalCustomerId $customerId + * + * @return int + * + * @throws Exception + */ + public function getTotalItems(PayPalCustomerId $customerId) + { + $query = new DbQuery(); + $query->select('COUNT(*)'); + $query->from('pscheckout_payment_token'); + $query->where('`paypal_customer_id` = ' . (int) $customerId->getValue()); + $totalItems = $this->db->getValue($query); + + if (false === $totalItems) { + throw new Exception('Failed to get PayPal Payment Method tokens from database.'); + } + + return (int) $totalItems; + } +} diff --git a/src/PaymentMethodToken/PaymentMethodTokenService.php b/src/PaymentMethodToken/PaymentMethodTokenService.php new file mode 100644 index 000000000..eeaed1986 --- /dev/null +++ b/src/PaymentMethodToken/PaymentMethodTokenService.php @@ -0,0 +1,60 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PaymentMethodToken; + +use Exception; +use GuzzleHttp\Psr7\Request; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\ValueObject\PayPalCustomerId; + +class PaymentMethodTokenService +{ + private $httpClient; + + public function __construct($httpClient) + { + $this->httpClient = $httpClient; + } + + /** + * @param PayPalCustomerId $customerId + * + * @return array + * + * @throws Exception + */ + public function fetchPaymentMethodTokens(PayPalCustomerId $customerId) + { + try { + $request = new Request('GET', 'https://api.paypal.com/v3/vault/payment-tokens&customer_id=' . $customerId->getValue(), []); + $response = $this->httpClient->sendRequest($request); + + $data = json_decode($response->getBody()->getContents(), true); + + if (empty($data['payment_tokens'])) { + throw new Exception('Failed to fetch PayPal Payment Method tokens from response.'); + } + + return $data['payment_tokens']; + } catch (Exception $exception) { + throw new Exception('Failed to fetch PayPal Payment Method tokens.', 0, $exception); + } + } +} diff --git a/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQuery.php b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQuery.php new file mode 100644 index 000000000..8536765e4 --- /dev/null +++ b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQuery.php @@ -0,0 +1,92 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\Query; + +use PrestaShop\Module\PrestashopCheckout\Customer\ValueObject\CustomerId; + +class GetCustomerPaymentMethodTokensQuery +{ + /** + * @var CustomerId + */ + private $customerId; + + /** + * @var int + */ + private $pageSize; + + /** + * @var int + */ + private $pageNumber; + + /** + * @var bool + */ + private $isTotalCountRequired; + + /** + * @param CustomerId $customerId + * @param int $pageSize + * @param int $pageNumber + * @param bool $isTotalCountRequired + */ + public function __construct(CustomerId $customerId, $pageSize, $pageNumber, $isTotalCountRequired = false) + { + $this->customerId = $customerId; + $this->pageSize = $pageSize; + $this->pageNumber = $pageNumber; + $this->isTotalCountRequired = $isTotalCountRequired; + } + + /** + * @return CustomerId + */ + public function getCustomerId() + { + return $this->customerId; + } + + /** + * @return int + */ + public function getPageSize() + { + return $this->pageSize; + } + + /** + * @return int + */ + public function getPageNumber() + { + return $this->pageNumber; + } + + /** + * @return bool + */ + public function isTotalCountRequired() + { + return $this->isTotalCountRequired; + } +} diff --git a/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryHandler.php b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryHandler.php new file mode 100644 index 000000000..f839d6c69 --- /dev/null +++ b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryHandler.php @@ -0,0 +1,76 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\Query; + +use Exception; +use PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\PaymentMethodTokenRepository; +use PrestaShop\Module\PrestashopCheckout\PayPal\Customer\PayPalCustomerRepository; + +class GetCustomerPaymentMethodTokensQueryHandler +{ + /** + * @var PayPalCustomerRepository + */ + private $customerRepository; + + /** + * @var PaymentMethodTokenRepository + */ + private $paymentMethodTokenRepository; + + /** + * @param PayPalCustomerRepository $customerRepository + * @param PaymentMethodTokenRepository $paymentMethodTokenRepository + */ + public function __construct(PayPalCustomerRepository $customerRepository, PaymentMethodTokenRepository $paymentMethodTokenRepository) + { + $this->customerRepository = $customerRepository; + $this->paymentMethodTokenRepository = $paymentMethodTokenRepository; + } + + /** + * @param GetCustomerPaymentMethodTokensQuery $query + * + * @return GetCustomerPaymentMethodTokensQueryResult + * + * @throws Exception + */ + public function handle(GetCustomerPaymentMethodTokensQuery $query) + { + $customerIdPayPal = $query->getCustomerId()->getValue() ? $this->customerRepository->findPayPalCustomerIdByCustomerId($query->getCustomerId()) : null; + $paymentTokens = $this->paymentMethodTokenRepository->findByCustomerId($customerIdPayPal, $query->getPageSize(), $query->getPageNumber()); + + if ($query->isTotalCountRequired()) { + $totalItems = $this->paymentMethodTokenRepository->getTotalItems($customerIdPayPal); + $totalPages = (int) ceil($totalItems / $query->getPageSize()); + } else { + $totalItems = null; + $totalPages = null; + } + + return new GetCustomerPaymentMethodTokensQueryResult( + $paymentTokens, + $query->getCustomerId(), + $totalItems, + $totalPages + ); + } +} diff --git a/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryResult.php b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryResult.php new file mode 100644 index 000000000..eb7f871c4 --- /dev/null +++ b/src/PaymentMethodToken/Query/GetCustomerPaymentMethodTokensQueryResult.php @@ -0,0 +1,92 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PaymentMethodToken\Query; + +use PrestaShop\Module\PrestashopCheckout\Customer\ValueObject\CustomerId; + +class GetCustomerPaymentMethodTokensQueryResult +{ + /** + * @var array + */ + private $paymentTokens; + + /** + * @var CustomerId + */ + private $customerId; + + /** + * @var int + */ + private $totalItems; + + /** + * @var int + */ + private $totalPages; + + /** + * @param array $paymentTokens + * @param CustomerId $customerId + * @param int $totalItems + * @param int|null $totalPages + */ + public function __construct(array $paymentTokens, CustomerId $customerId, $totalItems, $totalPages) + { + $this->paymentTokens = $paymentTokens; + $this->customerId = $customerId; + $this->totalItems = $totalItems; + $this->totalPages = $totalPages; + } + + /** + * @return array + */ + public function getPaymentTokens() + { + return $this->paymentTokens; + } + + /** + * @return CustomerId + */ + public function getCustomerId() + { + return $this->customerId; + } + + /** + * @return int + */ + public function getTotalItems() + { + return $this->totalItems; + } + + /** + * @return int + */ + public function getTotalPages() + { + return $this->totalPages; + } +} diff --git a/src/PaymentMethodToken/ValueObject/PaymentMethodTokenId.php b/src/PaymentMethodToken/ValueObject/PaymentMethodTokenId.php new file mode 100644 index 000000000..d08c35dae --- /dev/null +++ b/src/PaymentMethodToken/ValueObject/PaymentMethodTokenId.php @@ -0,0 +1,74 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Vault\ValueObject; + +use InvalidArgumentException; + +class PaymentMethodTokenId +{ + /** + * @var string + */ + private $id; + + /** + * @param string $id + * + * @throws InvalidArgumentException + */ + public function __construct($id) + { + $this->assertIsValid($id); + $this->id = $id; + } + + /** + * @return string + */ + public function getValue() + { + return $this->id; + } + + /** + * @param string $id + * + * @return void + * + * @throws InvalidArgumentException + */ + private function assertIsValid($id) + { + if (!is_string($id)) { + throw new InvalidArgumentException('PayPal Vault ID must be a string.'); + } + + $length = strlen($id); + + if ($length < 1 || $length > 36) { + throw new InvalidArgumentException('PayPal Vault ID must be between 1 and 36 characters long.'); + } + + if (preg_match('/^[0-9a-zA-Z_-]+$/', $id) !== 1) { + throw new InvalidArgumentException('PayPal Vault ID must be alphanumeric.'); + } + } +} diff --git a/tests/Unit/PayPal/Order/DTO/CreatePayPalOrderRequestTest.php b/tests/Unit/PayPal/Order/DTO/CreatePayPalOrderRequestTest.php new file mode 100644 index 000000000..ba00a0906 --- /dev/null +++ b/tests/Unit/PayPal/Order/DTO/CreatePayPalOrderRequestTest.php @@ -0,0 +1,96 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace Tests\Unit\PayPal\Order\DTO; + +use PHPUnit\Framework\TestCase; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AmountWithBreakdown; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PaymentSourceRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PayPalRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PayPalWalletExperienceContext; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PurchaseUnitRequest; + +class CreatePayPalOrderRequestTest extends TestCase +{ + /** + * @var CreatePayPalOrderRequest + */ + private $createPayPalOrderRequest; + + public function setUp(): void + { + $this->createPayPalOrderRequest = new CreatePayPalOrderRequest(); + $this->createPayPalOrderRequest->setIntent('CAPTURE'); + $this->createPayPalOrderRequest->setPurchaseUnits($this->createPurchaseUnits()); + $this->createPayPalOrderRequest->setPaymentSource($this->createPaymentSource()); + } + + public function testGetIntent() + { + $this->assertEquals('CAPTURE', $this->createPayPalOrderRequest->getIntent()); + } + + public function testGetPurchaseUnits() + { + $purchaseUnits = $this->createPayPalOrderRequest->getPurchaseUnits(); + $this->assertEquals(1, count($purchaseUnits)); + $this->assertInstanceOf(PurchaseUnitRequest::class, $purchaseUnits[0]); + } + + public function testGetPaymentSource() + { + $this->assertInstanceOf(PaymentSourceRequest::class, $this->createPayPalOrderRequest->getPaymentSource()); + } + + /** + * @return PurchaseUnitRequest[] + */ + private function createPurchaseUnits() + { + $purchaseUnits = []; + $amountWithBreakdown = new AmountWithBreakdown(); + $amountWithBreakdown->setValue('100.00'); + $amountWithBreakdown->setCurrencyCode('EUR'); + $purchaseUnitRequest = new PurchaseUnitRequest(); + $purchaseUnitRequest->setAmount($amountWithBreakdown); + $purchaseUnits[] = $purchaseUnitRequest; + + return $purchaseUnits; + } + + /** + * @return PaymentSourceRequest + */ + private function createPaymentSource() + { + $paymentSource = new PaymentSourceRequest(); + $paypal = new PayPalRequest(); + $experienceContext = new PayPalWalletExperienceContext(); + $experienceContext->setBrandName('PrestaShop'); + $experienceContext->setLandingPage('LOGIN'); + $experienceContext->setReturnUrl('https://www.prestashop.com/return'); + $experienceContext->setCancelUrl('https://www.prestashop.com/cancel'); + $paypal->setExperienceContext($experienceContext); + $paymentSource->setPaypal($paypal); + + return $paymentSource; + } +} From 52a474da06dc4b2a69b42eb436bd765b994a76ab Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 4 Mar 2024 17:45:27 +0200 Subject: [PATCH 04/26] Fixed old Order client class extension --- config/common.yml | 1 - src/Api/Payment/Order.php | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/config/common.yml b/config/common.yml index 83f83fafa..7f3f4cacc 100644 --- a/config/common.yml +++ b/config/common.yml @@ -735,7 +735,6 @@ services: arguments: - '@PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' - ps_checkout.http.client.configuration: class: 'PrestaShop\Module\PrestashopCheckout\Http\CheckoutHttpClientConfigurationBuilder' public: true diff --git a/src/Api/Payment/Order.php b/src/Api/Payment/Order.php index 18f97a0d5..ffe782ecb 100644 --- a/src/Api/Payment/Order.php +++ b/src/Api/Payment/Order.php @@ -21,14 +21,14 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PaymentClient; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\OldPaymentClient; /** * Handle order requests * * @deprecated */ -class Order extends PaymentClient +class Order extends OldPaymentClient { /** * @deprecated From e02044c722f30183320ee3a75faaa5b5d87b979b Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 6 Mar 2024 10:12:45 +0200 Subject: [PATCH 05/26] Removed abstract property from PshHttpClientAdapter --- controllers/front/create.php | 2 +- src/Http/PsrHttpClientAdapter.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/front/create.php b/controllers/front/create.php index ded576aef..d716e2386 100755 --- a/controllers/front/create.php +++ b/controllers/front/create.php @@ -19,8 +19,8 @@ * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 */ -use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; +use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; use PrestaShop\Module\PrestashopCheckout\Controller\AbstractFrontController; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Query\GetPayPalOrderForCartIdQuery; diff --git a/src/Http/PsrHttpClientAdapter.php b/src/Http/PsrHttpClientAdapter.php index 4a285b2f7..513f4b5e7 100644 --- a/src/Http/PsrHttpClientAdapter.php +++ b/src/Http/PsrHttpClientAdapter.php @@ -26,7 +26,7 @@ use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; use Psr\Http\Message\RequestInterface; -abstract class PsrHttpClientAdapter implements HttpClientInterface +class PsrHttpClientAdapter implements HttpClientInterface { private $client; From 345a7cbbc46f8e770e0bce993c984f7b88f3bbff Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 6 Mar 2024 13:18:30 +0200 Subject: [PATCH 06/26] Added logger to new API client --- config/common.yml | 2 + .../PaymentClientConfigurationBuilder.php | 50 ++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/config/common.yml b/config/common.yml index 7f3f4cacc..aaf3e27a3 100644 --- a/config/common.yml +++ b/config/common.yml @@ -729,6 +729,8 @@ services: - '@ps_checkout.context.shop' - '@ps_checkout.repository.prestashop.account' - '@ps_checkout.context.prestashop' + - "@ps_checkout.logger.configuration" + - "@ps_checkout.logger" PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient: class: 'PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient' diff --git a/src/Builder/Configuration/PaymentClientConfigurationBuilder.php b/src/Builder/Configuration/PaymentClientConfigurationBuilder.php index 9361274c6..5ff5fa6a8 100755 --- a/src/Builder/Configuration/PaymentClientConfigurationBuilder.php +++ b/src/Builder/Configuration/PaymentClientConfigurationBuilder.php @@ -20,12 +20,19 @@ namespace PrestaShop\Module\PrestashopCheckout\Builder\Configuration; +use GuzzleHttp\Event\Emitter; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Subscriber\Log\Formatter; +use GuzzleHttp\Subscriber\Log\LogSubscriber; +use GuzzleLogMiddleware\LogMiddleware; use PrestaShop\Module\PrestashopCheckout\Context\PrestaShopContext; use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; +use PrestaShop\Module\PrestashopCheckout\Logger\LoggerConfiguration; use PrestaShop\Module\PrestashopCheckout\Repository\PsAccountRepository; use PrestaShop\Module\PrestashopCheckout\Routing\Router; use PrestaShop\Module\PrestashopCheckout\ShopContext; use Ps_checkout; +use Psr\Log\LoggerInterface; class PaymentClientConfigurationBuilder implements ConfigurationBuilderInterface { @@ -47,19 +54,31 @@ class PaymentClientConfigurationBuilder implements ConfigurationBuilderInterface * @var PrestaShopContext */ private $prestaShopContext; + /** + * @var LoggerConfiguration + */ + private $loggerConfiguration; + /** + * @var LoggerInterface + */ + private $logger; public function __construct( PaymentEnv $paymentEnv, Router $router, ShopContext $shopContext, PsAccountRepository $psAccountRepository, - PrestaShopContext $prestaShopContext + PrestaShopContext $prestaShopContext, + LoggerConfiguration $loggerConfiguration, + LoggerInterface $logger ) { $this->paymentEnv = $paymentEnv; $this->router = $router; $this->shopContext = $shopContext; $this->psAccountRepository = $psAccountRepository; $this->prestaShopContext = $prestaShopContext; + $this->loggerConfiguration = $loggerConfiguration; + $this->logger = $logger; } /** @@ -67,7 +86,7 @@ public function __construct( */ public function build() { - return [ + $configuration = [ 'base_url' => $this->paymentEnv->getPaymentApiUrl(), 'verify' => $this->getVerify(), 'timeout' => static::TIMEOUT, @@ -82,6 +101,33 @@ public function build() 'Prestashop-Version' => _PS_VERSION_, // prestashop version ], ]; + + if ( + $this->loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION') + && class_exists(HandlerStack::class) + && class_exists(LogMiddleware::class) + ) { + $handlerStack = HandlerStack::create(); + $handlerStack->push(new LogMiddleware($this->logger)); + $configuration['handler'] = $handlerStack; + } elseif ( + $this->loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::VERSION') + && class_exists(Emitter::class) + && class_exists(LogSubscriber::class) + && class_exists(Formatter::class) + ) { + $emitter = new Emitter(); + $emitter->attach(new LogSubscriber( + $this->logger, + Formatter::DEBUG + )); + + $configuration['emitter'] = $emitter; + } + + return $configuration; } /** From 7380e3079668191582f02b37ce13377a31aa2303 Mon Sep 17 00:00:00 2001 From: Bastien Tafforeau Date: Wed, 3 Jan 2024 09:43:14 +0100 Subject: [PATCH 07/26] Draft for httpclient refactoring --- src/Api/Payment/Client/OldPaymentClient.php | 179 +----------------- .../PaymentClientConfigurationBuilder.php | 89 +++++++++ src/Http/PsrClientAdapter.php | 45 +++++ 3 files changed, 143 insertions(+), 170 deletions(-) create mode 100755 src/Api/Payment/Client/PaymentClientConfigurationBuilder.php create mode 100644 src/Http/PsrClientAdapter.php diff --git a/src/Api/Payment/Client/OldPaymentClient.php b/src/Api/Payment/Client/OldPaymentClient.php index 8a4719df2..031705987 100755 --- a/src/Api/Payment/Client/OldPaymentClient.php +++ b/src/Api/Payment/Client/OldPaymentClient.php @@ -20,188 +20,27 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; -use Context; -use GuzzleHttp\Event\Emitter; -use GuzzleHttp\HandlerStack; -use GuzzleHttp\Subscriber\Log\Formatter; -use GuzzleHttp\Subscriber\Log\LogSubscriber; -use GuzzleLogMiddleware\LogMiddleware; -use Link; -use Module; -use PrestaShop\Module\PrestashopCheckout\Api\GenericClient; -use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; -use PrestaShop\Module\PrestashopCheckout\Exception\HttpTimeoutException; -use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; -use PrestaShop\Module\PrestashopCheckout\Logger\LoggerConfiguration; -use PrestaShop\Module\PrestashopCheckout\Routing\Router; -use PrestaShop\Module\PrestashopCheckout\ShopContext; -use PrestaShop\Module\PrestashopCheckout\Version\Version; -use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; -use Ps_checkout; -use Psr\Log\LoggerInterface; +use PrestaShop\Module\PrestashopCheckout\Http\PsrClientAdapter; +use Psr\Http\Message\RequestInterface; /** * Construct the client used to make call to maasland */ class OldPaymentClient extends GenericClient { - /** - * @param Link $link - * @param object|null $client - */ - public function __construct(Link $link, $client = null) - { - parent::__construct(); - - $this->setLink($link); - - // Client can be provided for tests - if (null === $client) { - /** @var Ps_checkout $module */ - $module = Module::getInstanceByName('ps_checkout'); - - /** @var Version $version */ - $version = $module->getService('ps_checkout.module.version'); - - /** @var LoggerConfiguration $loggerConfiguration */ - $loggerConfiguration = $module->getService('ps_checkout.logger.configuration'); - - /** @var LoggerInterface $logger */ - $logger = $module->getService('ps_checkout.logger'); + /** @var PsrClientAdapter */ + private $client; - /** @var Router $router */ - $router = $module->getService('ps_checkout.prestashop.router'); - - $clientConfiguration = [ - 'base_url' => (new PaymentEnv())->getPaymentApiUrl(), - 'verify' => $this->getVerify(), - 'timeout' => $this->timeout, - 'exceptions' => $this->catchExceptions, - 'headers' => [ - 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $this->token, // Token we get from PsAccounts - 'Shop-Id' => $this->shopUid, // Shop UUID we get from PsAccounts - 'Hook-Url' => $router->getDispatchWebhookLink((int) Context::getContext()->shop->id), - 'Bn-Code' => (new ShopContext())->getBnCode(), - 'Module-Version' => $version->getSemVersion(), // version of the module - 'Prestashop-Version' => _PS_VERSION_, // prestashop version - ], - ]; - - if ( - $loggerConfiguration->isHttpEnabled() - && defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION') - && class_exists(HandlerStack::class) - && class_exists(LogMiddleware::class) - ) { - $handlerStack = HandlerStack::create(); - $handlerStack->push(new LogMiddleware($logger)); - $clientConfiguration['handler'] = $handlerStack; - } elseif ( - $loggerConfiguration->isHttpEnabled() - && defined('\GuzzleHttp\ClientInterface::VERSION') - && class_exists(Emitter::class) - && class_exists(LogSubscriber::class) - && class_exists(Formatter::class) - ) { - $emitter = new Emitter(); - $emitter->attach(new LogSubscriber( - $logger, - Formatter::DEBUG - )); - - $clientConfiguration['emitter'] = $emitter; - } - - $client = (new ClientFactory())->getClient($clientConfiguration); - } - - $this->setClient($client); - } - - /** - * @param array $options - * - * @return array - * - * @throws HttpTimeoutException - */ - protected function post(array $options = []) + public function __construct(PaymentClientConfigurationBuilder $configurationBuilder) { - $delay = isset($options['delay']) ? (int) $options['delay'] : 2; - $retries = isset($options['retries']) ? (int) $options['retries'] : 2; - unset($options['delay'], $options['retries']); - - return $this->postWithRetry($options, $delay, $retries); + $this->client = new PsrClientAdapter($configurationBuilder->build()); } /** - * @param array $options - * @param int $delay - * @param int $retries - * - * @return array - * - * @throws HttpTimeoutException - * @throws PsCheckoutException + * {@inheritdoc} */ - private function postWithRetry(array $options, $delay = 2, $retries = 2) + public function sendRequest(RequestInterface $request) { - try { - $response = parent::post($options); - - if ($response['httpCode'] === 401 || false !== strpos($response['exceptionMessage'], 'Unauthorized')) { - throw new PsCheckoutException('Unauthorized', PsCheckoutException::PSCHECKOUT_HTTP_UNAUTHORIZED); - } - - if (false !== $response['status']) { - return $response; - } - - if ( - isset($response['exceptionCode']) - && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION - && false !== strpos($response['exceptionMessage'], 'cURL error 28') - ) { - throw new HttpTimeoutException($response['exceptionMessage'], PsCheckoutException::PSL_TIMEOUT); - } elseif ( - isset($response['exceptionCode']) - && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION - ) { - throw new PsCheckoutException($response['exceptionMessage'], PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION); - } - - if ( - isset($response['body']['message']) - && ($response['body']['message'] === 'Error: ETIMEDOUT' || $response['body']['message'] === 'Error: ESOCKETTIMEDOUT') - ) { - throw new HttpTimeoutException($response['body']['message'], PsCheckoutException::PSL_TIMEOUT); - } - } catch (HttpTimeoutException $exception) { - if ($this->isRouteRetryable() && $retries > 0) { - sleep($delay); - - return $this->postWithRetry($options, $delay, $retries - 1); - } - - throw $exception; - } - - return $response; - } - - /** - * @return bool - */ - private function isRouteRetryable() - { - switch ($this->getRoute()) { - case '/payments/order/capture': - case '/payments/order/refund': - return false; - } - - return true; + return $this->client->sendRequest($request); } } diff --git a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php b/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php new file mode 100755 index 000000000..b485c8e32 --- /dev/null +++ b/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php @@ -0,0 +1,89 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; + +use PrestaShop\Module\PrestashopCheckout\Configuration\PrestaShopConfiguration; +use PrestaShop\Module\PrestashopCheckout\Environment\Env; +use PrestaShop\Module\PrestashopCheckout\Repository\PsAccountRepository; +use PrestaShop\Module\PrestashopCheckout\Routing\Router; +use PrestaShop\Module\PrestashopCheckout\ShopContext; +use Ps_checkout; + +class PaymentClientConfigurationBuilder +{ + const TIMEOUT = 10; + + /** @var Env */ + private $env; + + /** @var Router */ + private $router; + + /** @var ShopContext */ + private $shopContext; + + /** @var PsAccountRepository */ + private $psAccountRepository; + + /** @var PrestaShopConfiguration */ + private $prestaShopConfiguration; + + /** @var CertFileProvider */ + private $certFileProvider; + + public function __construct( + Env $env, + Router $router, + ShopContext $shopContext, + PsAccountRepository $psAccountRepository, + PrestaShopConfiguration $prestaShopConfiguration, + CertFileProvider $certFileProvider + ) { + $this->env = $env; + $this->router = $router; + $this->shopContext = $shopContext; + $this->psAccountRepository = $psAccountRepository; + $this->prestaShopConfiguration = $prestaShopConfiguration; + $this->certFileProvider = $certFileProvider; + } + + /** + * @return array + */ + public function build() + { + return [ + 'base_url' => $this->env->getPaymentApiUrl(), + 'verify' => $this->certFileProvider->getPath(), + 'timeout' => static::TIMEOUT, + 'headers' => [ + 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) + 'Accept' => 'application/json', + 'Authorization' => 'Bearer ' . $this->psAccountRepository->getIdToken(), // Token we get from PsAccounts + 'Shop-Id' => $this->psAccountRepository->getShopUuid(), // Shop UUID we get from PsAccounts + 'Hook-Url' => $this->router->getDispatchWebhookLink((int) Context::getContext()->shop->id), + 'Bn-Code' => $this->shopContext->getBnCode(), + 'Module-Version' => Ps_checkout::VERSION, // version of the module + 'Prestashop-Version' => _PS_VERSION_, // prestashop version + ], + ]; + } +} diff --git a/src/Http/PsrClientAdapter.php b/src/Http/PsrClientAdapter.php new file mode 100644 index 000000000..fcef2a437 --- /dev/null +++ b/src/Http/PsrClientAdapter.php @@ -0,0 +1,45 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Http; + +use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; +use Psr\Http\Message\RequestInterface; + +class PsrClientAdapter implements HttpClientInterface +{ + private $client; + + /** + * @param array $configuration + */ + public function __construct(array $configuration) + { + $this->client = (new ClientFactory())->getClient($configuration); + } + + /** + * {@inheritdoc} + */ + public function sendRequest(RequestInterface $request) + { + return $this->client->sendRequest($request); + } +} From b305f0bcaccf92a0b2c4823f04ef17cc3f98960d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20=C5=A0edys?= Date: Tue, 13 Feb 2024 13:01:14 +0200 Subject: [PATCH 08/26] Modified payment client and configuration builder (#1199) * Modified payment client and configuration builder * Changed PayPalClient name * Added builder interface * CS fix --- .../PaymentClientConfigurationBuilder.php | 89 ------------------- src/Http/PsrClientAdapter.php | 45 ---------- 2 files changed, 134 deletions(-) delete mode 100755 src/Api/Payment/Client/PaymentClientConfigurationBuilder.php delete mode 100644 src/Http/PsrClientAdapter.php diff --git a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php b/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php deleted file mode 100755 index b485c8e32..000000000 --- a/src/Api/Payment/Client/PaymentClientConfigurationBuilder.php +++ /dev/null @@ -1,89 +0,0 @@ - - * @copyright Since 2007 PrestaShop SA and Contributors - * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 - */ - -namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; - -use PrestaShop\Module\PrestashopCheckout\Configuration\PrestaShopConfiguration; -use PrestaShop\Module\PrestashopCheckout\Environment\Env; -use PrestaShop\Module\PrestashopCheckout\Repository\PsAccountRepository; -use PrestaShop\Module\PrestashopCheckout\Routing\Router; -use PrestaShop\Module\PrestashopCheckout\ShopContext; -use Ps_checkout; - -class PaymentClientConfigurationBuilder -{ - const TIMEOUT = 10; - - /** @var Env */ - private $env; - - /** @var Router */ - private $router; - - /** @var ShopContext */ - private $shopContext; - - /** @var PsAccountRepository */ - private $psAccountRepository; - - /** @var PrestaShopConfiguration */ - private $prestaShopConfiguration; - - /** @var CertFileProvider */ - private $certFileProvider; - - public function __construct( - Env $env, - Router $router, - ShopContext $shopContext, - PsAccountRepository $psAccountRepository, - PrestaShopConfiguration $prestaShopConfiguration, - CertFileProvider $certFileProvider - ) { - $this->env = $env; - $this->router = $router; - $this->shopContext = $shopContext; - $this->psAccountRepository = $psAccountRepository; - $this->prestaShopConfiguration = $prestaShopConfiguration; - $this->certFileProvider = $certFileProvider; - } - - /** - * @return array - */ - public function build() - { - return [ - 'base_url' => $this->env->getPaymentApiUrl(), - 'verify' => $this->certFileProvider->getPath(), - 'timeout' => static::TIMEOUT, - 'headers' => [ - 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $this->psAccountRepository->getIdToken(), // Token we get from PsAccounts - 'Shop-Id' => $this->psAccountRepository->getShopUuid(), // Shop UUID we get from PsAccounts - 'Hook-Url' => $this->router->getDispatchWebhookLink((int) Context::getContext()->shop->id), - 'Bn-Code' => $this->shopContext->getBnCode(), - 'Module-Version' => Ps_checkout::VERSION, // version of the module - 'Prestashop-Version' => _PS_VERSION_, // prestashop version - ], - ]; - } -} diff --git a/src/Http/PsrClientAdapter.php b/src/Http/PsrClientAdapter.php deleted file mode 100644 index fcef2a437..000000000 --- a/src/Http/PsrClientAdapter.php +++ /dev/null @@ -1,45 +0,0 @@ - - * @copyright Since 2007 PrestaShop SA and Contributors - * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 - */ - -namespace PrestaShop\Module\PrestashopCheckout\Http; - -use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; -use Psr\Http\Message\RequestInterface; - -class PsrClientAdapter implements HttpClientInterface -{ - private $client; - - /** - * @param array $configuration - */ - public function __construct(array $configuration) - { - $this->client = (new ClientFactory())->getClient($configuration); - } - - /** - * {@inheritdoc} - */ - public function sendRequest(RequestInterface $request) - { - return $this->client->sendRequest($request); - } -} From a0bf1046590f5edab77e89d281d49b8e7499196f Mon Sep 17 00:00:00 2001 From: Matthias RAIGNE <5262628+Matt75@users.noreply.github.com> Date: Tue, 13 Feb 2024 12:36:28 +0100 Subject: [PATCH 09/26] PAYSHIP-2630 (#1182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Replace client token by user id token * Implement payment method token * Interfaces * PAYSHIP-2631 PayPal Create Order Request DTO * Added correct class import * [PAYSHIP-2637] CreatePayPalOrderResponse DTO (#1189) * Added CreatePayPalOrderResponse DTO * Added DTOs for create order response * CS fix * Added licenses * [PAYSHIP-2632] Order create refactoring (#1183) * Created required classes * Added order create command handler logic * Added paypal order query handler * Moved QueryResult to Query namespace * Added create command and get order query to command bus factory * CS fix * PHPStan fixes * Reverted to old create handler * PHPStan fixes * Fixed regex and wrong customerId type --------- Co-authored-by: Laurynas Co-authored-by: Laurynas Šedys --- config/common.yml | 1 - .../Order/CommandHandler/CreatePayPalOrderCommandHandler.php | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/config/common.yml b/config/common.yml index aaf3e27a3..d60f72729 100644 --- a/config/common.yml +++ b/config/common.yml @@ -369,7 +369,6 @@ services: - '@ps_checkout.paypal.order.translations' - '@ps_checkout.context.shop' - ps_checkout.paypal.builder.view_order_summary: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\PayPalOrderSummaryViewBuilder' public: true diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 733d8eace..972b3fcef 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -25,6 +25,7 @@ use PrestaShop\Module\PrestashopCheckout\Event\EventDispatcherInterface; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\CreatePayPalOrderPayloadBuilderInterface; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Event\PayPalOrderCreatedEvent; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Exception\PayPalOrderException; class CreatePayPalOrderCommandHandler From 7298811b6877e03e3b318be2e9d5094965553d06 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 12 Feb 2024 16:04:24 +0200 Subject: [PATCH 10/26] Changed CreateOrderHandler to use new HttpClient --- .../Payment/Client/PayPalOrderHttpClient.php | 45 +++++++++++++++++++ src/Api/Payment/PaymentService.php | 10 ++++- .../CreatePayPalOrderCommandHandler.php | 26 +++++++---- 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/src/Api/Payment/Client/PayPalOrderHttpClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php index c9860aa3a..693f7e470 100755 --- a/src/Api/Payment/Client/PayPalOrderHttpClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -20,8 +20,16 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception\HttpException; +use Http\Client\Exception\NetworkException; +use Http\Client\Exception\RequestException; +use Http\Client\Exception\TransferException; use PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder; use PrestaShop\Module\PrestashopCheckout\Http\PsrHttpClientAdapter; +use PrestaShop\Module\PrestashopCheckout\Http\Request\CreatePayPalOrderRequest; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; class PayPalOrderHttpClient extends PsrHttpClientAdapter { @@ -29,4 +37,41 @@ public function __construct(PaymentClientConfigurationBuilder $configurationBuil { parent::__construct($configurationBuilder->build()); } + + /** + * @param RequestInterface $request + * @return ResponseInterface + * + * @throws HttpException + */ + public function sendRequest(RequestInterface $request) + { + try { + return parent::sendRequest($request); + } catch (NetworkException $exception) { + // Thrown when the request cannot be completed because of network issues. + // No response here + } catch (HttpException $exception) { + // Thrown when a response was received but the request itself failed. + // There a response here + // So this one contains why response failed with Maasland error response + if ($exception->getResponse()->getStatusCode() === 500) { + // Internal Server Error: retry then stop using Maasland for XXX times after X failed retries, requires a circuit breaker + } + if ($exception->getResponse()->getStatusCode() === 503) { + // Service Unavailable: we should stop using Maasland, requires a circuit breaker + } + // response status code 4XX throw exception to be catched on specific method + throw $exception; // Avoid this to be catched next + } catch (RequestException $exception) { + // No response here + } catch (TransferException $exception) { + // others without response + } + } + + public function createOrder($payload, $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/create', $options, $payload)); + } } diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 6f79ba9b3..3b6147bf8 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -26,6 +26,7 @@ use Http\Client\Exception\RequestException; use Http\Client\Exception\TransferException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; +use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequest; use Psr\Http\Message\ResponseInterface; class PaymentService @@ -40,10 +41,15 @@ public function __construct(PayPalOrderHttpClient $client) $this->client = $client; } - public function createOrder(array $payload) + /** + * @param CreatePayPalOrderRequest $request + * @return ResponseInterface|void + */ + public function createOrder(CreatePayPalOrderRequest $request) { + $payload = (array) $request; try { - return $this->sendRequest('POST', '/payments/order/create', [], $payload); + return $this->client->createOrder($payload); } catch (HttpException $exception) { $response = $exception->getResponse(); if ($response->getStatusCode() === 400) { diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 972b3fcef..00e30d020 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -20,6 +20,7 @@ namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler; +use PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService; use PrestaShop\Module\PrestashopCheckout\Cart\CartRepositoryInterface; use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; use PrestaShop\Module\PrestashopCheckout\Event\EventDispatcherInterface; @@ -34,23 +35,31 @@ class CreatePayPalOrderCommandHandler * @var CartRepositoryInterface */ private $cartRepository; + /** * @var CreatePayPalOrderPayloadBuilderInterface */ private $createPayPalOrderPayloadBuilder; + /** * @var EventDispatcherInterface */ private $eventDispatcher; + /** + * @var PaymentService + */ + private $paymentService; public function __construct( CartRepositoryInterface $cartRepository, CreatePayPalOrderPayloadBuilderInterface $createPayPalOrderPayloadBuilder, - EventDispatcherInterface $eventDispatcher + EventDispatcherInterface $eventDispatcher, + PaymentService $paymentService ) { $this->cartRepository = $cartRepository; $this->createPayPalOrderPayloadBuilder = $createPayPalOrderPayloadBuilder; $this->eventDispatcher = $eventDispatcher; + $this->paymentService = $paymentService; } /** @@ -65,12 +74,13 @@ public function handle(CreatePayPalOrderCommand $command) { $cart = $this->cartRepository->getCartById($command->getCartId()); $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); -// $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( -// $order->getId(), -// $order->toArray(), -// $command->getCartId(), -// $command->isHostedFields(), -// $command->isExpressCheckout() -// )); + $order = $this->paymentService->createOrder($payload); + $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( + $order->getId(), + $order->toArray(), + $command->getCartId(), + $command->isHostedFields(), + $command->isExpressCheckout() + )); } } From 2a655a46221f9920181083d9abaef61a826cc25f Mon Sep 17 00:00:00 2001 From: Laurynas Date: Tue, 13 Feb 2024 13:43:14 +0200 Subject: [PATCH 11/26] Fix --- src/Api/Payment/PaymentService.php | 2 +- .../CommandHandler/CreatePayPalOrderCommandHandler.php | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 3b6147bf8..312fe48e9 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -26,7 +26,7 @@ use Http\Client\Exception\RequestException; use Http\Client\Exception\TransferException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; -use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; use Psr\Http\Message\ResponseInterface; class PaymentService diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 00e30d020..0f16b50dd 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -74,10 +74,11 @@ public function handle(CreatePayPalOrderCommand $command) { $cart = $this->cartRepository->getCartById($command->getCartId()); $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); - $order = $this->paymentService->createOrder($payload); + $response = $this->paymentService->createOrder($payload); + $order = $response->getBody(); $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( - $order->getId(), - $order->toArray(), + $order['id'], + $order, $command->getCartId(), $command->isHostedFields(), $command->isExpressCheckout() From da3d354bbbecbcc08110a28c71d68f80eee21399 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Tue, 13 Feb 2024 17:12:21 +0200 Subject: [PATCH 12/26] Added order managing functions to OrderHttpClient --- .../Payment/Client/PayPalOrderHttpClient.php | 57 +++++++++++++++- src/Api/Payment/PaymentService.php | 66 ++++--------------- 2 files changed, 67 insertions(+), 56 deletions(-) diff --git a/src/Api/Payment/Client/PayPalOrderHttpClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php index 693f7e470..6d1282b1a 100755 --- a/src/Api/Payment/Client/PayPalOrderHttpClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -70,8 +70,63 @@ public function sendRequest(RequestInterface $request) } } - public function createOrder($payload, $options = []) + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function createOrder(array $payload, array $options = []) { return $this->sendRequest(new Request('POST', '/payments/order/create', $options, $payload)); } + + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function updateOrder(array $payload, array $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/update', $options, $payload)); + } + + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function fetchOrder(array $payload, array $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/fetch', $options, $payload)); + } + + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function captureOrder(array $payload, array $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/capture', $options, $payload)); + } + + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function refundOrder(array $payload, array $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/refund', $options, $payload)); + } + + /** + * @param array $payload + * @param array $options + * @return ResponseInterface + */ + public function generateClientToken(array $payload, array $options = []) + { + return $this->sendRequest(new Request('POST', '/payments/order/generate_client_token', $options, $payload)); + } } diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 312fe48e9..73d070b63 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -121,21 +121,21 @@ public function createOrder(CreatePayPalOrderRequest $request) public function updateOrder(array $payload) { - return $this->sendRequest('POST', '/payments/order/update', [], $payload); + return $this->client->updateOrder($payload); } /** - * @param array{order_id: string} $data + * @param string $orderId * * @return ResponseInterface */ - public function getOrder(array $data) + public function getOrder($orderId) { $payload = [ - 'orderId' => $data['order_id'], + 'orderId' => $orderId, ]; - return $this->sendRequest('POST', '/payments/order/fetch', [], $payload); + return $this->client->fetchOrder($payload); } /** @@ -153,30 +153,30 @@ public function captureOrder(array $data) ], ]; - return $this->sendRequest('POST', '/payments/order/capture', [], $payload); + return $this->client->captureOrder($payload); } public function refundOrder(array $payload) { - return $this->sendRequest('POST', '/payments/order/refund', [], $payload); + return $this->client->refundOrder($payload); } /** - * @param array{merchant_id: string} $data + * @param string $merchantId * * @return ResponseInterface */ - public function getIdentityToken(array $data) + public function getIdentityToken($merchantId) { $payload = [ 'return_payload' => true, 'payee' => [ - 'merchant_id' => $data['merchant_id'], + 'merchant_id' => $merchantId, ], ]; try { - return $this->sendRequest('POST', '/payments/order/generate_client_token', [], $payload); + return $this->client->generateClientToken($payload); } catch (HttpException $exception) { $response = $exception->getResponse(); if ($response->getStatusCode() === 400) { @@ -195,48 +195,4 @@ public function getIdentityToken(array $data) return $response; } } - - /** - * @param string $method - * @param string $uri - * @param array $options - * @param array $payload - * - * @return ResponseInterface - * - * @throws NetworkException - * @throws HttpException - * @throws RequestException - * @throws TransferException - */ - private function sendRequest($method, $uri, $options, $payload) - { - try { - return $this->client->sendRequest(new Request($method, $uri, $options, json_encode($payload))); - } catch (NetworkException $exception) { - throw $exception; // TODO Replace - // Thrown when the request cannot be completed because of network issues. - // No response here - } catch (HttpException $exception) { - // Thrown when a response was received but the request itself failed. - // There a response here - // So this one contains why response failed with Maasland error response - if ($exception->getResponse()->getStatusCode() === 500) { - throw $exception; // TODO Replace - // Internal Server Error: retry then stop using Maasland for XXX times after X failed retries, requires a circuit breaker - } - if ($exception->getResponse()->getStatusCode() === 503) { - throw $exception; // TODO Replace - // Service Unavailable: we should stop using Maasland, requires a circuit breaker - } - // response status code 4XX throw exception to be catched on specific method - throw $exception; // Avoid this to be catched next - } catch (RequestException $exception) { - throw $exception; // TODO Replace - // No response here - } catch (TransferException $exception) { - throw $exception; // TODO Replace - // others without response - } - } } From 6d3fc0ca68f2aed3465d97b53ba320adab50594e Mon Sep 17 00:00:00 2001 From: Laurynas Date: Tue, 13 Feb 2024 18:09:08 +0200 Subject: [PATCH 13/26] CS fix --- src/Api/Payment/Client/PayPalOrderHttpClient.php | 8 +++++++- src/Api/Payment/PaymentService.php | 4 +--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Api/Payment/Client/PayPalOrderHttpClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php index 6d1282b1a..a03dcb675 100755 --- a/src/Api/Payment/Client/PayPalOrderHttpClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -27,7 +27,6 @@ use Http\Client\Exception\TransferException; use PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder; use PrestaShop\Module\PrestashopCheckout\Http\PsrHttpClientAdapter; -use PrestaShop\Module\PrestashopCheckout\Http\Request\CreatePayPalOrderRequest; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -40,6 +39,7 @@ public function __construct(PaymentClientConfigurationBuilder $configurationBuil /** * @param RequestInterface $request + * * @return ResponseInterface * * @throws HttpException @@ -73,6 +73,7 @@ public function sendRequest(RequestInterface $request) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function createOrder(array $payload, array $options = []) @@ -83,6 +84,7 @@ public function createOrder(array $payload, array $options = []) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function updateOrder(array $payload, array $options = []) @@ -93,6 +95,7 @@ public function updateOrder(array $payload, array $options = []) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function fetchOrder(array $payload, array $options = []) @@ -103,6 +106,7 @@ public function fetchOrder(array $payload, array $options = []) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function captureOrder(array $payload, array $options = []) @@ -113,6 +117,7 @@ public function captureOrder(array $payload, array $options = []) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function refundOrder(array $payload, array $options = []) @@ -123,6 +128,7 @@ public function refundOrder(array $payload, array $options = []) /** * @param array $payload * @param array $options + * * @return ResponseInterface */ public function generateClientToken(array $payload, array $options = []) diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 73d070b63..a7edeab6e 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -22,9 +22,6 @@ use GuzzleHttp\Psr7\Request; use Http\Client\Exception\HttpException; -use Http\Client\Exception\NetworkException; -use Http\Client\Exception\RequestException; -use Http\Client\Exception\TransferException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; use Psr\Http\Message\ResponseInterface; @@ -43,6 +40,7 @@ public function __construct(PayPalOrderHttpClient $client) /** * @param CreatePayPalOrderRequest $request + * * @return ResponseInterface|void */ public function createOrder(CreatePayPalOrderRequest $request) From 86a0c2f9d8e47114259411fa4fd9b1f949130e12 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 14 Feb 2024 12:46:46 +0200 Subject: [PATCH 14/26] Added json encoding for request sending --- src/Api/Payment/Client/PayPalOrderHttpClient.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Api/Payment/Client/PayPalOrderHttpClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php index a03dcb675..6422c6e3d 100755 --- a/src/Api/Payment/Client/PayPalOrderHttpClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -64,8 +64,10 @@ public function sendRequest(RequestInterface $request) // response status code 4XX throw exception to be catched on specific method throw $exception; // Avoid this to be catched next } catch (RequestException $exception) { + throw $exception; // No response here } catch (TransferException $exception) { + throw $exception; // others without response } } @@ -78,7 +80,7 @@ public function sendRequest(RequestInterface $request) */ public function createOrder(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/create', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/create', $options, json_encode($payload))); } /** @@ -89,7 +91,7 @@ public function createOrder(array $payload, array $options = []) */ public function updateOrder(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/update', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/update', $options, json_encode($payload))); } /** @@ -100,7 +102,7 @@ public function updateOrder(array $payload, array $options = []) */ public function fetchOrder(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/fetch', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/fetch', $options, json_encode($payload))); } /** @@ -111,7 +113,7 @@ public function fetchOrder(array $payload, array $options = []) */ public function captureOrder(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/capture', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/capture', $options, json_encode($payload))); } /** @@ -122,7 +124,7 @@ public function captureOrder(array $payload, array $options = []) */ public function refundOrder(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/refund', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/refund', $options, json_encode($payload))); } /** @@ -133,6 +135,6 @@ public function refundOrder(array $payload, array $options = []) */ public function generateClientToken(array $payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/generate_client_token', $options, $payload)); + return $this->sendRequest(new Request('POST', '/payments/order/generate_client_token', $options, json_encode($payload))); } } From 0310a61fcd65d288df7842c3bf78a6f8c90bed0f Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 14 Feb 2024 17:57:35 +0200 Subject: [PATCH 15/26] Added dependency config --- config/common.yml | 10 ++++++++-- src/Api/Payment/PaymentService.php | 1 - src/Http/PsrHttpClientAdapter.php | 4 ++++ .../CommandHandler/CreatePayPalOrderCommandHandler.php | 2 +- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/config/common.yml b/config/common.yml index d60f72729..6ca7f6a0a 100644 --- a/config/common.yml +++ b/config/common.yml @@ -455,7 +455,7 @@ services: PrestaShop\Module\PrestashopCheckout\Order\Command\CreateOrderCommand: "ps_checkout.command.handler.order.create_order" PrestaShop\Module\PrestashopCheckout\Order\Command\UpdateOrderStatusCommand: "ps_checkout.command.handler.order.update_order_status" PrestaShop\Module\PrestashopCheckout\Order\Matrice\Command\UpdateOrderMatriceCommand: "ps_checkout.command.handler.order.matrice.update_order_matrice" - PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand: "ps_checkout.command.handler.paypal.order.create_paypal_order" + PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\CreatePayPalOrderCommandHandler' PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\UpdatePayPalOrderCommand: "ps_checkout.command.handler.paypal.order.update_paypal_order" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CapturePayPalOrderCommand: "ps_checkout.command.handler.paypal.order.capture_paypal_order" PrestaShop\Module\PrestashopCheckout\Checkout\Command\CancelCheckoutCommand: "ps_checkout.command.handler.checkout.cancel_checkout" @@ -576,13 +576,14 @@ services: arguments: - "@ps_checkout.event.dispatcher" - ps_checkout.command.handler.paypal.order.create_paypal_order: + PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\CreatePayPalOrderCommandHandler: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\CreatePayPalOrderCommandHandler' public: true arguments: - '@?' - '@?' - '@ps_checkout.event.dispatcher' + - '@PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' ps_checkout.command.handler.paypal.order.update_paypal_order: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\UpdatePayPalOrderCommandHandler' @@ -736,6 +737,11 @@ services: arguments: - '@PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' + PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService: + class: 'PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' + arguments: + - '@PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient' + ps_checkout.http.client.configuration: class: 'PrestaShop\Module\PrestashopCheckout\Http\CheckoutHttpClientConfigurationBuilder' public: true diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index a7edeab6e..042871a51 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -20,7 +20,6 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; -use GuzzleHttp\Psr7\Request; use Http\Client\Exception\HttpException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; diff --git a/src/Http/PsrHttpClientAdapter.php b/src/Http/PsrHttpClientAdapter.php index 513f4b5e7..c5fdb3825 100644 --- a/src/Http/PsrHttpClientAdapter.php +++ b/src/Http/PsrHttpClientAdapter.php @@ -24,10 +24,14 @@ use Http\Client\Exception\NetworkException; use Http\Client\Exception\TransferException; use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; +use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; class PsrHttpClientAdapter implements HttpClientInterface { + /** + * @var ClientInterface + */ private $client; /** diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 0f16b50dd..4b930ad8e 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -75,7 +75,7 @@ public function handle(CreatePayPalOrderCommand $command) $cart = $this->cartRepository->getCartById($command->getCartId()); $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); $response = $this->paymentService->createOrder($payload); - $order = $response->getBody(); + $order = json_decode($response->getBody()->getContents()); $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( $order['id'], $order, From fe55342eff632f5f8fcef57aa01db1708a02740b Mon Sep 17 00:00:00 2001 From: Bastien Tafforeau Date: Mon, 19 Feb 2024 10:33:15 +0100 Subject: [PATCH 16/26] Create order unit tests --- src/Api/Payment/PaymentService.php | 215 +++++++++++------ .../CreatePayPalOrderRequestInterface.php | 36 +++ src/Exception/InvalidRequestException.php | 36 +++ src/Exception/NotAuthorizedException.php | 31 +++ .../UnprocessableEntityException.php | 68 ++++++ .../Order/DTO/CreatePayPalOrderRequest.php | 2 +- .../PaymentServiceCreateOrderTest.php | 219 ++++++++++++++++++ 7 files changed, 539 insertions(+), 68 deletions(-) create mode 100644 src/DTO/Orders/CreatePayPalOrderRequestInterface.php create mode 100644 src/Exception/InvalidRequestException.php create mode 100644 src/Exception/NotAuthorizedException.php create mode 100644 src/Exception/UnprocessableEntityException.php create mode 100644 tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 042871a51..6d90c2610 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -22,7 +22,10 @@ use Http\Client\Exception\HttpException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; -use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; +use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequestInterface; +use PrestaShop\Module\PrestashopCheckout\Exception\InvalidRequestException; +use PrestaShop\Module\PrestashopCheckout\Exception\NotAuthorizedException; +use PrestaShop\Module\PrestashopCheckout\Exception\UnprocessableEntityException; use Psr\Http\Message\ResponseInterface; class PaymentService @@ -38,80 +41,144 @@ public function __construct(PayPalOrderHttpClient $client) } /** - * @param CreatePayPalOrderRequest $request - * + * @param CreatePayPalOrderRequestInterface $request * @return ResponseInterface|void + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ - public function createOrder(CreatePayPalOrderRequest $request) + public function createOrder(CreatePayPalOrderRequestInterface $request) { $payload = (array) $request; try { return $this->client->createOrder($payload); } catch (HttpException $exception) { $response = $exception->getResponse(); - if ($response->getStatusCode() === 400) { - // INVALID_REQUEST : - // - INVALID_ARRAY_MAX_ITEMS - // - INVALID_ARRAY_MIN_ITEMS - // - INVALID_COUNTRY_CODE - // - INVALID_PARAMETER_SYNTAX - // - INVALID_STRING_LENGTH - // - INVALID_PARAMETER_VALUE - // - MISSING_REQUIRED_PARAMETER - // - NOT_SUPPORTED - // - PAYPAL_REQUEST_ID_REQUIRED - // - MALFORMED_REQUEST_JSON - } - if ($response->getStatusCode() === 401) { - // NOT_AUTHORIZED - // - PERMISSION_DENIED - // - PERMISSION_DENIED_FOR_DONATION_ITEMS - // - MALFORMED_REQUEST - } - if ($response->getStatusCode() === 422) { - // UNPROCESSABLE_ENTITY - // - AMOUNT_MISMATCH - // - BILLING_ADDRESS_INVALID - // - CANNOT_BE_NEGATIVE - // - CANNOT_BE_ZERO_OR_NEGATIVE - // - CARD_EXPIRED - // - CITY_REQUIRED - // - DECIMAL_PRECISION - // - DONATION_ITEMS_NOT_SUPPORTED - // - DUPLICATE_REFERENCE_ID - // - INVALID_CURRENCY_CODE - // - INVALID_PAYER_ID - // - ITEM_TOTAL_MISMATCH - // - ITEM_TOTAL_REQUIRED - // - MAX_VALUE_EXCEEDED - // - MISSING_PICKUP_ADDRESS - // - MULTI_CURRENCY_ORDER - // - MULTIPLE_ITEM_CATEGORIES - // - MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED - // - MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED - // - PAYEE_ACCOUNT_INVALID - // - PAYEE_ACCOUNT_LOCKED_OR_CLOSED - // - PAYEE_ACCOUNT_RESTRICTED - // - REFERENCE_ID_REQUIRED - // - PAYMENT_SOURCE_CANNOT_BE_USED - // - PAYMENT_SOURCE_DECLINED_BY_PROCESSOR - // - PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED - // - POSTAL_CODE_REQUIRED - // - SHIPPING_ADDRESS_INVALID - // - TAX_TOTAL_MISMATCH - // - TAX_TOTAL_REQUIRED - // - UNSUPPORTED_INTENT - // - UNSUPPORTED_PAYMENT_INSTRUCTION - // - SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT - // - UNSUPPORTED_SHIPPING_TYPE - // - SHIPPING_OPTION_NOT_SELECTED - // - SHIPPING_OPTIONS_NOT_SUPPORTED - // - MULTIPLE_SHIPPING_OPTION_SELECTED - // - PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH - // - CARD_CLOSED - // - ORDER_CANNOT_BE_SAVED - // - SAVE_ORDER_NOT_SUPPORTED - // - PUI_DUPLICATE_ORDER + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + switch ($response->getStatusCode()) { + case 400: + switch ($errorMsg) { + case 'INVALID_ARRAY_MAX_ITEMS': + throw new InvalidRequestException('The number of items in an array parameter is too large', InvalidRequestException::INVALID_ARRAY_MAX_ITEMS); + case 'INVALID_ARRAY_MIN_ITEMS': + throw new InvalidRequestException('The number of items in an array parameter is too small', InvalidRequestException::INVALID_ARRAY_MIN_ITEMS); + case 'INVALID_COUNTRY_CODE': + throw new InvalidRequestException('Country code is invalid', InvalidRequestException::INVALID_COUNTRY_CODE); + case 'INVALID_PARAMETER_SYNTAX': + throw new InvalidRequestException('The value of a field does not conform to the expected format', InvalidRequestException::INVALID_PARAMETER_SYNTAX); + case 'INVALID_STRING_LENGTH': + throw new InvalidRequestException('The value of a field is either too short or too long', InvalidRequestException::INVALID_STRING_LENGTH); + case 'INVALID_PARAMETER_VALUE': + throw new InvalidRequestException('A parameter value is not valid', InvalidRequestException::INVALID_PARAMETER_VALUE); + case 'MISSING_REQUIRED_PARAMETER': + throw new InvalidRequestException('A required parameter is missing', InvalidRequestException::MISSING_REQUIRED_PARAMETER); + case 'NOT_SUPPORTED': + throw new InvalidRequestException('A field used is not currently supported', InvalidRequestException::NOT_SUPPORTED); + case 'PAYPAL_REQUEST_ID_REQUIRED': + throw new InvalidRequestException('A PayPal-Request-Id is required if you are trying to process payment for an Order', InvalidRequestException::PAYPAL_REQUEST_ID_REQUIRED); + case 'MALFORMED_REQUEST_JSON': + throw new InvalidRequestException('The request JSON is not well formed', InvalidRequestException::MALFORMED_REQUEST_JSON); + default: + throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); + } + case 401: + switch ($errorMsg) { + case 'PERMISSION_DENIED': + throw new NotAuthorizedException('You do not have permission to access or perform operations on this resource', NotAuthorizedException::PERMISSION_DENIED); + case 'PERMISSION_DENIED_FOR_DONATION_ITEMS': + throw new NotAuthorizedException('The payee have not been granted appropriate permissions to send items.category as DONATION', NotAuthorizedException::PERMISSION_DENIED_FOR_DONATION_ITEMS); + case 'MALFORMED_REQUEST': + throw new NotAuthorizedException('You have sent a request that PayPal server could not understand', NotAuthorizedException::MALFORMED_REQUEST); + default: + throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); + } + case 422: + switch ($errorMsg) { + case 'AMOUNT_MISMATCH': + throw new UnprocessableEntityException('Total amount mismatch with the breakdown', UnprocessableEntityException::AMOUNT_MISMATCH); + case 'BILLING_ADDRESS_INVALID': + throw new UnprocessableEntityException('Provided billing address is invalid', UnprocessableEntityException::BILLING_ADDRESS_INVALID); + case 'CANNOT_BE_NEGATIVE': + throw new UnprocessableEntityException('Currency must be greater than or equal to zero', UnprocessableEntityException::CANNOT_BE_NEGATIVE); + case 'CANNOT_BE_ZERO_OR_NEGATIVE': + throw new UnprocessableEntityException('Currency must be greater than zero', UnprocessableEntityException::CANNOT_BE_ZERO_OR_NEGATIVE); + case 'CARD_EXPIRED': + throw new UnprocessableEntityException('The payment card provided is expired', UnprocessableEntityException::CARD_EXPIRED); + case 'CITY_REQUIRED': + throw new UnprocessableEntityException('The specified country requires a city in address.admin_area_2', UnprocessableEntityException::CITY_REQUIRED); + case 'DECIMAL_PRECISION': + throw new UnprocessableEntityException('If the currency supports decimals, only two decimal places are supported', UnprocessableEntityException::DECIMAL_PRECISION); + case 'DONATION_ITEMS_NOT_SUPPORTED': + throw new UnprocessableEntityException('If purchase_unit has DONATION as the items.category, then the order can at most have one purchase_unit', UnprocessableEntityException::DONATION_ITEMS_NOT_SUPPORTED); + case 'DUPLICATE_REFERENCE_ID': + throw new UnprocessableEntityException('The reference_id must be unique', UnprocessableEntityException::DUPLICATE_REFERENCE_ID); + case 'INVALID_CURRENCY_CODE': + throw new UnprocessableEntityException('Currency code is invalid or is not currently supported', UnprocessableEntityException::INVALID_CURRENCY_CODE); + case 'INVALID_PAYER_ID': + throw new UnprocessableEntityException('The payer ID is not valid', UnprocessableEntityException::INVALID_PAYER_ID); + case 'ITEM_TOTAL_MISMATCH': + throw new UnprocessableEntityException('Should equal sum of unit_amount * quantity across all items for a given purchase_unit', UnprocessableEntityException::ITEM_TOTAL_MISMATCH); + case 'ITEM_TOTAL_REQUIRED': + throw new UnprocessableEntityException('If item details are specified, items.unit_amount, items.quantity and amount.breakdown.item_total are required', UnprocessableEntityException::ITEM_TOTAL_REQUIRED); + case 'MAX_VALUE_EXCEEDED': + throw new UnprocessableEntityException('Should be less than or equal to 9999999.99', UnprocessableEntityException::MAX_VALUE_EXCEEDED); + case 'MISSING_PICKUP_ADDRESS': + throw new UnprocessableEntityException('A pickup address (shipping.address) is required for the provided shipping.type', UnprocessableEntityException::MISSING_PICKUP_ADDRESS); + case 'MULTI_CURRENCY_ORDER': + throw new UnprocessableEntityException('Multiple differing values of currency_code are not supported', UnprocessableEntityException::MULTI_CURRENCY_ORDER); + case 'MULTIPLE_ITEM_CATEGORIES': + throw new UnprocessableEntityException('For a given purchase unit, items.category as DONATION cannot be combined with items with either PHYSICAL_GOODS or DIGITAL_GOODS', UnprocessableEntityException::MULTIPLE_ITEM_CATEGORIES); + case 'MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED': + throw new UnprocessableEntityException('Multiple shipping addresses are not supported', UnprocessableEntityException::MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED); + case 'MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED': + throw new UnprocessableEntityException('Different shipping.type are not supported across purchase units', UnprocessableEntityException::MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED); + case 'PAYEE_ACCOUNT_INVALID': + throw new UnprocessableEntityException('Mismatch between request payeeId and payeeEmail', UnprocessableEntityException::PAYEE_ACCOUNT_INVALID); + case 'PAYEE_ACCOUNT_LOCKED_OR_CLOSED': + throw new UnprocessableEntityException('The merchant account is locked or closed', UnprocessableEntityException::PAYEE_ACCOUNT_LOCKED_OR_CLOSED); + case 'PAYEE_ACCOUNT_RESTRICTED': + throw new UnprocessableEntityException('The merchant account is restricted', UnprocessableEntityException::PAYEE_ACCOUNT_RESTRICTED); + case 'REFERENCE_ID_REQUIRED': + throw new UnprocessableEntityException('The reference_id is required for each purchase_unit', UnprocessableEntityException::REFERENCE_ID_REQUIRED); + case 'PAYMENT_SOURCE_CANNOT_BE_USED': + throw new UnprocessableEntityException('The provided payment source cannot be used to pay for the order', UnprocessableEntityException::PAYMENT_SOURCE_CANNOT_BE_USED); + case 'PAYMENT_SOURCE_DECLINED_BY_PROCESSOR': + throw new UnprocessableEntityException('The provided payment source is declined by the processor', UnprocessableEntityException::PAYMENT_SOURCE_DECLINED_BY_PROCESSOR); + case 'PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED': + throw new UnprocessableEntityException('The provided payment source is declined by the processor', UnprocessableEntityException::PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED); + case 'POSTAL_CODE_REQUIRED': + throw new UnprocessableEntityException('The specified country requires a postal code', UnprocessableEntityException::POSTAL_CODE_REQUIRED); + case 'SHIPPING_ADDRESS_INVALID': + throw new UnprocessableEntityException('Provided shipping address is invalid', UnprocessableEntityException::SHIPPING_ADDRESS_INVALID); + case 'TAX_TOTAL_MISMATCH': + throw new UnprocessableEntityException('Should equal sum of tax * quantity across all items for a given purchase unit', UnprocessableEntityException::TAX_TOTAL_MISMATCH); + case 'TAX_TOTAL_REQUIRED': + throw new UnprocessableEntityException('If item details are specified, items.tax_total, items.quantity, and amount.breakdown.tax_total are required', UnprocessableEntityException::TAX_TOTAL_REQUIRED); + case 'UNSUPPORTED_INTENT': + throw new UnprocessableEntityException('The intent AUTHORIZE is not supported for multiple purchase units', UnprocessableEntityException::UNSUPPORTED_INTENT); + case 'UNSUPPORTED_PAYMENT_INSTRUCTION': + throw new UnprocessableEntityException('You must provide the payment instruction when you capture an authorized payment using intent AUTHORIZE', UnprocessableEntityException::UNSUPPORTED_PAYMENT_INSTRUCTION); + case 'SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT': + throw new UnprocessableEntityException('PayPal account is not setup to be able to support a shipping.type PICKUP_IN_PERSON', UnprocessableEntityException::SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT); + case 'UNSUPPORTED_SHIPPING_TYPE': + throw new UnprocessableEntityException('The provided shipping.type is only supported for application_context.shipping_preference SET_PROVIDED_ADDRESS or NO_SHIPPING', UnprocessableEntityException::UNSUPPORTED_SHIPPING_TYPE); + case 'SHIPPING_OPTION_NOT_SELECTED': + throw new UnprocessableEntityException('At least one of the shipping.option should be set to selected = true', UnprocessableEntityException::SHIPPING_OPTION_NOT_SELECTED); + case 'SHIPPING_OPTIONS_NOT_SUPPORTED': + throw new UnprocessableEntityException('Shipping options are not supported when application_context.shipping_preference is set to NO_SHIPPING or SET_PROVIDED_ADDRESS', UnprocessableEntityException::SHIPPING_OPTIONS_NOT_SUPPORTED); + case 'MULTIPLE_SHIPPING_OPTION_SELECTED': + throw new UnprocessableEntityException('Only one shipping.option can be set to selected = true', UnprocessableEntityException::MULTIPLE_SHIPPING_OPTION_SELECTED); + case 'PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH': + throw new UnprocessableEntityException('The amount provided in the preferred shipping option should match the amount provided in amount breakdown', UnprocessableEntityException::PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH); + case 'CARD_CLOSED': + throw new UnprocessableEntityException('The card is closed with the issuer', UnprocessableEntityException::CARD_CLOSED); + case 'ORDER_CANNOT_BE_SAVED': + throw new UnprocessableEntityException('The option to save an order is only available if the intent is AUTHORIZE and processing_instruction uses one of the ORDER_SAVED options', UnprocessableEntityException::ORDER_CANNOT_BE_SAVED); + case 'SAVE_ORDER_NOT_SUPPORTED': + throw new UnprocessableEntityException('PayPal account is setup in a way that does not allow it to be used for saving the order', UnprocessableEntityException::SAVE_ORDER_NOT_SUPPORTED); + case 'PUI_DUPLICATE_ORDER': + throw new UnprocessableEntityException('A Pay Upon Invoice order with the same payload has already been successfully processed in the last few seconds', UnprocessableEntityException::PUI_DUPLICATE_ORDER); + default: + throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); + } } } } @@ -192,4 +259,18 @@ public function getIdentityToken($merchantId) return $response; } } + + /** + * @param string $body + * + * @return string + */ + private function getErrorMessage($body) + { + $body = json_decode($body, true); + if ($body['details'][0]['issue']) return $body['details'][0]['issue']; + if ($body['name']) return $body['name']; + if ($body['error']) return $body['error']; + return ''; + } } diff --git a/src/DTO/Orders/CreatePayPalOrderRequestInterface.php b/src/DTO/Orders/CreatePayPalOrderRequestInterface.php new file mode 100644 index 000000000..62d8fbef8 --- /dev/null +++ b/src/DTO/Orders/CreatePayPalOrderRequestInterface.php @@ -0,0 +1,36 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\DTO\Orders; + +interface CreatePayPalOrderRequestInterface +{ + public function getIntent(); + + public function setIntent($intent); + + public function getPurchaseUnits(); + + public function setPurchaseUnits(array $purchase_units); + + public function getPaymentSource(); + + public function setPaymentSource(PaymentSourceRequest $payment_source); +} diff --git a/src/Exception/InvalidRequestException.php b/src/Exception/InvalidRequestException.php new file mode 100644 index 000000000..7376908d3 --- /dev/null +++ b/src/Exception/InvalidRequestException.php @@ -0,0 +1,36 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Exception; + +class InvalidRequestException extends PsCheckoutException +{ + const UNKNOWN = 0; + const INVALID_ARRAY_MAX_ITEMS = 1; + const INVALID_ARRAY_MIN_ITEMS = 2; + const INVALID_COUNTRY_CODE = 3; + const INVALID_PARAMETER_SYNTAX = 4; + const INVALID_STRING_LENGTH = 5; + const INVALID_PARAMETER_VALUE = 6; + const MISSING_REQUIRED_PARAMETER = 7; + const NOT_SUPPORTED = 8; + const PAYPAL_REQUEST_ID_REQUIRED = 9; + const MALFORMED_REQUEST_JSON = 10; +} diff --git a/src/Exception/NotAuthorizedException.php b/src/Exception/NotAuthorizedException.php new file mode 100644 index 000000000..415521a02 --- /dev/null +++ b/src/Exception/NotAuthorizedException.php @@ -0,0 +1,31 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Exception; + +class NotAuthorizedException extends PsCheckoutException +{ + const UNKNOWN = 0; + const PERMISSION_DENIED = 1; + const PERMISSION_DENIED_FOR_DONATION_ITEMS = 2; + const MALFORMED_REQUEST = 3; + const INVALID_TOKEN = 4; + const INVALID_CLIENT = 5; +} diff --git a/src/Exception/UnprocessableEntityException.php b/src/Exception/UnprocessableEntityException.php new file mode 100644 index 000000000..cc78b9bca --- /dev/null +++ b/src/Exception/UnprocessableEntityException.php @@ -0,0 +1,68 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Exception; + +class UnprocessableEntityException extends PsCheckoutException +{ + const UNKNOWN = 0; + const AMOUNT_MISMATCH = 1; + const BILLING_ADDRESS_INVALID = 2; + const CANNOT_BE_NEGATIVE = 3; + const CANNOT_BE_ZERO_OR_NEGATIVE = 4; + const CARD_EXPIRED = 5; + const CITY_REQUIRED = 6; + const DECIMAL_PRECISION = 7; + const DONATION_ITEMS_NOT_SUPPORTED = 8; + const DUPLICATE_REFERENCE_ID = 9; + const INVALID_CURRENCY_CODE = 10; + const INVALID_PAYER_ID = 11; + const ITEM_TOTAL_MISMATCH = 12; + const ITEM_TOTAL_REQUIRED = 13; + const MAX_VALUE_EXCEEDED = 14; + const MISSING_PICKUP_ADDRESS = 15; + const MULTI_CURRENCY_ORDER = 16; + const MULTIPLE_ITEM_CATEGORIES = 17; + const MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED = 18; + const MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED = 19; + const PAYEE_ACCOUNT_INVALID = 20; + const PAYEE_ACCOUNT_LOCKED_OR_CLOSED = 21; + const PAYEE_ACCOUNT_RESTRICTED = 22; + const REFERENCE_ID_REQUIRED = 23; + const PAYMENT_SOURCE_CANNOT_BE_USED = 24; + const PAYMENT_SOURCE_DECLINED_BY_PROCESSOR = 25; + const PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED = 26; + const POSTAL_CODE_REQUIRED = 27; + const SHIPPING_ADDRESS_INVALID = 28; + const TAX_TOTAL_MISMATCH = 29; + const TAX_TOTAL_REQUIRED = 30; + const UNSUPPORTED_INTENT = 31; + const UNSUPPORTED_PAYMENT_INSTRUCTION = 32; + const SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT = 33; + const UNSUPPORTED_SHIPPING_TYPE = 34; + const SHIPPING_OPTION_NOT_SELECTED = 35; + const SHIPPING_OPTIONS_NOT_SUPPORTED = 36; + const MULTIPLE_SHIPPING_OPTION_SELECTED = 37; + const PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH = 38; + const CARD_CLOSED = 39; + const ORDER_CANNOT_BE_SAVED = 40; + const SAVE_ORDER_NOT_SUPPORTED = 41; + const PUI_DUPLICATE_ORDER = 42; +} diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php index 491a1e1a7..6ce3c76db 100644 --- a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php +++ b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php @@ -20,7 +20,7 @@ namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; -class CreatePayPalOrderRequest +class CreatePayPalOrderRequest implements CreatePayPalOrderRequestInterface { /** * @var string diff --git a/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php new file mode 100644 index 000000000..6101f2724 --- /dev/null +++ b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php @@ -0,0 +1,219 @@ +testErrorsCreateOrder(400, $errorName, $errorCode); + } + + /** + * @dataProvider notAuthorizedErrorsProvider + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException + */ + public function testNotAuthorizedErrorsCreateOrder($errorName, $errorCode) + { + $this->testErrorsCreateOrder(401, $errorName, $errorCode); + } + + /** + * @dataProvider unprocessableEntityErrorsProvider + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException + */ + public function testUnprocessableEntityErrorsCreateOrder($errorName, $errorCode) + { + $this->testErrorsCreateOrder(422, $errorName, $errorCode); + } + + /** + * @param int $statusCode + * @param string $errorName + * @param int $errorCode + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException + */ + private function testErrorsCreateOrder($statusCode, $errorName, $errorCode) + { + switch ($statusCode) { + case 400: + $error = $this->getInvalidRequestError($errorName); + break; + case 401: + $error = $this->getNotAuthorizedError($errorName); + break; + case 422: + default: + $error = $this->getUnprocessableEntityError($errorName); + break; + } + + $requestMock = $this->createMock(RequestInterface::class); + $createRequestMock = $this->createMock(CreatePayPalOrderRequestInterface::class); + + $streamMock = $this->createMock(StreamInterface::class); + $streamMock->method('getContents')->willReturn(json_encode($error)); + + $responseMock = $this->createMock(ResponseInterface::class); + $responseMock->method('getStatusCode')->willReturn($statusCode); + $responseMock->method('getBody')->willReturn($streamMock); + + $clientMock = $this->createMock(PayPalOrderHttpClient::class); + $clientMock->method('createOrder')->willThrowException(new HttpException('An error occurred', $requestMock, $responseMock)); + + $this->expectExceptionCode($errorCode); + $paymentService = new PaymentService($clientMock); + $paymentService->createOrder($createRequestMock); + } + + private function getInvalidRequestError($issueError) + { + return [ + "name" => "INVALID_REQUEST", + "message" => "Request is not well-formed, syntactically incorrect, or violates schema.", + "debug_id" => "b6b9a374802ea", + "details" => [ + [ + "field" => "", + "value" => "", + "location" => "body", + "issue" => $issueError, + "description" => "" + ] + ], + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE", + "rel" => "information_link", + "encType" => "application/json" + ] + ] + ]; + } + + private function getNotAuthorizedError($issueError) + { + return [ + "name" => $issueError, + "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/overview/#error", + "rel" => "information_link" + ] + ] + ]; + } + + private function getUnprocessableEntityError($issueError) + { + return [ + "name" => "UNPROCESSABLE_ENTITY", + "details" => [ + [ + "field" => "", + "value" => "", + "issue" => $issueError, + "description" => "" + ] + ], + "message" => "The requested action could not be performed, semantically incorrect, or failed business validation.", + "debug_id" => "c9a75b43fc807", + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED", + "rel" => "information_link", + "method" => "GET" + ] + ] + ]; + } + + public function invalidRequestErrorsProvider() + { + return [ + ['INVALID_ARRAY_MAX_ITEMS', InvalidRequestException::INVALID_ARRAY_MAX_ITEMS], + ['INVALID_ARRAY_MIN_ITEMS', InvalidRequestException::INVALID_ARRAY_MIN_ITEMS], + ['INVALID_COUNTRY_CODE', InvalidRequestException::INVALID_COUNTRY_CODE], + ['INVALID_PARAMETER_SYNTAX', InvalidRequestException::INVALID_PARAMETER_SYNTAX], + ['INVALID_STRING_LENGTH', InvalidRequestException::INVALID_STRING_LENGTH], + ['INVALID_PARAMETER_VALUE', InvalidRequestException::INVALID_PARAMETER_VALUE], + ['MISSING_REQUIRED_PARAMETER', InvalidRequestException::MISSING_REQUIRED_PARAMETER], + ['NOT_SUPPORTED', InvalidRequestException::NOT_SUPPORTED], + ['PAYPAL_REQUEST_ID_REQUIRED', InvalidRequestException::PAYPAL_REQUEST_ID_REQUIRED], + ['MALFORMED_REQUEST_JSON', InvalidRequestException::MALFORMED_REQUEST_JSON] + ]; + } + + public function notAuthorizedErrorsProvider() + { + return [ + ['PERMISSION_DENIED', NotAuthorizedException::PERMISSION_DENIED], + ['PERMISSION_DENIED_FOR_DONATION_ITEMS', NotAuthorizedException::PERMISSION_DENIED_FOR_DONATION_ITEMS], + ['MALFORMED_REQUEST', NotAuthorizedException::MALFORMED_REQUEST] + ]; + } + + public function unprocessableEntityErrorsProvider() { + return [ + ['AMOUNT_MISMATCH', UnprocessableEntityException::AMOUNT_MISMATCH], + ['BILLING_ADDRESS_INVALID', UnprocessableEntityException::BILLING_ADDRESS_INVALID], + ['CANNOT_BE_NEGATIVE', UnprocessableEntityException::CANNOT_BE_NEGATIVE], + ['CANNOT_BE_ZERO_OR_NEGATIVE', UnprocessableEntityException::CANNOT_BE_ZERO_OR_NEGATIVE], + ['CARD_EXPIRED', UnprocessableEntityException::CARD_EXPIRED], + ['CITY_REQUIRED', UnprocessableEntityException::CITY_REQUIRED], + ['DECIMAL_PRECISION', UnprocessableEntityException::DECIMAL_PRECISION], + ['DONATION_ITEMS_NOT_SUPPORTED', UnprocessableEntityException::DONATION_ITEMS_NOT_SUPPORTED], + ['DUPLICATE_REFERENCE_ID', UnprocessableEntityException::DUPLICATE_REFERENCE_ID], + ['INVALID_CURRENCY_CODE', UnprocessableEntityException::INVALID_CURRENCY_CODE], + ['INVALID_PAYER_ID', UnprocessableEntityException::INVALID_PAYER_ID], + ['ITEM_TOTAL_MISMATCH', UnprocessableEntityException::ITEM_TOTAL_MISMATCH], + ['ITEM_TOTAL_REQUIRED', UnprocessableEntityException::ITEM_TOTAL_REQUIRED], + ['MAX_VALUE_EXCEEDED', UnprocessableEntityException::MAX_VALUE_EXCEEDED], + ['MISSING_PICKUP_ADDRESS', UnprocessableEntityException::MISSING_PICKUP_ADDRESS], + ['MULTI_CURRENCY_ORDER', UnprocessableEntityException::MULTI_CURRENCY_ORDER], + ['MULTIPLE_ITEM_CATEGORIES', UnprocessableEntityException::MULTIPLE_ITEM_CATEGORIES], + ['MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED', UnprocessableEntityException::MULTIPLE_SHIPPING_ADDRESS_NOT_SUPPORTED], + ['MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED', UnprocessableEntityException::MULTIPLE_SHIPPING_TYPE_NOT_SUPPORTED], + ['PAYEE_ACCOUNT_INVALID', UnprocessableEntityException::PAYEE_ACCOUNT_INVALID], + ['PAYEE_ACCOUNT_LOCKED_OR_CLOSED', UnprocessableEntityException::PAYEE_ACCOUNT_LOCKED_OR_CLOSED], + ['PAYEE_ACCOUNT_RESTRICTED', UnprocessableEntityException::PAYEE_ACCOUNT_RESTRICTED], + ['REFERENCE_ID_REQUIRED', UnprocessableEntityException::REFERENCE_ID_REQUIRED], + ['PAYMENT_SOURCE_CANNOT_BE_USED', UnprocessableEntityException::PAYMENT_SOURCE_CANNOT_BE_USED], + ['PAYMENT_SOURCE_DECLINED_BY_PROCESSOR', UnprocessableEntityException::PAYMENT_SOURCE_DECLINED_BY_PROCESSOR], + ['PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED', UnprocessableEntityException::PAYMENT_SOURCE_INFO_CANNOT_BE_VERIFIED], + ['POSTAL_CODE_REQUIRED', UnprocessableEntityException::POSTAL_CODE_REQUIRED], + ['SHIPPING_ADDRESS_INVALID', UnprocessableEntityException::SHIPPING_ADDRESS_INVALID], + ['TAX_TOTAL_MISMATCH', UnprocessableEntityException::TAX_TOTAL_MISMATCH], + ['TAX_TOTAL_REQUIRED', UnprocessableEntityException::TAX_TOTAL_REQUIRED], + ['UNSUPPORTED_INTENT', UnprocessableEntityException::UNSUPPORTED_INTENT], + ['UNSUPPORTED_PAYMENT_INSTRUCTION', UnprocessableEntityException::UNSUPPORTED_PAYMENT_INSTRUCTION], + ['SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT', UnprocessableEntityException::SHIPPING_TYPE_NOT_SUPPORTED_FOR_CLIENT], + ['UNSUPPORTED_SHIPPING_TYPE', UnprocessableEntityException::UNSUPPORTED_SHIPPING_TYPE], + ['SHIPPING_OPTION_NOT_SELECTED', UnprocessableEntityException::SHIPPING_OPTION_NOT_SELECTED], + ['SHIPPING_OPTIONS_NOT_SUPPORTED', UnprocessableEntityException::SHIPPING_OPTIONS_NOT_SUPPORTED], + ['MULTIPLE_SHIPPING_OPTION_SELECTED', UnprocessableEntityException::MULTIPLE_SHIPPING_OPTION_SELECTED], + ['PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH', UnprocessableEntityException::PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH], + ['CARD_CLOSED', UnprocessableEntityException::CARD_CLOSED], + ['ORDER_CANNOT_BE_SAVED', UnprocessableEntityException::ORDER_CANNOT_BE_SAVED], + ['SAVE_ORDER_NOT_SUPPORTED', UnprocessableEntityException::SAVE_ORDER_NOT_SUPPORTED], + ['PUI_DUPLICATE_ORDER', UnprocessableEntityException::PUI_DUPLICATE_ORDER] + ]; + } +} From 175ae2ded6dd282e66b637fb3c16040980cbe058 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 19 Feb 2024 13:19:20 +0200 Subject: [PATCH 17/26] Renamed service names --- config/common.yml | 24 ++++++++++--------- .../CheckoutEventSubscriber.php | 6 ++--- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/config/common.yml b/config/common.yml index 6ca7f6a0a..04b072cb9 100644 --- a/config/common.yml +++ b/config/common.yml @@ -482,32 +482,34 @@ services: - "@ps_checkout.logger" - "@ps_checkout.logger.configuration" - ps_checkout.event.subscriber.checkout: + PrestaShop\Module\PrestashopCheckout\Checkout\EventSubscriber\CheckoutEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\Checkout\EventSubscriber\CheckoutEventSubscriber' public: true arguments: - "@ps_checkout.module" + - '@PrestaShop\Module\PrestashopCheckout\Checkout\CheckoutChecker' + - '@ps_checkout.bus.command' - ps_checkout.event.subscriber.order: + PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber\OrderEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber\OrderEventSubscriber' public: true arguments: - "@ps_checkout.module" - "@ps_checkout.repository.pscheckoutcart" - ps_checkout.event.subscriber.paypal.order: + PrestaShop\Module\PrestashopCheckout\PayPal\Order\EventSubscriber\PayPalOrderEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\EventSubscriber\PayPalOrderEventSubscriber' public: true arguments: - "@ps_checkout.module" - "@ps_checkout.repository.pscheckoutcart" - "@ps_checkout.cache.paypal.order" - - "@ps_checkout.checkout.checker" + - '@PrestaShop\Module\PrestashopCheckout\Checkout\CheckoutChecker' - "@ps_checkout.paypal.order.service.check_transition_paypal_order_status" - "@ps_checkout.order.state.service.order_state_mapper" - '@ps_checkout.paypal.configuration' - ps_checkout.event.subscriber.paypal.capture: + PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber' public: true arguments: @@ -532,12 +534,12 @@ services: factory: ["@ps_checkout.event.dispatcher.factory", "create"] arguments: - [ - "@ps_checkout.event.subscriber.checkout", - "@ps_checkout.event.subscriber.order", - "@ps_checkout.event.subscriber.paypal.order", - "@ps_checkout.event.subscriber.paypal.capture", + '@PrestaShop\Module\PrestashopCheckout\Checkout\EventSubscriber\CheckoutEventSubscriber', + '@PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber\OrderEventSubscriber', + '@PrestaShop\Module\PrestashopCheckout\PayPal\Order\EventSubscriber\PayPalOrderEventSubscriber', + '@PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber', '@PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Refund\EventSubscriber\PayPalRefundEventSubscriber' - ] + ] ps_checkout.event.dispatcher: class: 'PrestaShop\Module\PrestashopCheckout\Event\SymfonyEventDispatcherAdapter' @@ -709,7 +711,7 @@ services: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\CheckTransitionPayPalCaptureStatusService' public: true - ps_checkout.checkout.checker: + PrestaShop\Module\PrestashopCheckout\Checkout\CheckoutChecker: class: 'PrestaShop\Module\PrestashopCheckout\Checkout\CheckoutChecker' public: true arguments: diff --git a/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php b/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php index 1849b37a9..0c988524c 100644 --- a/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php +++ b/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php @@ -61,11 +61,11 @@ class CheckoutEventSubscriber implements EventSubscriberInterface /** * @param Ps_checkout $module */ - public function __construct(Ps_checkout $module) + public function __construct(Ps_checkout $module, CheckoutChecker $checkoutChecker, CommandBusInterface $commandBus) { $this->module = $module; - $this->checkoutChecker = $this->module->getService('ps_checkout.checkout.checker'); - $this->commandBus = $this->module->getService('ps_checkout.bus.command'); + $this->checkoutChecker = $checkoutChecker; + $this->commandBus = $commandBus; } /** From 140b092d50cd8760188383f2971f186fc8952ae9 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Mon, 19 Feb 2024 13:31:07 +0200 Subject: [PATCH 18/26] Fixed interface and tests --- src/Api/Payment/PaymentService.php | 17 +++- .../CreatePayPalOrderRequestInterface.php | 11 +++ .../Order/DTO/CreatePayPalOrderRequest.php | 2 + .../PaymentServiceCreateOrderTest.php | 97 ++++++++++--------- 4 files changed, 78 insertions(+), 49 deletions(-) diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 6d90c2610..16e9c5f6a 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -42,7 +42,9 @@ public function __construct(PayPalOrderHttpClient $client) /** * @param CreatePayPalOrderRequestInterface $request + * * @return ResponseInterface|void + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ public function createOrder(CreatePayPalOrderRequestInterface $request) @@ -79,6 +81,7 @@ public function createOrder(CreatePayPalOrderRequestInterface $request) default: throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); } + // no break case 401: switch ($errorMsg) { case 'PERMISSION_DENIED': @@ -90,6 +93,7 @@ public function createOrder(CreatePayPalOrderRequestInterface $request) default: throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); } + // no break case 422: switch ($errorMsg) { case 'AMOUNT_MISMATCH': @@ -268,9 +272,16 @@ public function getIdentityToken($merchantId) private function getErrorMessage($body) { $body = json_decode($body, true); - if ($body['details'][0]['issue']) return $body['details'][0]['issue']; - if ($body['name']) return $body['name']; - if ($body['error']) return $body['error']; + if (isset($body['details'][0]['issue']) && $body['details'][0]['issue']) { + return $body['details'][0]['issue']; + } + if ($body['name']) { + return $body['name']; + } + if ($body['error']) { + return $body['error']; + } + return ''; } } diff --git a/src/DTO/Orders/CreatePayPalOrderRequestInterface.php b/src/DTO/Orders/CreatePayPalOrderRequestInterface.php index 62d8fbef8..d8214ed1b 100644 --- a/src/DTO/Orders/CreatePayPalOrderRequestInterface.php +++ b/src/DTO/Orders/CreatePayPalOrderRequestInterface.php @@ -20,6 +20,9 @@ namespace PrestaShop\Module\PrestashopCheckout\DTO\Orders; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ApplicationContextRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PaymentSourceRequest; + interface CreatePayPalOrderRequestInterface { public function getIntent(); @@ -33,4 +36,12 @@ public function setPurchaseUnits(array $purchase_units); public function getPaymentSource(); public function setPaymentSource(PaymentSourceRequest $payment_source); + + public function getApplicationContext(); + + public function setApplicationContext(ApplicationContextRequest $application_context); + + public function getProcessingInstruction(); + + public function setProcessingInstruction($processing_instruction); } diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php index 6ce3c76db..2c2fe973a 100644 --- a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php +++ b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php @@ -20,6 +20,8 @@ namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; +use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequestInterface; + class CreatePayPalOrderRequest implements CreatePayPalOrderRequestInterface { /** diff --git a/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php index 6101f2724..c494f6512 100644 --- a/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php +++ b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php @@ -18,38 +18,42 @@ class PaymentServiceCreateOrderTest extends TestCase { /** * @dataProvider invalidRequestErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ public function testInvalidRequestErrorsCreateOrder($errorName, $errorCode) { - $this->testErrorsCreateOrder(400, $errorName, $errorCode); + $this->handleTestErrorsCreateOrder(400, $errorName, $errorCode); } /** * @dataProvider notAuthorizedErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ public function testNotAuthorizedErrorsCreateOrder($errorName, $errorCode) { - $this->testErrorsCreateOrder(401, $errorName, $errorCode); + $this->handleTestErrorsCreateOrder(401, $errorName, $errorCode); } /** * @dataProvider unprocessableEntityErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ public function testUnprocessableEntityErrorsCreateOrder($errorName, $errorCode) { - $this->testErrorsCreateOrder(422, $errorName, $errorCode); + $this->handleTestErrorsCreateOrder(422, $errorName, $errorCode); } /** * @param int $statusCode * @param string $errorName * @param int $errorCode + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException */ - private function testErrorsCreateOrder($statusCode, $errorName, $errorCode) + private function handleTestErrorsCreateOrder($statusCode, $errorName, $errorCode) { switch ($statusCode) { case 400: @@ -85,63 +89,63 @@ private function testErrorsCreateOrder($statusCode, $errorName, $errorCode) private function getInvalidRequestError($issueError) { return [ - "name" => "INVALID_REQUEST", - "message" => "Request is not well-formed, syntactically incorrect, or violates schema.", - "debug_id" => "b6b9a374802ea", - "details" => [ + 'name' => 'INVALID_REQUEST', + 'message' => 'Request is not well-formed, syntactically incorrect, or violates schema.', + 'debug_id' => 'b6b9a374802ea', + 'details' => [ [ - "field" => "", - "value" => "", - "location" => "body", - "issue" => $issueError, - "description" => "" - ] + 'field' => '', + 'value' => '', + 'location' => 'body', + 'issue' => $issueError, + 'description' => '', + ], ], - "links" => [ + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE", - "rel" => "information_link", - "encType" => "application/json" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE', + 'rel' => 'information_link', + 'encType' => 'application/json', + ], + ], ]; } private function getNotAuthorizedError($issueError) { return [ - "name" => $issueError, - "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", - "links" => [ + 'name' => $issueError, + 'message' => 'Authentication failed due to invalid authentication credentials or a missing Authorization header.', + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/overview/#error", - "rel" => "information_link" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/overview/#error', + 'rel' => 'information_link', + ], + ], ]; } private function getUnprocessableEntityError($issueError) { return [ - "name" => "UNPROCESSABLE_ENTITY", - "details" => [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [ [ - "field" => "", - "value" => "", - "issue" => $issueError, - "description" => "" - ] + 'field' => '', + 'value' => '', + 'issue' => $issueError, + 'description' => '', + ], ], - "message" => "The requested action could not be performed, semantically incorrect, or failed business validation.", - "debug_id" => "c9a75b43fc807", - "links" => [ + 'message' => 'The requested action could not be performed, semantically incorrect, or failed business validation.', + 'debug_id' => 'c9a75b43fc807', + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED", - "rel" => "information_link", - "method" => "GET" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED', + 'rel' => 'information_link', + 'method' => 'GET', + ], + ], ]; } @@ -157,7 +161,7 @@ public function invalidRequestErrorsProvider() ['MISSING_REQUIRED_PARAMETER', InvalidRequestException::MISSING_REQUIRED_PARAMETER], ['NOT_SUPPORTED', InvalidRequestException::NOT_SUPPORTED], ['PAYPAL_REQUEST_ID_REQUIRED', InvalidRequestException::PAYPAL_REQUEST_ID_REQUIRED], - ['MALFORMED_REQUEST_JSON', InvalidRequestException::MALFORMED_REQUEST_JSON] + ['MALFORMED_REQUEST_JSON', InvalidRequestException::MALFORMED_REQUEST_JSON], ]; } @@ -166,11 +170,12 @@ public function notAuthorizedErrorsProvider() return [ ['PERMISSION_DENIED', NotAuthorizedException::PERMISSION_DENIED], ['PERMISSION_DENIED_FOR_DONATION_ITEMS', NotAuthorizedException::PERMISSION_DENIED_FOR_DONATION_ITEMS], - ['MALFORMED_REQUEST', NotAuthorizedException::MALFORMED_REQUEST] + ['MALFORMED_REQUEST', NotAuthorizedException::MALFORMED_REQUEST], ]; } - public function unprocessableEntityErrorsProvider() { + public function unprocessableEntityErrorsProvider() + { return [ ['AMOUNT_MISMATCH', UnprocessableEntityException::AMOUNT_MISMATCH], ['BILLING_ADDRESS_INVALID', UnprocessableEntityException::BILLING_ADDRESS_INVALID], @@ -213,7 +218,7 @@ public function unprocessableEntityErrorsProvider() { ['CARD_CLOSED', UnprocessableEntityException::CARD_CLOSED], ['ORDER_CANNOT_BE_SAVED', UnprocessableEntityException::ORDER_CANNOT_BE_SAVED], ['SAVE_ORDER_NOT_SUPPORTED', UnprocessableEntityException::SAVE_ORDER_NOT_SUPPORTED], - ['PUI_DUPLICATE_ORDER', UnprocessableEntityException::PUI_DUPLICATE_ORDER] + ['PUI_DUPLICATE_ORDER', UnprocessableEntityException::PUI_DUPLICATE_ORDER], ]; } } From 4652037a720a06e3d369d772644a7021fe80f176 Mon Sep 17 00:00:00 2001 From: Bastien Tafforeau Date: Fri, 23 Feb 2024 09:44:19 +0100 Subject: [PATCH 19/26] Handling more errors for PaymentService --- src/Api/Payment/PaymentService.php | 263 +++++++++++++++--- .../UpdatePayPalOrderRequestInterface.php | 25 ++ src/Exception/InvalidRequestException.php | 3 + src/Exception/NotAuthorizedException.php | 7 +- .../UnprocessableEntityException.php | 32 +++ .../PaymentServiceGetOrderTest.php | 88 ++++++ .../PaymentServiceUpdateOrderTest.php | 193 +++++++++++++ 7 files changed, 578 insertions(+), 33 deletions(-) create mode 100644 src/DTO/Orders/UpdatePayPalOrderRequestInterface.php create mode 100644 tests/Unit/PaymentService/PaymentServiceGetOrderTest.php create mode 100644 tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index 16e9c5f6a..cae0cf57d 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -23,8 +23,10 @@ use Http\Client\Exception\HttpException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequestInterface; +use PrestaShop\Module\PrestashopCheckout\DTO\Orders\UpdatePayPalOrderRequestInterface; use PrestaShop\Module\PrestashopCheckout\Exception\InvalidRequestException; use PrestaShop\Module\PrestashopCheckout\Exception\NotAuthorizedException; +use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; use PrestaShop\Module\PrestashopCheckout\Exception\UnprocessableEntityException; use Psr\Http\Message\ResponseInterface; @@ -43,9 +45,9 @@ public function __construct(PayPalOrderHttpClient $client) /** * @param CreatePayPalOrderRequestInterface $request * - * @return ResponseInterface|void + * @return ResponseInterface * - * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function createOrder(CreatePayPalOrderRequestInterface $request) { @@ -183,19 +185,103 @@ public function createOrder(CreatePayPalOrderRequestInterface $request) default: throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); } + default: + throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } } } - public function updateOrder(array $payload) + /** + * @param UpdatePayPalOrderRequestInterface $request + * @return ResponseInterface + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ + public function updateOrder(UpdatePayPalOrderRequestInterface $request) { - return $this->client->updateOrder($payload); + $payload = (array) $request; + try { + return $this->client->updateOrder($payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + switch ($response->getStatusCode()) { + case 400: + switch ($errorMsg) { + case 'FIELD_NOT_PATCHABLE': + throw new InvalidRequestException('Field cannot be patched', InvalidRequestException::FIELD_NOT_PATCHABLE); + case 'INVALID_ARRAY_MAX_ITEMS': + throw new InvalidRequestException('The number of items in an array parameter is too large', InvalidRequestException::INVALID_ARRAY_MAX_ITEMS); + case 'INVALID_PARAMETER_SYNTAX': + throw new InvalidRequestException('The value of a field does not conform to the expected format', InvalidRequestException::INVALID_PARAMETER_SYNTAX); + case 'INVALID_STRING_LENGTH': + throw new InvalidRequestException('The value of a field is either too short or too long', InvalidRequestException::INVALID_STRING_LENGTH); + case 'INVALID_PARAMETER_VALUE': + throw new InvalidRequestException('The value of a field is invalid', InvalidRequestException::INVALID_PARAMETER_VALUE); + case 'MISSING_REQUIRED_PARAMETER': + throw new InvalidRequestException('A required field or parameter is missing', InvalidRequestException::MISSING_REQUIRED_PARAMETER); + case 'AMOUNT_NOT_PATCHABLE': + throw new InvalidRequestException('The amount cannot be updated as the payer has chosen and approved a specific financing offer for a given amount', InvalidRequestException::AMOUNT_NOT_PATCHABLE); + case 'INVALID_PATCH_OPERATION': + throw new InvalidRequestException('The operation cannot be honored. Cannot add a already existing property nor remove a property that is not present', InvalidRequestException::INVALID_PATCH_OPERATION); + default: + throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); + } + case 401: + switch ($errorMsg) { + case 'PERMISSION_DENIED': + throw new NotAuthorizedException('You do not have permission to access or perform operations on this resource', NotAuthorizedException::PERMISSION_DENIED); + case 'PAYEE_ACCOUNT_NOT_SUPPORTED': + throw new NotAuthorizedException('Payee does not have an account', NotAuthorizedException::PAYEE_ACCOUNT_NOT_SUPPORTED); + case 'PAYEE_ACCOUNT_NOT_VERIFIED': + throw new NotAuthorizedException('Payee has not verified their account with PayPal', NotAuthorizedException::PAYEE_ACCOUNT_NOT_VERIFIED); + case 'PAYEE_NOT_CONSENTED': + throw new NotAuthorizedException('Payee does not have appropriate consent to allow the API caller to process this type of transaction on their behalf', NotAuthorizedException::PAYEE_NOT_CONSENTED); + default: + throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); + } + case 422: + switch ($errorMsg) { + case 'INVALID_JSON_POINTER_FORMAT': + throw new UnprocessableEntityException('Path should be a valid JSON Pointer that references a location within the request', UnprocessableEntityException::INVALID_JSON_POINTER_FORMAT); + case 'INVALID_PARAMETER': + throw new UnprocessableEntityException('Cannot be specified as part of the request', UnprocessableEntityException::INVALID_PARAMETER); + case 'NOT_PATCHABLE': + throw new UnprocessableEntityException('Cannot be patched', UnprocessableEntityException::NOT_PATCHABLE); + case 'UNSUPPORTED_PATCH_PARAMETER_VALUE': + throw new UnprocessableEntityException('The value specified for this field is not currently supported', UnprocessableEntityException::UNSUPPORTED_PATCH_PARAMETER_VALUE); + case 'PATCH_VALUE_REQUIRED': + throw new UnprocessableEntityException('Specify a value for the field being patched', UnprocessableEntityException::PATCH_VALUE_REQUIRED); + case 'PATCH_PATH_REQUIRED': + throw new UnprocessableEntityException('Specify a value for the field in which the operation needs to be performed', UnprocessableEntityException::PATCH_PATH_REQUIRED); + case 'REFERENCE_ID_NOT_FOUND': + throw new UnprocessableEntityException('Filter expression value is incorrect. Check the value of the reference_id', UnprocessableEntityException::REFERENCE_ID_NOT_FOUND); + case 'MULTI_CURRENCY_ORDER': + throw new UnprocessableEntityException('Multiple differing values of currency_code are not supported', UnprocessableEntityException::MULTI_CURRENCY_ORDER); + case 'SHIPPING_OPTION_NOT_SELECTED': + throw new UnprocessableEntityException('At least one of the shipping.option should be set to selected = true', UnprocessableEntityException::SHIPPING_OPTION_NOT_SELECTED); + case 'SHIPPING_OPTIONS_NOT_SUPPORTED': + throw new UnprocessableEntityException('Shipping options are not supported when application_context.shipping_preference is set to NO_SHIPPING or SET_PROVIDED_ADDRESS', UnprocessableEntityException::SHIPPING_OPTIONS_NOT_SUPPORTED); + case 'MULTIPLE_SHIPPING_OPTION_SELECTED': + throw new UnprocessableEntityException('Only one shipping.option can be set to selected = true', UnprocessableEntityException::MULTIPLE_SHIPPING_OPTION_SELECTED); + case 'ORDER_ALREADY_COMPLETED': + throw new UnprocessableEntityException('The order cannot be patched after it is completed', UnprocessableEntityException::ORDER_ALREADY_COMPLETED); + case 'PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH': + throw new UnprocessableEntityException('The amount provided in the preferred shipping option should match the amount provided in amount breakdown', UnprocessableEntityException::PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH); + default: + throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); + } + default: + throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); + } + } } /** * @param string $orderId * * @return ResponseInterface + * + * @throws NotAuthorizedException|PsCheckoutException */ public function getOrder($orderId) { @@ -203,13 +289,33 @@ public function getOrder($orderId) 'orderId' => $orderId, ]; - return $this->client->fetchOrder($payload); + try { + return $this->client->fetchOrder($payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + switch ($response->getStatusCode()) { + case 401: + switch ($errorMsg) { + case 'PERMISSION_DENIED': + throw new NotAuthorizedException('You do not have permission to access or perform operations on this resource', NotAuthorizedException::PERMISSION_DENIED); + case 'invalid_token': + throw new NotAuthorizedException('Token signature verification failed', NotAuthorizedException::INVALID_TOKEN); + default: + throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); + } + default: + throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); + } + } } /** * @param array{funding_source: string, order_id: string, merchant_id: string} $data * * @return ResponseInterface + * + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function captureOrder(array $data) { @@ -221,12 +327,126 @@ public function captureOrder(array $data) ], ]; - return $this->client->captureOrder($payload); + try { + return $this->client->captureOrder($payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + switch ($response->getStatusCode()) { + case 400: + switch ($errorMsg) { + case 'INVALID_PARAMETER_VALUE': + throw new InvalidRequestException('The value of a field is invalid', InvalidRequestException::INVALID_PARAMETER_VALUE); + case 'MISSING_REQUIRED_PARAMETER': + throw new InvalidRequestException('A required field or parameter is missing', InvalidRequestException::MISSING_REQUIRED_PARAMETER); + case 'INVALID_STRING_LENGTH': + throw new InvalidRequestException('The value of a field is either too short or too long', InvalidRequestException::INVALID_STRING_LENGTH); + default: + throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); + } + case 401: + switch ($errorMsg) { + case 'CONSENT_NEEDED': + throw new NotAuthorizedException('Payee consent needed', NotAuthorizedException::CONSENT_NEEDED); + case 'PERMISSION_DENIED': + throw new NotAuthorizedException('You do not have permission to access or perform operations on this resource', NotAuthorizedException::PERMISSION_DENIED); + case 'PERMISSION_DENIED_FOR_DONATION_ITEMS': + throw new NotAuthorizedException('The payee have not been granted appropriate permissions to send items.category as DONATION', NotAuthorizedException::PERMISSION_DENIED_FOR_DONATION_ITEMS); + default: + throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); + } + case 422: + switch ($errorMsg) { + case 'AGREEMENT_ALREADY_CANCELLED': + throw new UnprocessableEntityException('The requested agreement is already canceled', UnprocessableEntityException::AGREEMENT_ALREADY_CANCELLED); + case 'BILLING_AGREEMENT_NOT_FOUND': + throw new UnprocessableEntityException('The requested billing agreement token was not found', UnprocessableEntityException::BILLING_AGREEMENT_NOT_FOUND); + case 'CARD_EXPIRED': + throw new UnprocessableEntityException('The payment card provided is expired', UnprocessableEntityException::CARD_EXPIRED); + case 'COMPLIANCE_VIOLATION': + throw new UnprocessableEntityException('Transaction is declined due to compliance violation', UnprocessableEntityException::COMPLIANCE_VIOLATION); + case 'DOMESTIC_TRANSACTION_REQUIRED': + throw new UnprocessableEntityException('This transaction requires the payee and payer to be resident in the same country', UnprocessableEntityException::DOMESTIC_TRANSACTION_REQUIRED); + case 'DUPLICATE_INVOICE_ID': + throw new UnprocessableEntityException('Duplicate invoice ID detected', UnprocessableEntityException::DUPLICATE_INVOICE_ID); + case 'INSTRUMENT_DECLINED': + throw new UnprocessableEntityException('The instrument presented was either declined by the processor or bank or it cannot be used for this payment', UnprocessableEntityException::INSTRUMENT_DECLINED); + case 'ORDER_NOT_APPROVED': + throw new UnprocessableEntityException('Payer has not yet approved the Order for payment', UnprocessableEntityException::ORDER_NOT_APPROVED); + case 'MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED': + throw new UnprocessableEntityException('The maximum number of payment attempts has been exceeded', UnprocessableEntityException::MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED); + case 'PAYEE_BLOCKED_TRANSACTION': + throw new UnprocessableEntityException('The fraud settings for this seller are such that this payment cannot be executed', UnprocessableEntityException::PAYEE_BLOCKED_TRANSACTION); + case 'PAYER_ACCOUNT_LOCKED_OR_CLOSED': + throw new UnprocessableEntityException('The payer account cannot be used for this transaction', UnprocessableEntityException::PAYER_ACCOUNT_LOCKED_OR_CLOSED); + case 'PAYER_ACCOUNT_RESTRICTED': + throw new UnprocessableEntityException('The payer account is restricted', UnprocessableEntityException::PAYER_ACCOUNT_RESTRICTED); + case 'PAYER_CANNOT_PAY': + throw new UnprocessableEntityException('The payer cannot pay for this transaction', UnprocessableEntityException::PAYER_CANNOT_PAY); + case 'TRANSACTION_LIMIT_EXCEEDED': + throw new UnprocessableEntityException('Total payment amount exceeded transaction limit', UnprocessableEntityException::TRANSACTION_LIMIT_EXCEEDED); + case 'TRANSACTION_RECEIVING_LIMIT_EXCEEDED': + throw new UnprocessableEntityException('The transaction exceeds the receiver’s receiving limit', UnprocessableEntityException::TRANSACTION_RECEIVING_LIMIT_EXCEEDED); + case 'TRANSACTION_REFUSED': + throw new UnprocessableEntityException('The request was refused', UnprocessableEntityException::TRANSACTION_REFUSED); + case 'REDIRECT_PAYER_FOR_ALTERNATE_FUNDING': + throw new UnprocessableEntityException('Transaction failed. Redirect the payer to select another funding source', UnprocessableEntityException::REDIRECT_PAYER_FOR_ALTERNATE_FUNDING); + case 'ORDER_ALREADY_CAPTURED': + throw new UnprocessableEntityException('Order already captured', UnprocessableEntityException::ORDER_ALREADY_CAPTURED); + case 'TRANSACTION_BLOCKED_BY_PAYEE': + throw new UnprocessableEntityException('Transaction blocked by payee’s fraud protection settings', UnprocessableEntityException::TRANSACTION_BLOCKED_BY_PAYEE); + case 'AUTH_CAPTURE_NOT_ENABLED': + throw new UnprocessableEntityException('Authorization and capture feature is not enabled for the merchant', UnprocessableEntityException::AUTH_CAPTURE_NOT_ENABLED); + case 'NOT_ENABLED_FOR_CARD_PROCESSING': + throw new UnprocessableEntityException('The API caller account is not setup to be able to process card payments', UnprocessableEntityException::NOT_ENABLED_FOR_CARD_PROCESSING); + case 'PAYEE_NOT_ENABLED_FOR_CARD_PROCESSING': + throw new UnprocessableEntityException('Payee account is not setup to be able to process card payments', UnprocessableEntityException::PAYEE_NOT_ENABLED_FOR_CARD_PROCESSING); + case 'INVALID_PICKUP_ADDRESS': + throw new UnprocessableEntityException('If the shipping_option.type is set to PICKUP, then the shipping_detail.name.full_name should start with S2S', UnprocessableEntityException::INVALID_PICKUP_ADDRESS); + case 'SHIPPING_ADDRESS_INVALID': + throw new UnprocessableEntityException('Provided shipping address is invalid', UnprocessableEntityException::SHIPPING_ADDRESS_INVALID); + case 'CARD_CLOSED': + throw new UnprocessableEntityException('The card is closed with the issuer', UnprocessableEntityException::CARD_CLOSED); + default: + throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); + } + default: + throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); + } + } } + /** + * @throws NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ public function refundOrder(array $payload) { - return $this->client->refundOrder($payload); + try { + return $this->client->refundOrder($payload); + } catch (HttpException $exception) { + $response = $exception->getResponse(); + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + switch ($response->getStatusCode()) { + case 401: + switch ($errorMsg) { + case 'invalid_token': + throw new NotAuthorizedException('Token signature verification failed', NotAuthorizedException::INVALID_TOKEN); + default: + throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); + } + case 422: + switch ($errorMsg) { + case 'CANNOT_PROCESS_REFUNDS': + throw new UnprocessableEntityException('Current invoice state does not support refunds', UnprocessableEntityException::CANNOT_PROCESS_REFUNDS); + case 'INVALID_REFUND_AMOUNT': + throw new UnprocessableEntityException('Recorded refunds cannot exceed recorded payments', UnprocessableEntityException::INVALID_REFUND_AMOUNT); + default: + throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); + } + default: + throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); + } + } } /** @@ -247,20 +467,8 @@ public function getIdentityToken($merchantId) return $this->client->generateClientToken($payload); } catch (HttpException $exception) { $response = $exception->getResponse(); - if ($response->getStatusCode() === 400) { - // INVALID_REQUEST - } - if ($response->getStatusCode() === 401) { - // NOT_AUTHORIZED - } - if ($response->getStatusCode() === 404) { - // RESOURCE_NOT_FOUND - } - if ($response->getStatusCode() === 422) { - // UNPROCESSABLE_ENTITY - } - - return $response; + $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); + // Il y a rien dans la doc PayPal pour les erreurs sur IdentityToken } } @@ -272,16 +480,9 @@ public function getIdentityToken($merchantId) private function getErrorMessage($body) { $body = json_decode($body, true); - if (isset($body['details'][0]['issue']) && $body['details'][0]['issue']) { - return $body['details'][0]['issue']; - } - if ($body['name']) { - return $body['name']; - } - if ($body['error']) { - return $body['error']; - } - + if (isset($body['details'][0]['issue'])) return $body['details'][0]['issue']; + if (isset($body['name'])) return $body['name']; + if (isset($body['error'])) return $body['error']; return ''; } } diff --git a/src/DTO/Orders/UpdatePayPalOrderRequestInterface.php b/src/DTO/Orders/UpdatePayPalOrderRequestInterface.php new file mode 100644 index 000000000..a8ca221d4 --- /dev/null +++ b/src/DTO/Orders/UpdatePayPalOrderRequestInterface.php @@ -0,0 +1,25 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\DTO\Orders; + +interface UpdatePayPalOrderRequestInterface +{ +} diff --git a/src/Exception/InvalidRequestException.php b/src/Exception/InvalidRequestException.php index 7376908d3..16f9fed76 100644 --- a/src/Exception/InvalidRequestException.php +++ b/src/Exception/InvalidRequestException.php @@ -33,4 +33,7 @@ class InvalidRequestException extends PsCheckoutException const NOT_SUPPORTED = 8; const PAYPAL_REQUEST_ID_REQUIRED = 9; const MALFORMED_REQUEST_JSON = 10; + const FIELD_NOT_PATCHABLE = 11; + const AMOUNT_NOT_PATCHABLE = 12; + const INVALID_PATCH_OPERATION = 13; } diff --git a/src/Exception/NotAuthorizedException.php b/src/Exception/NotAuthorizedException.php index 415521a02..0e1c3bc82 100644 --- a/src/Exception/NotAuthorizedException.php +++ b/src/Exception/NotAuthorizedException.php @@ -26,6 +26,9 @@ class NotAuthorizedException extends PsCheckoutException const PERMISSION_DENIED = 1; const PERMISSION_DENIED_FOR_DONATION_ITEMS = 2; const MALFORMED_REQUEST = 3; - const INVALID_TOKEN = 4; - const INVALID_CLIENT = 5; + const PAYEE_ACCOUNT_NOT_SUPPORTED = 4; + const PAYEE_ACCOUNT_NOT_VERIFIED = 5; + const PAYEE_NOT_CONSENTED = 6; + const INVALID_TOKEN = 7; + const CONSENT_NEEDED = 8; } diff --git a/src/Exception/UnprocessableEntityException.php b/src/Exception/UnprocessableEntityException.php index cc78b9bca..f3b117bdd 100644 --- a/src/Exception/UnprocessableEntityException.php +++ b/src/Exception/UnprocessableEntityException.php @@ -65,4 +65,36 @@ class UnprocessableEntityException extends PsCheckoutException const ORDER_CANNOT_BE_SAVED = 40; const SAVE_ORDER_NOT_SUPPORTED = 41; const PUI_DUPLICATE_ORDER = 42; + const INVALID_JSON_POINTER_FORMAT = 43; + const INVALID_PARAMETER = 44; + const NOT_PATCHABLE = 45; + const UNSUPPORTED_PATCH_PARAMETER_VALUE = 46; + const PATCH_VALUE_REQUIRED = 47; + const PATCH_PATH_REQUIRED = 48; + const REFERENCE_ID_NOT_FOUND = 49; + const ORDER_ALREADY_COMPLETED = 50; + const AGREEMENT_ALREADY_CANCELLED = 51; + const BILLING_AGREEMENT_NOT_FOUND = 52; + const COMPLIANCE_VIOLATION = 53; + const DOMESTIC_TRANSACTION_REQUIRED = 54; + const DUPLICATE_INVOICE_ID = 55; + const INSTRUMENT_DECLINED = 56; + const ORDER_NOT_APPROVED = 57; + const MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED = 58; + const PAYEE_BLOCKED_TRANSACTION = 59; + const PAYER_ACCOUNT_LOCKED_OR_CLOSED = 60; + const PAYER_ACCOUNT_RESTRICTED = 61; + const PAYER_CANNOT_PAY = 62; + const TRANSACTION_LIMIT_EXCEEDED = 63; + const TRANSACTION_RECEIVING_LIMIT_EXCEEDED = 64; + const TRANSACTION_REFUSED = 65; + const REDIRECT_PAYER_FOR_ALTERNATE_FUNDING = 66; + const ORDER_ALREADY_CAPTURED = 67; + const TRANSACTION_BLOCKED_BY_PAYEE = 68; + const AUTH_CAPTURE_NOT_ENABLED = 69; + const NOT_ENABLED_FOR_CARD_PROCESSING = 70; + const PAYEE_NOT_ENABLED_FOR_CARD_PROCESSING = 71; + const INVALID_PICKUP_ADDRESS = 72; + const CANNOT_PROCESS_REFUNDS = 73; + const INVALID_REFUND_AMOUNT = 74; } diff --git a/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php b/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php new file mode 100644 index 000000000..692ee3ed5 --- /dev/null +++ b/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php @@ -0,0 +1,88 @@ +testErrorsGetOrder(401, $errorName, $errorCode); + } + + /** + * @param int $statusCode + * @param string $errorName + * @param int $errorCode + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ + private function testErrorsGetOrder($statusCode, $errorName, $errorCode) + { + if ($errorName === 'invalid_token') { + $error = $this->getInvalidTokenError(); + } else { + $error = $this->getNotAuthorizedError($errorName); + } + + $requestMock = $this->createMock(RequestInterface::class); + + $streamMock = $this->createMock(StreamInterface::class); + $streamMock->method('getContents')->willReturn(json_encode($error)); + + $responseMock = $this->createMock(ResponseInterface::class); + $responseMock->method('getStatusCode')->willReturn($statusCode); + $responseMock->method('getBody')->willReturn($streamMock); + + $clientMock = $this->createMock(PayPalOrderHttpClient::class); + $clientMock->method('fetchOrder')->willThrowException(new HttpException('An error occurred', $requestMock, $responseMock)); + + $this->expectExceptionCode($errorCode); + $paymentService = new PaymentService($clientMock); + $paymentService->getOrder('LUX8l091NV'); + } + + private function getNotAuthorizedError($issueError) + { + return [ + "name" => $issueError, + "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/overview/#error", + "rel" => "information_link" + ] + ] + ]; + } + + private function getInvalidTokenError() + { + return [ + "error" => "invalid_token", + "error_description" => "Current version only supports token for response_type" + ]; + } + + public function notAuthorizedErrorsProvider() + { + return [ + ['PERMISSION_DENIED', NotAuthorizedException::PERMISSION_DENIED], + ['invalid_token', NotAuthorizedException::INVALID_TOKEN] + ]; + } +} diff --git a/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php b/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php new file mode 100644 index 000000000..b5d9c04bd --- /dev/null +++ b/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php @@ -0,0 +1,193 @@ +testErrorsUpdateOrder(400, $errorName, $errorCode); + } + + /** + * @dataProvider notAuthorizedErrorsProvider + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ + public function testNotAuthorizedErrorsUpdateOrder($errorName, $errorCode) + { + $this->testErrorsUpdateOrder(401, $errorName, $errorCode); + } + + /** + * @dataProvider unprocessableEntityErrorsProvider + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ + public function testUnprocessableEntityErrorsUpdateOrder($errorName, $errorCode) + { + $this->testErrorsUpdateOrder(422, $errorName, $errorCode); + } + + /** + * @param int $statusCode + * @param string $errorName + * @param int $errorCode + * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException + */ + private function testErrorsUpdateOrder($statusCode, $errorName, $errorCode) + { + switch ($statusCode) { + case 400: + $error = $this->getInvalidRequestError($errorName); + break; + case 401: + $error = $this->getNotAuthorizedError($errorName); + break; + case 422: + default: + $error = $this->getUnprocessableEntityError($errorName); + break; + } + + $requestMock = $this->createMock(RequestInterface::class); + $updateRequestMock = $this->createMock(UpdatePayPalOrderRequestInterface::class); + + $streamMock = $this->createMock(StreamInterface::class); + $streamMock->method('getContents')->willReturn(json_encode($error)); + + $responseMock = $this->createMock(ResponseInterface::class); + $responseMock->method('getStatusCode')->willReturn($statusCode); + $responseMock->method('getBody')->willReturn($streamMock); + + $clientMock = $this->createMock(PayPalOrderHttpClient::class); + $clientMock->method('updateOrder')->willThrowException(new HttpException('An error occurred', $requestMock, $responseMock)); + + $this->expectExceptionCode($errorCode); + $paymentService = new PaymentService($clientMock); + $paymentService->updateOrder($updateRequestMock); + } + + private function getInvalidRequestError($issueError) + { + return [ + "name" => "INVALID_REQUEST", + "message" => "Request is not well-formed, syntactically incorrect, or violates schema.", + "debug_id" => "b6b9a374802ea", + "details" => [ + [ + "field" => "", + "value" => "", + "location" => "body", + "issue" => $issueError, + "description" => "" + ] + ], + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE", + "rel" => "information_link", + "encType" => "application/json" + ] + ] + ]; + } + + private function getNotAuthorizedError($issueError) + { + return [ + "name" => $issueError, + "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/overview/#error", + "rel" => "information_link" + ] + ] + ]; + } + + private function getUnprocessableEntityError($issueError) + { + return [ + "name" => "UNPROCESSABLE_ENTITY", + "details" => [ + [ + "field" => "", + "value" => "", + "issue" => $issueError, + "description" => "" + ] + ], + "message" => "The requested action could not be performed, semantically incorrect, or failed business validation.", + "debug_id" => "c9a75b43fc807", + "links" => [ + [ + "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED", + "rel" => "information_link", + "method" => "GET" + ] + ] + ]; + } + + public function invalidRequestErrorsProvider() + { + return [ + ['FIELD_NOT_PATCHABLE', InvalidRequestException::FIELD_NOT_PATCHABLE], + ['INVALID_ARRAY_MAX_ITEMS', InvalidRequestException::INVALID_ARRAY_MAX_ITEMS], + ['INVALID_PARAMETER_SYNTAX', InvalidRequestException::INVALID_PARAMETER_SYNTAX], + ['INVALID_STRING_LENGTH', InvalidRequestException::INVALID_STRING_LENGTH], + ['INVALID_PARAMETER_VALUE', InvalidRequestException::INVALID_PARAMETER_VALUE], + ['MISSING_REQUIRED_PARAMETER', InvalidRequestException::MISSING_REQUIRED_PARAMETER], + ['AMOUNT_NOT_PATCHABLE', InvalidRequestException::AMOUNT_NOT_PATCHABLE], + ['INVALID_PATCH_OPERATION', InvalidRequestException::INVALID_PATCH_OPERATION], + ['ERROR_CURRENTLY_UNKNOWN', InvalidRequestException::UNKNOWN] + ]; + } + + public function notAuthorizedErrorsProvider() + { + return [ + ['PERMISSION_DENIED', NotAuthorizedException::PERMISSION_DENIED], + ['PAYEE_ACCOUNT_NOT_SUPPORTED', NotAuthorizedException::PAYEE_ACCOUNT_NOT_SUPPORTED], + ['PAYEE_ACCOUNT_NOT_VERIFIED', NotAuthorizedException::PAYEE_ACCOUNT_NOT_VERIFIED], + ['PAYEE_NOT_CONSENTED', NotAuthorizedException::PAYEE_NOT_CONSENTED], + ['ERROR_CURRENTLY_UNKNOWN', NotAuthorizedException::UNKNOWN] + ]; + } + + public function unprocessableEntityErrorsProvider() { + return [ + ['INVALID_JSON_POINTER_FORMAT', UnprocessableEntityException::INVALID_JSON_POINTER_FORMAT], + ['INVALID_PARAMETER', UnprocessableEntityException::INVALID_PARAMETER], + ['NOT_PATCHABLE', UnprocessableEntityException::NOT_PATCHABLE], + ['UNSUPPORTED_PATCH_PARAMETER_VALUE', UnprocessableEntityException::UNSUPPORTED_PATCH_PARAMETER_VALUE], + ['PATCH_VALUE_REQUIRED', UnprocessableEntityException::PATCH_VALUE_REQUIRED], + ['PATCH_PATH_REQUIRED', UnprocessableEntityException::PATCH_PATH_REQUIRED], + ['REFERENCE_ID_NOT_FOUND', UnprocessableEntityException::REFERENCE_ID_NOT_FOUND], + ['MULTI_CURRENCY_ORDER', UnprocessableEntityException::MULTI_CURRENCY_ORDER], + ['SHIPPING_OPTION_NOT_SELECTED', UnprocessableEntityException::SHIPPING_OPTION_NOT_SELECTED], + ['SHIPPING_OPTIONS_NOT_SUPPORTED', UnprocessableEntityException::SHIPPING_OPTIONS_NOT_SUPPORTED], + ['MULTIPLE_SHIPPING_OPTION_SELECTED', UnprocessableEntityException::MULTIPLE_SHIPPING_OPTION_SELECTED], + ['ORDER_ALREADY_COMPLETED', UnprocessableEntityException::ORDER_ALREADY_COMPLETED], + ['PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH', UnprocessableEntityException::PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH], + ['ERROR_CURRENTLY_UNKNOWN', UnprocessableEntityException::UNKNOWN] + ]; + } +} From 67eacb4ceaa8ad8f3e61ad89510a3ba09508888f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20=C5=A0edys?= Date: Tue, 5 Mar 2024 13:28:17 +0200 Subject: [PATCH 20/26] Symfony serializer (#1202) * Create ObjectNormalizer to add supports of SKIP_NULL_VALUES * Added object deserializing tests * Added dependency injection for serializer * Updated PaymentService with response serialization * CS fix * Removed custom object normalizer * Added bootstrap to phpunit config * Added order object serialization to pass to event * Service refactoring * Added toArray function to object serializer and fixed snake case conversion * Added serializer interface * Fix * Fixed phpstan errors * Added json serialization to order requests and fixed cs issues --------- Co-authored-by: Matt75 <5262628+Matt75@users.noreply.github.com> --- .github/workflows/php.yml | 9 +- config/common.yml | 20 +- .../Payment/Client/PayPalOrderHttpClient.php | 39 +-- src/Api/Payment/PaymentService.php | 59 ++++- src/Api/Payment/Service/PaymentService.php | 67 ----- .../CheckoutEventSubscriber.php | 17 +- .../CreateOrderCommandHandler.php | 13 +- .../EventSubscriber/OrderEventSubscriber.php | 25 +- .../CreatePayPalOrderCommandHandler.php | 26 +- .../Order/DTO/CreatePayPalOrderResponse.php | 20 ++ .../PayPalCaptureEventSubscriber.php | 13 +- src/Serializer/ObjectSerializer.php | 84 ++++++ src/Serializer/ObjectSerializerInterface.php | 57 ++++ .../PaymentServiceCreateOrderTest.php | 3 +- .../PaymentServiceGetOrderTest.php | 22 +- .../PaymentServiceUpdateOrderTest.php | 89 ++++--- .../Unit/Serializer/ObjectSerializerTest.php | 250 ++++++++++++++++++ tests/Unit/bootstrap.php | 6 + tests/Unit/phpunit.xml | 3 +- 19 files changed, 615 insertions(+), 207 deletions(-) delete mode 100755 src/Api/Payment/Service/PaymentService.php create mode 100644 src/Serializer/ObjectSerializer.php create mode 100644 src/Serializer/ObjectSerializerInterface.php create mode 100644 tests/Unit/Serializer/ObjectSerializerTest.php create mode 100644 tests/Unit/bootstrap.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 8e90cf09e..1db7da5ba 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -88,6 +88,9 @@ jobs: phpunit: name: PHPUnit runs-on: ubuntu-latest + strategy: + matrix: + presta-versions: [ '8.0.0', 'latest' ] steps: - name: Checkout uses: actions/checkout@v2 @@ -111,5 +114,9 @@ jobs: - run: composer install + - name: Pull PrestaShop files (Tag ${{ matrix.presta-versions }}) + run: docker run -tid --rm -v ps-volume:/var/www/html --name temp-ps prestashop/prestashop:${{ matrix.presta-versions }} + - name: Run PHPUnit - run: php vendor/bin/phpunit tests/Unit + run: docker run --rm --volumes-from temp-ps -v $PWD:/var/www/html/modules/ps_checkout -e _PS_ROOT_DIR_=/var/www/html/ --workdir=/var/www/html/modules/ps_checkout php:7.2 ./vendor/bin/phpunit -c ./tests/Unit/phpunit.xml +# run: php vendor/bin/phpunit tests/Unit diff --git a/config/common.yml b/config/common.yml index 04b072cb9..8593ccf45 100644 --- a/config/common.yml +++ b/config/common.yml @@ -436,7 +436,7 @@ services: ps_checkout.tactician.bus: class: 'League\Tactician\CommandBus' - factory: ["@ps_checkout.tactician.bus.factory", "create"] + factory: ['@PrestaShop\Module\PrestashopCheckout\CommandBus\TacticianCommandBusFactory', "create"] ps_checkout.bus.command: class: 'PrestaShop\Module\PrestashopCheckout\CommandBus\TacticianCommandBusAdapter' @@ -444,7 +444,7 @@ services: arguments: - "@ps_checkout.tactician.bus" - ps_checkout.tactician.bus.factory: + PrestaShop\Module\PrestashopCheckout\CommandBus\TacticianCommandBusFactory: class: 'PrestaShop\Module\PrestashopCheckout\CommandBus\TacticianCommandBusFactory' public: true arguments: @@ -452,7 +452,7 @@ services: - "@ps_checkout.logger" - PrestaShop\Module\PrestashopCheckout\Order\Command\AddOrderPaymentCommand: "ps_checkout.command.handler.order.add_order_payment" - PrestaShop\Module\PrestashopCheckout\Order\Command\CreateOrderCommand: "ps_checkout.command.handler.order.create_order" + PrestaShop\Module\PrestashopCheckout\Order\Command\CreateOrderCommand: 'PrestaShop\Module\PrestashopCheckout\Order\CommandHandler\CreateOrderCommandHandler' PrestaShop\Module\PrestashopCheckout\Order\Command\UpdateOrderStatusCommand: "ps_checkout.command.handler.order.update_order_status" PrestaShop\Module\PrestashopCheckout\Order\Matrice\Command\UpdateOrderMatriceCommand: "ps_checkout.command.handler.order.matrice.update_order_matrice" PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\CreatePayPalOrderCommandHandler' @@ -486,16 +486,16 @@ services: class: 'PrestaShop\Module\PrestashopCheckout\Checkout\EventSubscriber\CheckoutEventSubscriber' public: true arguments: - - "@ps_checkout.module" - '@PrestaShop\Module\PrestashopCheckout\Checkout\CheckoutChecker' - '@ps_checkout.bus.command' + - '@ps_checkout.repository.pscheckoutcart' PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber\OrderEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber\OrderEventSubscriber' public: true arguments: - - "@ps_checkout.module" - "@ps_checkout.repository.pscheckoutcart" + - '@ps_checkout.bus.command' PrestaShop\Module\PrestashopCheckout\PayPal\Order\EventSubscriber\PayPalOrderEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\EventSubscriber\PayPalOrderEventSubscriber' @@ -513,11 +513,11 @@ services: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber' public: true arguments: - - "@ps_checkout.module" - "@ps_checkout.order.service.check_order_amount" - "@ps_checkout.cache.paypal.capture" - "@ps_checkout.cache.paypal.order" - "@ps_checkout.order.state.service.order_state_mapper" + - "@ps_checkout.bus.command" PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Refund\EventSubscriber\PayPalRefundEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Refund\EventSubscriber\PayPalRefundEventSubscriber' @@ -555,7 +555,7 @@ services: - "@ps_checkout.funding_source.translation" - "@ps_checkout.paypal.configuration" - ps_checkout.command.handler.order.create_order: + PrestaShop\Module\PrestashopCheckout\Order\CommandHandler\CreateOrderCommandHandler: class: 'PrestaShop\Module\PrestashopCheckout\Order\CommandHandler\CreateOrderCommandHandler' public: true arguments: @@ -565,6 +565,7 @@ services: - "@ps_checkout.order.state.service.order_state_mapper" - "@ps_checkout.module" - "@ps_checkout.order.service.check_order_amount" + - '@ps_checkout.funding_source.translation' ps_checkout.command.handler.order.update_order_status: class: 'PrestaShop\Module\PrestashopCheckout\Order\CommandHandler\UpdateOrderStatusCommandHandler' @@ -586,6 +587,7 @@ services: - '@?' - '@ps_checkout.event.dispatcher' - '@PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' + - '@PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer' ps_checkout.command.handler.paypal.order.update_paypal_order: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\CommandHandler\UpdatePayPalOrderCommandHandler' @@ -743,6 +745,10 @@ services: class: 'PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' arguments: - '@PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient' + - '@PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer' + + PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer: + class: 'PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer' ps_checkout.http.client.configuration: class: 'PrestaShop\Module\PrestashopCheckout\Http\CheckoutHttpClientConfigurationBuilder' diff --git a/src/Api/Payment/Client/PayPalOrderHttpClient.php b/src/Api/Payment/Client/PayPalOrderHttpClient.php index 6422c6e3d..07f52b253 100755 --- a/src/Api/Payment/Client/PayPalOrderHttpClient.php +++ b/src/Api/Payment/Client/PayPalOrderHttpClient.php @@ -42,13 +42,14 @@ public function __construct(PaymentClientConfigurationBuilder $configurationBuil * * @return ResponseInterface * - * @throws HttpException + * @throws HttpException|RequestException|TransferException|NetworkException */ public function sendRequest(RequestInterface $request) { try { return parent::sendRequest($request); } catch (NetworkException $exception) { + throw $exception; // Thrown when the request cannot be completed because of network issues. // No response here } catch (HttpException $exception) { @@ -73,68 +74,68 @@ public function sendRequest(RequestInterface $request) } /** - * @param array $payload + * @param string $payload //Payload JSON * @param array $options * * @return ResponseInterface */ - public function createOrder(array $payload, array $options = []) + public function createOrder($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/create', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/create', $options, $payload)); } /** - * @param array $payload + * @param string $payload * @param array $options * * @return ResponseInterface */ - public function updateOrder(array $payload, array $options = []) + public function updateOrder($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/update', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/update', $options, $payload)); } /** - * @param array $payload + * @param string $payload * @param array $options * * @return ResponseInterface */ - public function fetchOrder(array $payload, array $options = []) + public function fetchOrder($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/fetch', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/fetch', $options, $payload)); } /** - * @param array $payload + * @param string $payload * @param array $options * * @return ResponseInterface */ - public function captureOrder(array $payload, array $options = []) + public function captureOrder($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/capture', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/capture', $options, $payload)); } /** - * @param array $payload + * @param string $payload * @param array $options * * @return ResponseInterface */ - public function refundOrder(array $payload, array $options = []) + public function refundOrder($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/refund', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/refund', $options, $payload)); } /** - * @param array $payload + * @param string $payload * @param array $options * * @return ResponseInterface */ - public function generateClientToken(array $payload, array $options = []) + public function generateClientToken($payload, array $options = []) { - return $this->sendRequest(new Request('POST', '/payments/order/generate_client_token', $options, json_encode($payload))); + return $this->sendRequest(new Request('POST', '/payments/order/generate_client_token', $options, $payload)); } } diff --git a/src/Api/Payment/PaymentService.php b/src/Api/Payment/PaymentService.php index cae0cf57d..6c3177273 100644 --- a/src/Api/Payment/PaymentService.php +++ b/src/Api/Payment/PaymentService.php @@ -20,6 +20,7 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment; +use Exception; use Http\Client\Exception\HttpException; use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; use PrestaShop\Module\PrestashopCheckout\DTO\Orders\CreatePayPalOrderRequestInterface; @@ -28,7 +29,10 @@ use PrestaShop\Module\PrestashopCheckout\Exception\NotAuthorizedException; use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; use PrestaShop\Module\PrestashopCheckout\Exception\UnprocessableEntityException; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderResponse; +use PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializerInterface; use Psr\Http\Message\ResponseInterface; +use Symfony\Component\Serializer\Encoder\JsonEncoder; class PaymentService { @@ -36,24 +40,30 @@ class PaymentService * @var PayPalOrderHttpClient */ private $client; + /** + * @var ObjectSerializerInterface + */ + private $serializer; - public function __construct(PayPalOrderHttpClient $client) + public function __construct(PayPalOrderHttpClient $client, ObjectSerializerInterface $serializer) { $this->client = $client; + $this->serializer = $serializer; } /** * @param CreatePayPalOrderRequestInterface $request * - * @return ResponseInterface + * @return CreatePayPalOrderResponse * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function createOrder(CreatePayPalOrderRequestInterface $request) { - $payload = (array) $request; try { - return $this->client->createOrder($payload); + $response = $this->client->createOrder($this->serializer->serialize($request, JsonEncoder::FORMAT, true)); + + return $this->serializer->deserialize($response->getBody()->getContents(), CreatePayPalOrderResponse::class, JsonEncoder::FORMAT); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); @@ -185,6 +195,7 @@ public function createOrder(CreatePayPalOrderRequestInterface $request) default: throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); } + // no break default: throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } @@ -193,14 +204,15 @@ public function createOrder(CreatePayPalOrderRequestInterface $request) /** * @param UpdatePayPalOrderRequestInterface $request + * * @return ResponseInterface + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function updateOrder(UpdatePayPalOrderRequestInterface $request) { - $payload = (array) $request; try { - return $this->client->updateOrder($payload); + return $this->client->updateOrder($this->serializer->serialize($request, JsonEncoder::FORMAT, true)); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); @@ -226,6 +238,7 @@ public function updateOrder(UpdatePayPalOrderRequestInterface $request) default: throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); } + // no break case 401: switch ($errorMsg) { case 'PERMISSION_DENIED': @@ -239,6 +252,7 @@ public function updateOrder(UpdatePayPalOrderRequestInterface $request) default: throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); } + // no break case 422: switch ($errorMsg) { case 'INVALID_JSON_POINTER_FORMAT': @@ -270,6 +284,7 @@ public function updateOrder(UpdatePayPalOrderRequestInterface $request) default: throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); } + // no break default: throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } @@ -290,7 +305,7 @@ public function getOrder($orderId) ]; try { - return $this->client->fetchOrder($payload); + return $this->client->fetchOrder($this->serializer->serialize($payload, JsonEncoder::FORMAT, true)); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); @@ -304,6 +319,7 @@ public function getOrder($orderId) default: throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); } + // no break default: throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } @@ -328,7 +344,7 @@ public function captureOrder(array $data) ]; try { - return $this->client->captureOrder($payload); + return $this->client->captureOrder($this->serializer->serialize($payload, JsonEncoder::FORMAT, true)); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); @@ -344,6 +360,7 @@ public function captureOrder(array $data) default: throw new InvalidRequestException(sprintf('InvalidRequest unknown error : %s', $errorMsg), InvalidRequestException::UNKNOWN); } + // no break case 401: switch ($errorMsg) { case 'CONSENT_NEEDED': @@ -355,6 +372,7 @@ public function captureOrder(array $data) default: throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); } + // no break case 422: switch ($errorMsg) { case 'AGREEMENT_ALREADY_CANCELLED': @@ -410,6 +428,7 @@ public function captureOrder(array $data) default: throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); } + // no break default: throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } @@ -422,7 +441,7 @@ public function captureOrder(array $data) public function refundOrder(array $payload) { try { - return $this->client->refundOrder($payload); + return $this->client->refundOrder($this->serializer->serialize($payload, JsonEncoder::FORMAT, true)); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); @@ -434,6 +453,7 @@ public function refundOrder(array $payload) default: throw new NotAuthorizedException(sprintf('NotAuthorized unknown error : %s', $errorMsg), NotAuthorizedException::UNKNOWN); } + // no break case 422: switch ($errorMsg) { case 'CANNOT_PROCESS_REFUNDS': @@ -443,6 +463,7 @@ public function refundOrder(array $payload) default: throw new UnprocessableEntityException(sprintf('UnprocessableEntity unknown error : %s', $errorMsg), UnprocessableEntityException::UNKNOWN); } + // no break default: throw new PsCheckoutException(sprintf('Unknown error : %s', $errorMsg), PsCheckoutException::UNKNOWN); } @@ -453,6 +474,8 @@ public function refundOrder(array $payload) * @param string $merchantId * * @return ResponseInterface + * + * @throws Exception */ public function getIdentityToken($merchantId) { @@ -464,11 +487,14 @@ public function getIdentityToken($merchantId) ]; try { - return $this->client->generateClientToken($payload); + return $this->client->generateClientToken($this->serializer->serialize($payload, JsonEncoder::FORMAT, true)); } catch (HttpException $exception) { $response = $exception->getResponse(); $errorMsg = $this->getErrorMessage($response->getBody()->getContents()); // Il y a rien dans la doc PayPal pour les erreurs sur IdentityToken + throw new Exception('Temp exception'); + } catch (Exception $exception) { + throw $exception; } } @@ -480,9 +506,16 @@ public function getIdentityToken($merchantId) private function getErrorMessage($body) { $body = json_decode($body, true); - if (isset($body['details'][0]['issue'])) return $body['details'][0]['issue']; - if (isset($body['name'])) return $body['name']; - if (isset($body['error'])) return $body['error']; + if (isset($body['details'][0]['issue'])) { + return $body['details'][0]['issue']; + } + if (isset($body['name'])) { + return $body['name']; + } + if (isset($body['error'])) { + return $body['error']; + } + return ''; } } diff --git a/src/Api/Payment/Service/PaymentService.php b/src/Api/Payment/Service/PaymentService.php deleted file mode 100755 index 86fa5407c..000000000 --- a/src/Api/Payment/Service/PaymentService.php +++ /dev/null @@ -1,67 +0,0 @@ - - * @copyright Since 2007 PrestaShop SA and Contributors - * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 - */ - -namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Service; - -use PrestaShop\Module\PrestashopCheckout\Api\Payment\Client\PayPalOrderHttpClient; - -class PaymentService -{ - /** @var PayPalOrderHttpClient */ - private $paymentClient; - - /** - * @param PayPalOrderHttpClient $paymentClient - */ - public function __construct(PayPalOrderHttpClient $paymentClient) - { - $this->paymentClient = $paymentClient; - } - - public function createOrder(array $data) - { - // TODO - } - - public function updateOrder(array $data) - { - // TODO - } - - public function getOrder(array $data) - { - // TODO - } - - public function captureOrder(array $data) - { - // TODO - } - - public function refundOrder(array $data) - { - // TODO - } - - public function getIdentityToken(array $data) - { - // TODO - } -} diff --git a/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php b/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php index 0c988524c..b393f1907 100644 --- a/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php +++ b/src/Checkout/EventSubscriber/CheckoutEventSubscriber.php @@ -57,15 +57,16 @@ class CheckoutEventSubscriber implements EventSubscriberInterface * @var CheckoutChecker */ private $checkoutChecker; - /** - * @param Ps_checkout $module + * @var PsCheckoutCartRepository */ - public function __construct(Ps_checkout $module, CheckoutChecker $checkoutChecker, CommandBusInterface $commandBus) + private $psCheckoutCartRepository; + + public function __construct(CheckoutChecker $checkoutChecker, CommandBusInterface $commandBus, PsCheckoutCartRepository $psCheckoutCartRepository) { - $this->module = $module; $this->checkoutChecker = $checkoutChecker; $this->commandBus = $commandBus; + $this->psCheckoutCartRepository = $psCheckoutCartRepository; } /** @@ -122,7 +123,7 @@ public function proceedToPayment(CheckoutCompletedEvent $event) { try { /** @var GetPayPalOrderForCheckoutCompletedQueryResult $getPayPalOrderForCheckoutCompletedQueryResult */ - $getPayPalOrderForCheckoutCompletedQueryResult = $this->module->getService('ps_checkout.bus.command')->handle(new GetPayPalOrderForCheckoutCompletedQuery( + $getPayPalOrderForCheckoutCompletedQueryResult = $this->commandBus->handle(new GetPayPalOrderForCheckoutCompletedQuery( $event->getPayPalOrderId()->getValue() )); } catch (HttpTimeoutException $exception) { @@ -146,13 +147,11 @@ public function proceedToPayment(CheckoutCompletedEvent $event) return; } elseif ($exception->getCode() === PayPalException::RESOURCE_NOT_FOUND) { - /** @var PsCheckoutCartRepository $psCheckoutCartRepository */ - $psCheckoutCartRepository = $this->module->getService('ps_checkout.repository.pscheckoutcart'); - $psCheckoutCart = $psCheckoutCartRepository->findOneByPayPalOrderId($event->getPayPalOrderId()->getValue()); + $psCheckoutCart = $this->psCheckoutCartRepository->findOneByPayPalOrderId($event->getPayPalOrderId()->getValue()); if (Validate::isLoadedObject($psCheckoutCart)) { $psCheckoutCart->paypal_status = PsCheckoutCart::STATUS_CANCELED; - $psCheckoutCartRepository->save($psCheckoutCart); + $this->psCheckoutCartRepository->save($psCheckoutCart); } throw $exception; diff --git a/src/Order/CommandHandler/CreateOrderCommandHandler.php b/src/Order/CommandHandler/CreateOrderCommandHandler.php index 4a7e7921d..2a6d0ee4c 100644 --- a/src/Order/CommandHandler/CreateOrderCommandHandler.php +++ b/src/Order/CommandHandler/CreateOrderCommandHandler.php @@ -77,6 +77,10 @@ class CreateOrderCommandHandler extends AbstractOrderCommandHandler * @var CheckOrderAmount */ private $checkOrderAmount; + /** + * @var FundingSourceTranslationProvider + */ + private $fundingSourceTranslationProvider; public function __construct( ContextStateManager $contextStateManager, @@ -84,7 +88,8 @@ public function __construct( PsCheckoutCartRepository $psCheckoutCartRepository, OrderStateMapper $psOrderStateMapper, Ps_checkout $module, - CheckOrderAmount $checkOrderAmount + CheckOrderAmount $checkOrderAmount, + FundingSourceTranslationProvider $fundingSourceTranslationProvider ) { $this->contextStateManager = $contextStateManager; $this->eventDispatcher = $eventDispatcher; @@ -92,6 +97,7 @@ public function __construct( $this->psOrderStateMapper = $psOrderStateMapper; $this->module = $module; $this->checkOrderAmount = $checkOrderAmount; + $this->fundingSourceTranslationProvider = $fundingSourceTranslationProvider; } /** @@ -167,9 +173,6 @@ public function handle(CreateOrderCommand $command) $orderStateId = $this->psOrderStateMapper->getIdByKey(OrderStateConfigurationKeys::PS_CHECKOUT_STATE_PENDING); } - /** @var FundingSourceTranslationProvider $fundingSourceTranslationProvider */ - $fundingSourceTranslationProvider = $this->module->getService('ps_checkout.funding_source.translation'); - if ($this->shouldSetCartContext($this->contextStateManager->getContext(), $cart)) { $this->setCartContext($this->contextStateManager, $cart); } @@ -187,7 +190,7 @@ public function handle(CreateOrderCommand $command) (int) $cart->id, $orderStateId, $paidAmount, - $fundingSourceTranslationProvider->getPaymentMethodName($fundingSource), + $this->fundingSourceTranslationProvider->getPaymentMethodName($fundingSource), null, $extraVars, $currencyId, diff --git a/src/Order/EventSubscriber/OrderEventSubscriber.php b/src/Order/EventSubscriber/OrderEventSubscriber.php index 2d4f2f4e3..ee3701d1a 100644 --- a/src/Order/EventSubscriber/OrderEventSubscriber.php +++ b/src/Order/EventSubscriber/OrderEventSubscriber.php @@ -21,38 +21,32 @@ namespace PrestaShop\Module\PrestashopCheckout\Order\EventSubscriber; +use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; use PrestaShop\Module\PrestashopCheckout\Order\Event\OrderCreatedEvent; use PrestaShop\Module\PrestashopCheckout\Order\Exception\OrderException; use PrestaShop\Module\PrestashopCheckout\Order\Matrice\Command\UpdateOrderMatriceCommand; -use PrestaShop\Module\PrestashopCheckout\Order\State\Exception\OrderStateException; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Exception\PayPalOrderException; use PrestaShop\Module\PrestashopCheckout\Repository\PsCheckoutCartRepository; use PrestaShopException; -use Ps_checkout; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class OrderEventSubscriber implements EventSubscriberInterface { - /** - * @var Ps_checkout - */ - private $module; - /** * @var PsCheckoutCartRepository */ private $psCheckoutCartRepository; - /** - * @param Ps_checkout $module - * @param PsCheckoutCartRepository $psCheckoutCartRepository + * @var CommandBusInterface */ + private $commandBus; + public function __construct( - Ps_checkout $module, - PsCheckoutCartRepository $psCheckoutCartRepository + PsCheckoutCartRepository $psCheckoutCartRepository, + CommandBusInterface $commandBus ) { - $this->module = $module; $this->psCheckoutCartRepository = $psCheckoutCartRepository; + $this->commandBus = $commandBus; } /** @@ -70,17 +64,16 @@ public static function getSubscribedEvents() * * @return void * - * @throws PrestaShopException * @throws OrderException * @throws PayPalOrderException - * @throws OrderStateException + * @throws PrestaShopException */ public function updateOrderMatrice(OrderCreatedEvent $event) { $cartId = $event->getCartId()->getValue(); $psCheckoutCart = $this->psCheckoutCartRepository->findOneByCartId($cartId); - $this->module->getService('ps_checkout.bus.command')->handle(new UpdateOrderMatriceCommand( + $this->commandBus->handle(new UpdateOrderMatriceCommand( $event->getOrderId()->getValue(), $psCheckoutCart->getPaypalOrderId() )); diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 4b930ad8e..0faf45ca1 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -24,10 +24,15 @@ use PrestaShop\Module\PrestashopCheckout\Cart\CartRepositoryInterface; use PrestaShop\Module\PrestashopCheckout\Cart\Exception\CartNotFoundException; use PrestaShop\Module\PrestashopCheckout\Event\EventDispatcherInterface; +use PrestaShop\Module\PrestashopCheckout\Exception\InvalidRequestException; +use PrestaShop\Module\PrestashopCheckout\Exception\NotAuthorizedException; +use PrestaShop\Module\PrestashopCheckout\Exception\UnprocessableEntityException; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Command\CreatePayPalOrderCommand; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\CreatePayPalOrderPayloadBuilderInterface; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Event\PayPalOrderCreatedEvent; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Exception\PayPalOrderException; +use PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializerInterface; +use PrestaShop\PrestaShop\Core\Foundation\IoC\Exception; class CreatePayPalOrderCommandHandler { @@ -49,17 +54,23 @@ class CreatePayPalOrderCommandHandler * @var PaymentService */ private $paymentService; + /** + * @var ObjectSerializerInterface + */ + private $objectSerializer; public function __construct( CartRepositoryInterface $cartRepository, CreatePayPalOrderPayloadBuilderInterface $createPayPalOrderPayloadBuilder, EventDispatcherInterface $eventDispatcher, - PaymentService $paymentService + PaymentService $paymentService, + ObjectSerializerInterface $objectSerializer ) { $this->cartRepository = $cartRepository; $this->createPayPalOrderPayloadBuilder = $createPayPalOrderPayloadBuilder; $this->eventDispatcher = $eventDispatcher; $this->paymentService = $paymentService; + $this->objectSerializer = $objectSerializer; } /** @@ -67,18 +78,21 @@ public function __construct( * * @return void * - * @throws PayPalOrderException * @throws CartNotFoundException + * @throws PayPalOrderException + * @throws InvalidRequestException + * @throws NotAuthorizedException + * @throws UnprocessableEntityException + * @throws Exception */ public function handle(CreatePayPalOrderCommand $command) { $cart = $this->cartRepository->getCartById($command->getCartId()); $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); - $response = $this->paymentService->createOrder($payload); - $order = json_decode($response->getBody()->getContents()); + $order = $this->paymentService->createOrder($payload); $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( - $order['id'], - $order, + $order->getId(), + $this->objectSerializer->toArray($order, false, true), $command->getCartId(), $command->isHostedFields(), $command->isExpressCheckout() diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php b/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php index 575375841..0347213a4 100644 --- a/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php +++ b/src/PayPal/Order/DTO/CreatePayPalOrderResponse.php @@ -78,6 +78,8 @@ public function getId() public function setId($id) { $this->id = $id; + + return $this; } /** @@ -94,6 +96,8 @@ public function getCreateTime() public function setCreateTime($create_time) { $this->create_time = $create_time; + + return $this; } /** @@ -110,6 +114,8 @@ public function getUpdateTime() public function setUpdateTime($update_time) { $this->update_time = $update_time; + + return $this; } /** @@ -126,6 +132,8 @@ public function getPaymentSource() public function setPaymentSource($payment_source) { $this->payment_source = $payment_source; + + return $this; } /** @@ -142,6 +150,8 @@ public function getIntent() public function setIntent($intent) { $this->intent = $intent; + + return $this; } /** @@ -158,6 +168,8 @@ public function getProcessingInstruction() public function setProcessingInstruction($processing_instruction) { $this->processing_instruction = $processing_instruction; + + return $this; } /** @@ -174,6 +186,8 @@ public function getPayer() public function setPayer($payer) { $this->payer = $payer; + + return $this; } /** @@ -190,6 +204,8 @@ public function getPurchaseUnits() public function setPurchaseUnits($purchase_units) { $this->purchase_units = $purchase_units; + + return $this; } /** @@ -206,6 +222,8 @@ public function getStatus() public function setStatus($status) { $this->status = $status; + + return $this; } /** @@ -222,5 +240,7 @@ public function getLinks() public function setLinks($links) { $this->links = $links; + + return $this; } } diff --git a/src/PayPal/Payment/Capture/EventSubscriber/PayPalCaptureEventSubscriber.php b/src/PayPal/Payment/Capture/EventSubscriber/PayPalCaptureEventSubscriber.php index eefa235de..4a90ce784 100644 --- a/src/PayPal/Payment/Capture/EventSubscriber/PayPalCaptureEventSubscriber.php +++ b/src/PayPal/Payment/Capture/EventSubscriber/PayPalCaptureEventSubscriber.php @@ -41,17 +41,11 @@ use PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\Event\PayPalCaptureEvent; use PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\Event\PayPalCapturePendingEvent; use PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\Event\PayPalCaptureReversedEvent; -use Ps_checkout; use Psr\SimpleCache\CacheInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class PayPalCaptureEventSubscriber implements EventSubscriberInterface { - /** - * @var Ps_checkout - */ - private $module; - /** * @var CheckOrderAmount */ @@ -78,18 +72,17 @@ class PayPalCaptureEventSubscriber implements EventSubscriberInterface private $orderStateMapper; public function __construct( - Ps_checkout $module, CheckOrderAmount $checkOrderAmount, CacheInterface $capturePayPalCache, CacheInterface $orderPayPalCache, - OrderStateMapper $orderStateMapper + OrderStateMapper $orderStateMapper, + CommandBusInterface $commandBus ) { - $this->module = $module; $this->checkOrderAmount = $checkOrderAmount; - $this->commandBus = $this->module->getService('ps_checkout.bus.command'); $this->capturePayPalCache = $capturePayPalCache; $this->orderPayPalCache = $orderPayPalCache; $this->orderStateMapper = $orderStateMapper; + $this->commandBus = $commandBus; } /** diff --git a/src/Serializer/ObjectSerializer.php b/src/Serializer/ObjectSerializer.php new file mode 100644 index 000000000..8fbe72c18 --- /dev/null +++ b/src/Serializer/ObjectSerializer.php @@ -0,0 +1,84 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Serializer; + +use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; +use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; +use Symfony\Component\PropertyInfo\PropertyInfoExtractor; +use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; +use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; +use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; +use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; +use Symfony\Component\Serializer\Serializer; + +class ObjectSerializer implements ObjectSerializerInterface +{ + const PS_SKIP_NULL_VALUES = 'skip_null_values'; + private $serializer; + + public function __construct() + { + $this->serializer = new Serializer( + [ + new ObjectNormalizer(null, null, null, new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()])), + new ArrayDenormalizer(), + ], + [new JsonEncoder()]); + } + + /** + * {@inheritdoc} + */ + public function serialize($data, $format, $skipNullValues = false, $convertToSnakeCase = false, array $context = []) + { + $childContext = [defined('\Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer::SKIP_NULL_VALUES') ? AbstractObjectNormalizer::SKIP_NULL_VALUES : self::PS_SKIP_NULL_VALUES => $skipNullValues]; + + if ($convertToSnakeCase) { + $serializer = new Serializer( + [ + new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter(), null, new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()])), + new ArrayDenormalizer(), + ], + [new JsonEncoder()]); + + return $serializer->serialize($data, $format, array_replace($context, $childContext)); + } + + return $this->serializer->serialize($data, $format, array_replace($context, $childContext)); + } + + /** + * {@inheritdoc} + */ + public function deserialize($data, $type, $format, array $context = []) + { + return $this->serializer->deserialize($data, $type, $format, $context); + } + + /** + * {@inheritdoc} + */ + public function toArray($data, $skipNullValues = false, $convertToSnakeCase = false, array $context = []) + { + return json_decode($this->serialize($data, JsonEncoder::FORMAT, $skipNullValues, $convertToSnakeCase, $context), true); + } +} diff --git a/src/Serializer/ObjectSerializerInterface.php b/src/Serializer/ObjectSerializerInterface.php new file mode 100644 index 000000000..8ec1d701e --- /dev/null +++ b/src/Serializer/ObjectSerializerInterface.php @@ -0,0 +1,57 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Serializer; + +interface ObjectSerializerInterface +{ + /** + * @param mixed $data + * @param string $format + * @param bool $skipNullValues + * @param bool $convertToSnakeCase + * @param array $context + * + * @return string + */ + public function serialize($data, $format, $skipNullValues = false, $convertToSnakeCase = false, array $context = []); + + /** + * @template T + * + * @param string|array $data + * @param class-string $type //Class of the object created. For example CreatePayPalOrderResponse::class + * @param string $format //Format of the data passed. For example JsonEncoder::FORMAT + * @param array $context //Additional parameters. For example skip null values and etc. + * + * @return T + */ + public function deserialize($data, $type, $format, array $context = []); + + /** + * @param mixed $data + * @param bool $skipNullValues + * @param bool $convertToSnakeCase + * @param array $context + * + * @return array + */ + public function toArray($data, $skipNullValues = false, $convertToSnakeCase = false, array $context = []); +} diff --git a/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php index c494f6512..0edea616e 100644 --- a/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php +++ b/tests/Unit/PaymentService/PaymentServiceCreateOrderTest.php @@ -10,6 +10,7 @@ use PrestaShop\Module\PrestashopCheckout\Exception\InvalidRequestException; use PrestaShop\Module\PrestashopCheckout\Exception\NotAuthorizedException; use PrestaShop\Module\PrestashopCheckout\Exception\UnprocessableEntityException; +use PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; @@ -82,7 +83,7 @@ private function handleTestErrorsCreateOrder($statusCode, $errorName, $errorCode $clientMock->method('createOrder')->willThrowException(new HttpException('An error occurred', $requestMock, $responseMock)); $this->expectExceptionCode($errorCode); - $paymentService = new PaymentService($clientMock); + $paymentService = new PaymentService($clientMock, new ObjectSerializer()); $paymentService->createOrder($createRequestMock); } diff --git a/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php b/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php index 692ee3ed5..9255ad1e9 100644 --- a/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php +++ b/tests/Unit/PaymentService/PaymentServiceGetOrderTest.php @@ -18,6 +18,7 @@ class PaymentServiceGetOrderTest extends TestCase { /** * @dataProvider notAuthorizedErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function testNotAuthorizedErrorsGetOrder($errorName, $errorCode) @@ -29,6 +30,7 @@ public function testNotAuthorizedErrorsGetOrder($errorName, $errorCode) * @param int $statusCode * @param string $errorName * @param int $errorCode + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ private function testErrorsGetOrder($statusCode, $errorName, $errorCode) @@ -59,22 +61,22 @@ private function testErrorsGetOrder($statusCode, $errorName, $errorCode) private function getNotAuthorizedError($issueError) { return [ - "name" => $issueError, - "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", - "links" => [ + 'name' => $issueError, + 'message' => 'Authentication failed due to invalid authentication credentials or a missing Authorization header.', + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/overview/#error", - "rel" => "information_link" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/overview/#error', + 'rel' => 'information_link', + ], + ], ]; } private function getInvalidTokenError() { return [ - "error" => "invalid_token", - "error_description" => "Current version only supports token for response_type" + 'error' => 'invalid_token', + 'error_description' => 'Current version only supports token for response_type', ]; } @@ -82,7 +84,7 @@ public function notAuthorizedErrorsProvider() { return [ ['PERMISSION_DENIED', NotAuthorizedException::PERMISSION_DENIED], - ['invalid_token', NotAuthorizedException::INVALID_TOKEN] + ['invalid_token', NotAuthorizedException::INVALID_TOKEN], ]; } } diff --git a/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php b/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php index b5d9c04bd..845fdc317 100644 --- a/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php +++ b/tests/Unit/PaymentService/PaymentServiceUpdateOrderTest.php @@ -19,6 +19,7 @@ class PaymentServiceUpdateOrderTest extends TestCase { /** * @dataProvider invalidRequestErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function testInvalidRequestErrorsUpdateOrder($errorName, $errorCode) @@ -28,6 +29,7 @@ public function testInvalidRequestErrorsUpdateOrder($errorName, $errorCode) /** * @dataProvider notAuthorizedErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function testNotAuthorizedErrorsUpdateOrder($errorName, $errorCode) @@ -37,6 +39,7 @@ public function testNotAuthorizedErrorsUpdateOrder($errorName, $errorCode) /** * @dataProvider unprocessableEntityErrorsProvider + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ public function testUnprocessableEntityErrorsUpdateOrder($errorName, $errorCode) @@ -48,6 +51,7 @@ public function testUnprocessableEntityErrorsUpdateOrder($errorName, $errorCode) * @param int $statusCode * @param string $errorName * @param int $errorCode + * * @throws InvalidRequestException|NotAuthorizedException|UnprocessableEntityException|PsCheckoutException */ private function testErrorsUpdateOrder($statusCode, $errorName, $errorCode) @@ -86,63 +90,63 @@ private function testErrorsUpdateOrder($statusCode, $errorName, $errorCode) private function getInvalidRequestError($issueError) { return [ - "name" => "INVALID_REQUEST", - "message" => "Request is not well-formed, syntactically incorrect, or violates schema.", - "debug_id" => "b6b9a374802ea", - "details" => [ + 'name' => 'INVALID_REQUEST', + 'message' => 'Request is not well-formed, syntactically incorrect, or violates schema.', + 'debug_id' => 'b6b9a374802ea', + 'details' => [ [ - "field" => "", - "value" => "", - "location" => "body", - "issue" => $issueError, - "description" => "" - ] + 'field' => '', + 'value' => '', + 'location' => 'body', + 'issue' => $issueError, + 'description' => '', + ], ], - "links" => [ + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE", - "rel" => "information_link", - "encType" => "application/json" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_PARAMETER_VALUE', + 'rel' => 'information_link', + 'encType' => 'application/json', + ], + ], ]; } private function getNotAuthorizedError($issueError) { return [ - "name" => $issueError, - "message" => "Authentication failed due to invalid authentication credentials or a missing Authorization header.", - "links" => [ + 'name' => $issueError, + 'message' => 'Authentication failed due to invalid authentication credentials or a missing Authorization header.', + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/overview/#error", - "rel" => "information_link" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/overview/#error', + 'rel' => 'information_link', + ], + ], ]; } private function getUnprocessableEntityError($issueError) { return [ - "name" => "UNPROCESSABLE_ENTITY", - "details" => [ + 'name' => 'UNPROCESSABLE_ENTITY', + 'details' => [ [ - "field" => "", - "value" => "", - "issue" => $issueError, - "description" => "" - ] + 'field' => '', + 'value' => '', + 'issue' => $issueError, + 'description' => '', + ], ], - "message" => "The requested action could not be performed, semantically incorrect, or failed business validation.", - "debug_id" => "c9a75b43fc807", - "links" => [ + 'message' => 'The requested action could not be performed, semantically incorrect, or failed business validation.', + 'debug_id' => 'c9a75b43fc807', + 'links' => [ [ - "href" => "https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED", - "rel" => "information_link", - "method" => "GET" - ] - ] + 'href' => 'https://developer.paypal.com/docs/api/orders/v2/#error-MAX_VALUE_EXCEEDED', + 'rel' => 'information_link', + 'method' => 'GET', + ], + ], ]; } @@ -157,7 +161,7 @@ public function invalidRequestErrorsProvider() ['MISSING_REQUIRED_PARAMETER', InvalidRequestException::MISSING_REQUIRED_PARAMETER], ['AMOUNT_NOT_PATCHABLE', InvalidRequestException::AMOUNT_NOT_PATCHABLE], ['INVALID_PATCH_OPERATION', InvalidRequestException::INVALID_PATCH_OPERATION], - ['ERROR_CURRENTLY_UNKNOWN', InvalidRequestException::UNKNOWN] + ['ERROR_CURRENTLY_UNKNOWN', InvalidRequestException::UNKNOWN], ]; } @@ -168,11 +172,12 @@ public function notAuthorizedErrorsProvider() ['PAYEE_ACCOUNT_NOT_SUPPORTED', NotAuthorizedException::PAYEE_ACCOUNT_NOT_SUPPORTED], ['PAYEE_ACCOUNT_NOT_VERIFIED', NotAuthorizedException::PAYEE_ACCOUNT_NOT_VERIFIED], ['PAYEE_NOT_CONSENTED', NotAuthorizedException::PAYEE_NOT_CONSENTED], - ['ERROR_CURRENTLY_UNKNOWN', NotAuthorizedException::UNKNOWN] + ['ERROR_CURRENTLY_UNKNOWN', NotAuthorizedException::UNKNOWN], ]; } - public function unprocessableEntityErrorsProvider() { + public function unprocessableEntityErrorsProvider() + { return [ ['INVALID_JSON_POINTER_FORMAT', UnprocessableEntityException::INVALID_JSON_POINTER_FORMAT], ['INVALID_PARAMETER', UnprocessableEntityException::INVALID_PARAMETER], @@ -187,7 +192,7 @@ public function unprocessableEntityErrorsProvider() { ['MULTIPLE_SHIPPING_OPTION_SELECTED', UnprocessableEntityException::MULTIPLE_SHIPPING_OPTION_SELECTED], ['ORDER_ALREADY_COMPLETED', UnprocessableEntityException::ORDER_ALREADY_COMPLETED], ['PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH', UnprocessableEntityException::PREFERRED_SHIPPING_OPTION_AMOUNT_MISMATCH], - ['ERROR_CURRENTLY_UNKNOWN', UnprocessableEntityException::UNKNOWN] + ['ERROR_CURRENTLY_UNKNOWN', UnprocessableEntityException::UNKNOWN], ]; } } diff --git a/tests/Unit/Serializer/ObjectSerializerTest.php b/tests/Unit/Serializer/ObjectSerializerTest.php new file mode 100644 index 000000000..5099ffc39 --- /dev/null +++ b/tests/Unit/Serializer/ObjectSerializerTest.php @@ -0,0 +1,250 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace Serializer; + +use PHPUnit\Framework\TestCase; +use PrestaShop\Module\PrestashopCheckout\FundingSource\FundingSourceEntity; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CardResponse; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderResponse; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\LinkDescription; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PaymentSourceResponse; +use PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer; +use Symfony\Component\Serializer\Encoder\JsonEncoder; + +class ObjectSerializerTest extends TestCase +{ + /** + * @var ObjectSerializer + */ + private $serializer; + + public function __construct($name = null, array $data = [], $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->serializer = new ObjectSerializer(); + } + + /** + * @dataProvider objectProvider + */ + public function testSerializeWithoutEmptyValues($object, $expectedJson) + { + $json = $this->serializer->serialize($object, JsonEncoder::FORMAT, true); + $this->assertEquals($expectedJson, $json); + } + + /** + * @dataProvider objectWithEmptyValuesProvider + */ + public function testSerializeWithEmptyValues($object, $expectedJson) + { + $json = $this->serializer->serialize($object, JsonEncoder::FORMAT); + $this->assertEquals($expectedJson, $json); + } + + /** + * @dataProvider objectProvider + */ + public function testDeserialize($expectedObject, $json) + { + $newObject = $this->serializer->deserialize($json, FundingSourceEntity::class, JsonEncoder::FORMAT); + $this->assertEquals($expectedObject, $newObject); + } + + /** + * @dataProvider createPayPalOrderResponseSerializeObjectProvider + */ + public function testSerializePayPalOrderResponse($object, $expectedJson) + { + $json = $this->serializer->serialize($object, JsonEncoder::FORMAT, true, true); + $this->assertEquals($expectedJson, $json); + } + + /** + * @dataProvider createPayPalOrderResponseDeserializeObjectProvider + */ + public function testDeserializePayPalOrderResponse($expectedObject, $json) + { + $newObject = $this->serializer->deserialize($json, CreatePayPalOrderResponse::class, JsonEncoder::FORMAT); + $this->assertEquals($expectedObject, $newObject); + } + + /** + * @dataProvider arrayProvider + */ + public function testToArray($object, $expectedArray, $skipNullValues, $convertToSnakeCase) + { + $newArray = $this->serializer->toArray($object, $skipNullValues, $convertToSnakeCase); + $this->assertEquals($expectedArray, $newArray); + } + + public function objectProvider() + { + $fundingSourceEntity = new FundingSourceEntity('paypal'); + $fundingSourceEntity->setCountries(['US', 'FR']); + $fundingSourceEntity->setPosition(0); + + return [ + [ + new FundingSourceEntity('paypal'), + '{"name":"paypal","countries":[],"isEnabled":true,"isToggleable":true}', + ], + [ + $fundingSourceEntity, + '{"name":"paypal","position":0,"countries":["US","FR"],"isEnabled":true,"isToggleable":true}', + ], + ]; + } + + public function objectWithEmptyValuesProvider() + { + $fundingSourceEntity = new FundingSourceEntity('paypal'); + $fundingSourceEntity->setCountries(['US', 'FR']); + $fundingSourceEntity->setPosition(0); + + return [ + [ + new FundingSourceEntity('paypal'), + '{"name":"paypal","position":null,"countries":[],"isEnabled":true,"isToggleable":true}', + ], + [ + $fundingSourceEntity, + '{"name":"paypal","position":0,"countries":["US","FR"],"isEnabled":true,"isToggleable":true}', + ], + ]; + } + + public function createPayPalOrderResponseSerializeObjectProvider() + { + return [ + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]), + '{"id":"SOME_ID","links":[{"href":"HREF","rel":"REL","method":"METHOD"}]}', + ], + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]) + ->setPaymentSource(new PaymentSourceResponse(['card' => new CardResponse(['name' => 'AMEX'])])), + '{"id":"SOME_ID","payment_source":{"card":{"name":"AMEX"}},"links":[{"href":"HREF","rel":"REL","method":"METHOD"}]}', + ], + ]; + } + + public function createPayPalOrderResponseDeserializeObjectProvider() + { + return [ + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]), + '{"id":"SOME_ID","links":[{"href":"HREF","rel":"REL","method":"METHOD"}]}', + ], + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]) + ->setPaymentSource(new PaymentSourceResponse(['card' => new CardResponse(['name' => 'AMEX'])])), + '{"id":"SOME_ID","payment_source":{"card":{"name":"AMEX"}},"links":[{"href":"HREF","rel":"REL","method":"METHOD"}]}', + ], + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]) + ->setPaymentSource(new PaymentSourceResponse(['card' => new CardResponse(['name' => 'AMEX'])])), + '{"id": "SOME_ID","cart_id":"RANDOM_CART_ID","payment_source":{"card":{"name":"AMEX"}},"links":[{"href":"HREF","rel":"REL","method":"METHOD"}]}', + ], + ]; + } + + public function arrayProvider() + { + return [ + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]) + ->setPaymentSource(new PaymentSourceResponse(['card' => new CardResponse(['name' => 'AMEX'])])), + [ + 'id' => 'SOME_ID', + 'create_time' => null, + 'update_time' => null, + 'payment_source' => [ + 'card' => [ + 'name' => 'AMEX', + 'last_digits' => null, + 'brand' => null, + 'available_networks' => null, + 'type' => null, + 'authentication_result' => null, + 'attributes' => null, + 'from_request' => null, + 'expiry' => null, + 'bin_details' => null, + ], + 'paypal' => null, + 'bancontact' => null, + 'blik' => null, + 'eps' => null, + 'giropay' => null, + 'ideal' => null, + 'mybank' => null, + 'p24' => null, + 'sofort' => null, + 'trustly' => null, + 'venmo' => null, + ], + 'intent' => null, + 'processing_instruction' => null, + 'payer' => null, + 'purchase_units' => null, + 'status' => null, + 'links' => [ + ['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'], + ], + ], + false, + true, + ], + [ + (new CreatePayPalOrderResponse()) + ->setId('SOME_ID') + ->setLinks([new LinkDescription(['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'])]) + ->setPaymentSource(new PaymentSourceResponse(['card' => new CardResponse(['name' => 'AMEX'])])), + [ + 'id' => 'SOME_ID', + 'payment_source' => [ + 'card' => [ + 'name' => 'AMEX', + ], + ], + 'links' => [ + ['href' => 'HREF', 'rel' => 'REL', 'method' => 'METHOD'], + ], + ], + true, + true, + ], + ]; + } +} diff --git a/tests/Unit/bootstrap.php b/tests/Unit/bootstrap.php new file mode 100644 index 000000000..ec5e8adab --- /dev/null +++ b/tests/Unit/bootstrap.php @@ -0,0 +1,6 @@ + From 92dea79bbc3c63d8a6b57311a8246850376630da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurynas=20=C5=A0edys?= Date: Tue, 5 Mar 2024 17:20:26 +0200 Subject: [PATCH 21/26] [PAYSHIP-2679] New DB structure for PayPal Order (#1203) * Added new db structure for orders * Added entities for order * Added PayPal Order repository * Added create and delete functions * Added sql escaping * Added order saving to DB to event handler * Added new fields for order, capture and refund * phpstan fix --- config/common.yml | 11 + src/Database/TableManager.php | 53 +++ src/Entity/PayPalOrder.php | 254 ++++++++++ src/Entity/PayPalOrderAuthorization.php | 154 ++++++ src/Entity/PayPalOrderCapture.php | 229 +++++++++ src/Entity/PayPalOrderPurchaseUnit.php | 129 +++++ src/Entity/PayPalOrderRefund.php | 229 +++++++++ .../PayPalOrderEventSubscriber.php | 21 +- src/Repository/PayPalOrderRepository.php | 450 ++++++++++++++++++ upgrade/upgrade-8.4.0.0.php | 100 ++++ 10 files changed, 1629 insertions(+), 1 deletion(-) create mode 100644 src/Entity/PayPalOrder.php create mode 100644 src/Entity/PayPalOrderAuthorization.php create mode 100644 src/Entity/PayPalOrderCapture.php create mode 100644 src/Entity/PayPalOrderPurchaseUnit.php create mode 100644 src/Entity/PayPalOrderRefund.php create mode 100644 src/Repository/PayPalOrderRepository.php create mode 100644 upgrade/upgrade-8.4.0.0.php diff --git a/config/common.yml b/config/common.yml index 8593ccf45..d4ca063cf 100644 --- a/config/common.yml +++ b/config/common.yml @@ -12,6 +12,10 @@ services: arguments: - "ps_checkout" + ps_checkout.db: + class: Db + factory: [ 'Db', 'getInstance' ] + ps_checkout.module.version: class: 'PrestaShop\Module\PrestashopCheckout\Version\Version' factory: ["PrestaShop\\Module\\PrestashopCheckout\\Version\\Version", "buildFromString"] @@ -508,6 +512,7 @@ services: - "@ps_checkout.paypal.order.service.check_transition_paypal_order_status" - "@ps_checkout.order.state.service.order_state_mapper" - '@ps_checkout.paypal.configuration' + - '@PrestaShop\Module\PrestashopCheckout\Repository\PayPalOrderRepository' PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber: class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Payment\Capture\EventSubscriber\PayPalCaptureEventSubscriber' @@ -741,6 +746,12 @@ services: arguments: - '@PrestaShop\Module\PrestashopCheckout\Builder\Configuration\PaymentClientConfigurationBuilder' + + PrestaShop\Module\PrestashopCheckout\Repository\PayPalOrderRepository: + class: 'PrestaShop\Module\PrestashopCheckout\Repository\PayPalOrderRepository' + arguments: + - '@ps_checkout.db' + PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService: class: 'PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' arguments: diff --git a/src/Database/TableManager.php b/src/Database/TableManager.php index 319b4a790..966b5a28f 100644 --- a/src/Database/TableManager.php +++ b/src/Database/TableManager.php @@ -94,6 +94,59 @@ public function createTable() `data` text NOT NULL, PRIMARY KEY (`id_customer`, `paypal_customer_id`) ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_order` ( + `id` varchar(50) NOT NULL, + `id_cart` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `final_capture` tinyint(1) NOT NULL,, + `payment_source` text, + `environment` varchar(50) NOT NULL, + `is_card_fields` tinyint(1) NOT NULL, + `is_express_checkout` tinyint(1) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_capture` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `final_capture` tinyint(1) NOT NULL, + `created_at` varchar(50) NOT NULL, + `updated_at` varchar(50) NOT NULL, + `seller_protection` varchar(50) NOT NULL, + `seller_receivable_breakdown` text, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_refund` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `invoice_id` varchar(50) NOT NULL, + `custom_id` varchar(50) NOT NULL, + `acquirer_reference_number` varchar(50) NOT NULL, + `seller_payable_breakdown` text, + `id_order_slip` INT(10) UNSIGNED, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_authorization` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `expiration_time` varchar(50) NOT NULL, + `seller_protection` varchar(50) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + ') && $this->db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_purchase_unit` ( + `id_order` varchar(50) NOT NULL, + `checksum` varchar(50) NOT NULL, + `reference_id` varchar(50) NOT NULL, + `items` text, + PRIMARY KEY (`reference_id`, `id_order`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; '); $this->checkTable(); diff --git a/src/Entity/PayPalOrder.php b/src/Entity/PayPalOrder.php new file mode 100644 index 000000000..89432257f --- /dev/null +++ b/src/Entity/PayPalOrder.php @@ -0,0 +1,254 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Entity; + +class PayPalOrder +{ + /** + * @var string|null + */ + private $id; + /** + * @var int|null + */ + private $idCart; + /** + * @var string|null + */ + private $intent; + /** + * @var string|null + */ + private $fundingSource; + /** + * @var string|null + */ + private $status; + /** + * @var string|null + */ + private $paymentSource; + /** + * @var string + */ + private $environment; + /** + * @var bool + */ + private $isCardFields; + /** + * @var bool + */ + private $isExpressCheckout; + + public function __construct($id = null, $idCart = null, $intent = null, $fundingSource = null, $status = null, $paymentSource = null, $environment = 'LIVE', $isCardFields = false, $isExpressCheckout = false) + { + $this->id = $id; + $this->idCart = $idCart; + $this->intent = $intent; + $this->fundingSource = $fundingSource; + $this->status = $status; + $this->paymentSource = $paymentSource; + $this->environment = $environment; + $this->isCardFields = (bool) $isCardFields; + $this->isExpressCheckout = (bool) $isExpressCheckout; + } + + /** + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + * + * @return PayPalOrder + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return int|null + */ + public function getIdCart() + { + return $this->idCart; + } + + /** + * @param int $idCart + * + * @return PayPalOrder + */ + public function setIdCart($idCart) + { + $this->idCart = $idCart; + + return $this; + } + + /** + * @return string|null + */ + public function getIntent() + { + return $this->intent; + } + + /** + * @param string $intent + * + * @return PayPalOrder + */ + public function setIntent($intent) + { + $this->intent = $intent; + + return $this; + } + + /** + * @return string|null + */ + public function getFundingSource() + { + return $this->fundingSource; + } + + /** + * @param string $fundingSource + * + * @return PayPalOrder + */ + public function setFundingSource($fundingSource) + { + $this->fundingSource = $fundingSource; + + return $this; + } + + /** + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param string $status + * + * @return PayPalOrder + */ + public function setStatus($status) + { + $this->status = $status; + + return $this; + } + + /** + * @return string|null + */ + public function getPaymentSource() + { + return $this->paymentSource; + } + + /** + * @param string $paymentSource + * + * @return PayPalOrder + */ + public function setPaymentSource($paymentSource) + { + $this->paymentSource = $paymentSource; + + return $this; + } + + /** + * @return string + */ + public function getEnvironment() + { + return $this->environment; + } + + /** + * @param string $environment + * + * @return PayPalOrder + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + + return $this; + } + + /** + * @return bool + */ + public function getIsCardFields() + { + return $this->isCardFields; + } + + /** + * @param bool $isCardFields + * + * @return PayPalOrder + */ + public function setIsCardFields($isCardFields) + { + $this->isCardFields = (bool) $isCardFields; + + return $this; + } + + /** + * @return bool + */ + public function getIsExpressCheckout() + { + return $this->isExpressCheckout; + } + + /** + * @param bool $isExpressCheckout + * + * @return PayPalOrder + */ + public function setIsExpressCheckout($isExpressCheckout) + { + $this->isExpressCheckout = (bool) $isExpressCheckout; + + return $this; + } +} diff --git a/src/Entity/PayPalOrderAuthorization.php b/src/Entity/PayPalOrderAuthorization.php new file mode 100644 index 000000000..adb79221d --- /dev/null +++ b/src/Entity/PayPalOrderAuthorization.php @@ -0,0 +1,154 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Entity; + +class PayPalOrderAuthorization +{ + /** + * @var string|null + */ + private $id; + /** + * @var string|null + */ + private $idOrder; + /** + * @var string|null + */ + private $status; + /** + * @var string|null + */ + private $expirationTime; + /** + * @var string|null + */ + private $sellerProtection; + + public function __construct($id = null, $idOrder = null, $status = null, $expirationTime = null, $sellerProtection = null) + { + $this->id = $id; + $this->idOrder = $idOrder; + $this->status = $status; + $this->expirationTime = $expirationTime; + $this->sellerProtection = $sellerProtection; + } + + /** + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * @param string|null $id + * + * @return PayPalOrderAuthorization + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return string|null + */ + public function getIdOrder() + { + return $this->idOrder; + } + + /** + * @param string|null $idOrder + * + * @return PayPalOrderAuthorization + */ + public function setIdOrder($idOrder) + { + $this->idOrder = $idOrder; + + return $this; + } + + /** + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param string|null $status + * + * @return PayPalOrderAuthorization + */ + public function setStatus($status) + { + $this->status = $status; + + return $this; + } + + /** + * @return string|null + */ + public function getExpirationTime() + { + return $this->expirationTime; + } + + /** + * @param string|null $expirationTime + * + * @return PayPalOrderAuthorization + */ + public function setExpirationTime($expirationTime) + { + $this->expirationTime = $expirationTime; + + return $this; + } + + /** + * @return string|null + */ + public function getSellerProtection() + { + return $this->sellerProtection; + } + + /** + * @param string|null $sellerProtection + * + * @return PayPalOrderAuthorization + */ + public function setSellerProtection($sellerProtection) + { + $this->sellerProtection = $sellerProtection; + + return $this; + } +} diff --git a/src/Entity/PayPalOrderCapture.php b/src/Entity/PayPalOrderCapture.php new file mode 100644 index 000000000..6b3d30c92 --- /dev/null +++ b/src/Entity/PayPalOrderCapture.php @@ -0,0 +1,229 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Entity; + +class PayPalOrderCapture +{ + /** + * @var string|null + */ + private $id; + /** + * @var string|null + */ + private $idOrder; + /** + * @var string|null + */ + private $status; + /** + * @var bool + */ + private $finalCapture; + /** + * @var string|null + */ + private $createdAt; + /** + * @var string|null + */ + private $updatedAt; + /** + * @var string|null + */ + private $sellerProtection; + /** + * @var string|null + */ + private $sellerReceivableBreakdown; + + public function __construct($id = null, $idOrder = null, $status = null, $finalCapture = false, $createdAt = null, $updatedAt = null, $sellerProtection = null, $sellerReceivableBreakdown = null) + { + $this->id = $id; + $this->idOrder = $idOrder; + $this->status = $status; + $this->finalCapture = (bool) $finalCapture; + $this->createdAt = $createdAt; + $this->updatedAt = $updatedAt; + $this->sellerProtection = $sellerProtection; + $this->sellerReceivableBreakdown = $sellerReceivableBreakdown; + } + + /** + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * @param string|null $id + * + * @return PayPalOrderCapture + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return string|null + */ + public function getIdOrder() + { + return $this->idOrder; + } + + /** + * @param string|null $idOrder + * + * @return PayPalOrderCapture + */ + public function setIdOrder($idOrder) + { + $this->idOrder = $idOrder; + + return $this; + } + + /** + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param string|null $status + * + * @return PayPalOrderCapture + */ + public function setStatus($status) + { + $this->status = $status; + + return $this; + } + + /** + * @return bool|mixed + */ + public function getFinalCapture() + { + return $this->finalCapture; + } + + /** + * @param bool $finalCapture + * + * @return PayPalOrderCapture + */ + public function setFinalCapture($finalCapture) + { + $this->finalCapture = (bool) $finalCapture; + + return $this; + } + + /** + * @return string|null + */ + public function getCreatedAt() + { + return $this->createdAt; + } + + /** + * @param string|null $createdAt + * + * @return PayPalOrderCapture + */ + public function setCreatedAt($createdAt) + { + $this->createdAt = $createdAt; + + return $this; + } + + /** + * @return string|null + */ + public function getUpdatedAt() + { + return $this->updatedAt; + } + + /** + * @param string|null $updatedAt + * + * @return PayPalOrderCapture + */ + public function setUpdatedAt($updatedAt) + { + $this->updatedAt = $updatedAt; + + return $this; + } + + /** + * @return string|null + */ + public function getSellerProtection() + { + return $this->sellerProtection; + } + + /** + * @param string $sellerProtection + * + * @return PayPalOrderCapture + */ + public function setSellerProtection($sellerProtection) + { + $this->sellerProtection = $sellerProtection; + + return $this; + } + + /** + * @return string|null + */ + public function getSellerReceivableBreakdown() + { + return $this->sellerReceivableBreakdown; + } + + /** + * @param string $sellerReceivableBreakdown + * + * @return PayPalOrderCapture + */ + public function setSellerReceivableBreakdown($sellerReceivableBreakdown) + { + $this->sellerReceivableBreakdown = $sellerReceivableBreakdown; + + return $this; + } +} diff --git a/src/Entity/PayPalOrderPurchaseUnit.php b/src/Entity/PayPalOrderPurchaseUnit.php new file mode 100644 index 000000000..fa2d7590f --- /dev/null +++ b/src/Entity/PayPalOrderPurchaseUnit.php @@ -0,0 +1,129 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Entity; + +class PayPalOrderPurchaseUnit +{ + /** + * @var string|null + */ + private $idOrder; + /** + * @var string|null + */ + private $checksum; + /** + * @var string|null + */ + private $referenceId; + /** + * @var string|null + */ + private $items; + + public function __construct($idOrder = null, $checksum = null, $referenceId = null, $items = null) + { + $this->idOrder = $idOrder; + $this->checksum = $checksum; + $this->referenceId = $referenceId; + $this->items = $items; + } + + /** + * @return string|null + */ + public function getIdOrder() + { + return $this->idOrder; + } + + /** + * @param string|null $idOrder + * + * @return PayPalOrderPurchaseUnit + */ + public function setIdOrder($idOrder) + { + $this->idOrder = $idOrder; + + return $this; + } + + /** + * @return string|null + */ + public function getChecksum() + { + return $this->checksum; + } + + /** + * @param string|null $checksum + * + * @return PayPalOrderPurchaseUnit + */ + public function setChecksum($checksum) + { + $this->checksum = $checksum; + + return $this; + } + + /** + * @return string|null + */ + public function getReferenceId() + { + return $this->referenceId; + } + + /** + * @param string|null $referenceId + * + * @return PayPalOrderPurchaseUnit + */ + public function setReferenceId($referenceId) + { + $this->referenceId = $referenceId; + + return $this; + } + + /** + * @return string|null + */ + public function getItems() + { + return $this->items; + } + + /** + * @param string|null $items + * + * @return PayPalOrderPurchaseUnit + */ + public function setItems($items) + { + $this->items = $items; + + return $this; + } +} diff --git a/src/Entity/PayPalOrderRefund.php b/src/Entity/PayPalOrderRefund.php new file mode 100644 index 000000000..50ec416a9 --- /dev/null +++ b/src/Entity/PayPalOrderRefund.php @@ -0,0 +1,229 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Entity; + +class PayPalOrderRefund +{ + /** + * @var string|null + */ + private $id; + /** + * @var string|null + */ + private $idOrder; + /** + * @var string|null + */ + private $status; + /** + * @var string|null + */ + private $invoiceId; + /** + * @var string|null + */ + private $customId; + /** + * @var string|null + */ + private $acquirerReferenceNumber; + /** + * @var string|null + */ + private $sellerPayableBreakdown; + /** + * @var int + */ + private $idOrderSlip; + + public function __construct($id = null, $idOrder = null, $status = null, $invoiceId = null, $customId = null, $acquirerReferenceNumber = null, $sellerPayableBreakdown = null, $idOrderSlip = null) + { + $this->id = $id; + $this->idOrder = $idOrder; + $this->status = $status; + $this->invoiceId = $invoiceId; + $this->customId = $customId; + $this->acquirerReferenceNumber = $acquirerReferenceNumber; + $this->sellerPayableBreakdown = $sellerPayableBreakdown; + $this->idOrderSlip = $idOrderSlip; + } + + /** + * @return string|null + */ + public function getId() + { + return $this->id; + } + + /** + * @param string|null $id + * + * @return PayPalOrderRefund + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return string|null + */ + public function getIdOrder() + { + return $this->idOrder; + } + + /** + * @param string|null $idOrder + * + * @return PayPalOrderRefund + */ + public function setIdOrder($idOrder) + { + $this->idOrder = $idOrder; + + return $this; + } + + /** + * @return string|null + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param string|null $status + * + * @return PayPalOrderRefund + */ + public function setStatus($status) + { + $this->status = $status; + + return $this; + } + + /** + * @return string|null + */ + public function getInvoiceId() + { + return $this->invoiceId; + } + + /** + * @param string|null $invoiceId + * + * @return PayPalOrderRefund + */ + public function setInvoiceId($invoiceId) + { + $this->invoiceId = $invoiceId; + + return $this; + } + + /** + * @return string|null + */ + public function getCustomId() + { + return $this->customId; + } + + /** + * @param string|null $customId + * + * @return PayPalOrderRefund + */ + public function setCustomId($customId) + { + $this->customId = $customId; + + return $this; + } + + /** + * @return string|null + */ + public function getAcquirerReferenceNumber() + { + return $this->acquirerReferenceNumber; + } + + /** + * @param string|null $acquirerReferenceNumber + * + * @return PayPalOrderRefund + */ + public function setAcquirerReferenceNumber($acquirerReferenceNumber) + { + $this->acquirerReferenceNumber = $acquirerReferenceNumber; + + return $this; + } + + /** + * @return string|null + */ + public function getSellerPayableBreakdown() + { + return $this->sellerPayableBreakdown; + } + + /** + * @param string|null $sellerPayableBreakdown + * + * @return PayPalOrderRefund + */ + public function setSellerPayableBreakdown($sellerPayableBreakdown) + { + $this->sellerPayableBreakdown = $sellerPayableBreakdown; + + return $this; + } + + /** + * @return int|null + */ + public function getIdOrderSlip() + { + return $this->idOrderSlip; + } + + /** + * @param int $idOrderSlip + * + * @return PayPalOrderRefund + */ + public function setIdOrderSlip($idOrderSlip) + { + $this->idOrderSlip = (int) $idOrderSlip; + + return $this; + } +} diff --git a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php index 475a9b452..1d3709830 100644 --- a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php +++ b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php @@ -25,6 +25,7 @@ use PrestaShop\Module\PrestashopCheckout\Checkout\Command\SaveCheckoutCommand; use PrestaShop\Module\PrestashopCheckout\Checkout\Command\SavePayPalOrderStatusCommand; use PrestaShop\Module\PrestashopCheckout\CommandBus\CommandBusInterface; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrder; use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; use PrestaShop\Module\PrestashopCheckout\Order\Command\UpdateOrderStatusCommand; use PrestaShop\Module\PrestashopCheckout\Order\Exception\OrderNotFoundException; @@ -42,6 +43,7 @@ use PrestaShop\Module\PrestashopCheckout\PayPal\Order\Event\PayPalOrderUpdatedEvent; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\PayPalOrderStatus; use PrestaShop\Module\PrestashopCheckout\PayPal\PayPalConfiguration; +use PrestaShop\Module\PrestashopCheckout\Repository\PayPalOrderRepository; use PrestaShop\Module\PrestashopCheckout\Repository\PsCheckoutCartRepository; use Ps_checkout; use Psr\SimpleCache\CacheInterface; @@ -87,6 +89,10 @@ class PayPalOrderEventSubscriber implements EventSubscriberInterface * @var PayPalConfiguration */ private $payPalConfiguration; + /** + * @var PayPalOrderRepository + */ + private $payPalOrderRepository; public function __construct( Ps_checkout $module, @@ -95,7 +101,8 @@ public function __construct( CheckoutChecker $checkoutChecker, CheckTransitionPayPalOrderStatusService $checkTransitionPayPalOrderStatusService, OrderStateMapper $orderStateMapper, - PayPalConfiguration $payPalConfiguration + PayPalConfiguration $payPalConfiguration, + PayPalOrderRepository $payPalOrderRepository ) { $this->module = $module; $this->psCheckoutCartRepository = $psCheckoutCartRepository; @@ -105,6 +112,7 @@ public function __construct( $this->orderStateMapper = $orderStateMapper; $this->commandBus = $this->module->getService('ps_checkout.bus.command'); $this->payPalConfiguration = $payPalConfiguration; + $this->payPalOrderRepository = $payPalOrderRepository; } /** @@ -141,6 +149,17 @@ public function saveCreatedPayPalOrder(PayPalOrderCreatedEvent $event) { $order = $event->getOrderPayPal(); + $payPalOrder = new PayPalOrder( + $order['id'], + $event->getCartId(), + $order['intent'], + array_keys($order['payment_source'])[0], + $order['status'], + json_encode($order['payment_source']) + ); + + $this->payPalOrderRepository->createPayPalOrder($payPalOrder); + $this->commandBus->handle(new SaveCheckoutCommand( $event->getCartId()->getValue(), $event->getOrderPayPalId()->getValue(), diff --git a/src/Repository/PayPalOrderRepository.php b/src/Repository/PayPalOrderRepository.php new file mode 100644 index 000000000..34ffb71ee --- /dev/null +++ b/src/Repository/PayPalOrderRepository.php @@ -0,0 +1,450 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\Repository; + +use Db; +use DbQuery; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrder; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrderAuthorization; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrderCapture; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrderPurchaseUnit; +use PrestaShop\Module\PrestashopCheckout\Entity\PayPalOrderRefund; +use PrestaShop\PrestaShop\Core\Foundation\Database\EntityNotFoundException; +use PrestaShopDatabaseException; + +class PayPalOrderRepository +{ + const TABLE_ORDER = 'pscheckout_order'; + const TABLE_CAPTURE = 'pscheckout_capture'; + const TABLE_REFUND = 'pscheckout_refund'; + const TABLE_AUTHORIZATION = 'pscheckout_authorization'; + const TABLE_PURCHASE_UNIT = 'pscheckout_purchase_unit'; + + /** + * @var Db + */ + private $db; + + public function __construct(Db $db) + { + $this->db = $db; + } + + /** + * @param PayPalOrder $payPalOrder + * + * @return bool + * + * @throws PrestaShopDatabaseException + */ + public function createPayPalOrder(PayPalOrder $payPalOrder) + { + return $this->db->insert( + self::TABLE_ORDER, + [ + 'id' => pSQL($payPalOrder->getId()), + 'id_cart' => (int) $payPalOrder->getIdCart(), + 'funding_source' => pSQL($payPalOrder->getFundingSource()), + 'status' => pSQL($payPalOrder->getStatus()), + 'payment_source' => pSQL($payPalOrder->getPaymentSource()), + 'environment' => pSQL($payPalOrder->getEnvironment()), + 'is_card_fields' => $payPalOrder->getIsCardFields(), + 'is_express_checkout' => $payPalOrder->getIsExpressCheckout(), + ] + ); + } + + /** + * @param string $payPalOrderId + * + * @return PayPalOrder + * + * @throws EntityNotFoundException + */ + public function getPayPalOrderById($payPalOrderId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_ORDER, 'o') + ->where('o.`id_order` = ' . pSQL($payPalOrderId)); + $queryResult = $this->db->getRow($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + + return new PayPalOrder($queryResult['id'], (int) $queryResult['id_cart'], $queryResult['funding_source'], $queryResult['status'], $queryResult['payment_source']); + } + + /** + * @param int $cartId + * + * @return PayPalOrder + * + * @throws EntityNotFoundException + */ + public function getPayPalOrderByCartId($cartId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_ORDER, 'o') + ->where('o.`id_cart` = ' . (int) $cartId); + $queryResult = $this->db->getRow($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + + return new PayPalOrder($queryResult['id'], (int) $queryResult['id_cart'], $queryResult['funding_source'], $queryResult['status'], $queryResult['payment_source']); + } + + /** + * @param PayPalOrder $payPalOrder + * + * @return bool + */ + public function updatePayPalOrder(PayPalOrder $payPalOrder) + { + return $this->db->update( + self::TABLE_ORDER, + [ + 'funding_source' => pSQL($payPalOrder->getFundingSource()), + 'status' => pSQL($payPalOrder->getStatus()), + 'payment_source' => pSQL($payPalOrder->getPaymentSource()), + 'is_card_fields' => $payPalOrder->getIsCardFields(), + 'is_express_checkout' => $payPalOrder->getIsExpressCheckout(), + ], + '`id` = ' . pSQL($payPalOrder->getId()) + ); + } + + /** + * @param string $payPalOrderId + * + * @return bool + */ + public function deletePayPalOrder($payPalOrderId) + { + $orderId = pSQL($payPalOrderId); + $sql = 'DELETE FROM `' . _DB_PREFIX_ . self::TABLE_ORDER . "` WHERE `id` = $orderId;" + . 'DELETE FROM `' . _DB_PREFIX_ . self::TABLE_AUTHORIZATION . "` WHERE `id_order` = $orderId;" + . 'DELETE FROM `' . _DB_PREFIX_ . self::TABLE_REFUND . "` WHERE `id_order` = $orderId;" + . 'DELETE FROM `' . _DB_PREFIX_ . self::TABLE_CAPTURE . "` WHERE `id_order` = $orderId;" + . 'DELETE FROM `' . _DB_PREFIX_ . self::TABLE_PURCHASE_UNIT . "` WHERE `id_order` = $orderId;"; + + return $this->db->execute($sql); + } + + /** + * @param PayPalOrderAuthorization $payPalOrderAuthorization + * + * @return bool + * + * @throws PrestaShopDatabaseException + */ + public function createPayPalOrderAuthorization(PayPalOrderAuthorization $payPalOrderAuthorization) + { + return $this->db->insert( + self::TABLE_AUTHORIZATION, + [ + 'id' => pSQL($payPalOrderAuthorization->getId()), + 'id_order' => pSQL($payPalOrderAuthorization->getIdOrder()), + 'status' => pSQL($payPalOrderAuthorization->getStatus()), + 'expiration_time' => pSQL($payPalOrderAuthorization->getExpirationTime()), + 'seller_protection' => pSQL($payPalOrderAuthorization->getSellerProtection()), + ] + ); + } + + /** + * @param string $payPalOrderId + * + * @return PayPalOrderAuthorization[] + * + * @throws EntityNotFoundException + * @throws PrestaShopDatabaseException + */ + public function getPayPalOrderAuthorizations($payPalOrderId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_AUTHORIZATION, 'a') + ->where('a.`id_order` = ' . pSQL($payPalOrderId)); + $queryResult = $this->db->executeS($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + + if (array_key_exists(0, $queryResult)) { + $queryResult = [$queryResult]; + } + + return array_map(function ($authorization) { + return new PayPalOrderAuthorization( + $authorization['id'], + $authorization['id_order'], + $authorization['status'], + $authorization['expiration_time'], + $authorization['seller_protection'] + ); + }, $queryResult); + } + + /** + * @param PayPalOrderAuthorization $payPalOrderAuthorization + * + * @return bool + */ + public function updateAuthorization(PayPalOrderAuthorization $payPalOrderAuthorization) + { + return $this->db->update( + self::TABLE_AUTHORIZATION, + [ + 'status' => pSQL($payPalOrderAuthorization->getStatus()), + 'expiration_time' => pSQL($payPalOrderAuthorization->getExpirationTime()), + 'seller_protection' => pSQL($payPalOrderAuthorization->getSellerProtection()), + ], + '`id` = ' . pSQL($payPalOrderAuthorization->getId()) + ); + } + + /** + * @param PayPalOrderCapture $payPalOrderCapture + * + * @return bool + * + * @throws PrestaShopDatabaseException + */ + public function createPayPalOrderCapture(PayPalOrderCapture $payPalOrderCapture) + { + return $this->db->insert( + self::TABLE_CAPTURE, + [ + 'id' => pSQL($payPalOrderCapture->getId()), + 'id_order' => pSQL($payPalOrderCapture->getIdOrder()), + 'status' => pSQL($payPalOrderCapture->getStatus()), + 'final_capture' => (bool) $payPalOrderCapture->getFinalCapture(), + 'created_at' => pSQL($payPalOrderCapture->getCreatedAt()), + 'updated_at' => pSQL($payPalOrderCapture->getUpdatedAt()), + 'seller_protection' => pSQL($payPalOrderCapture->getSellerProtection()), + 'seller_receivable_breakdown' => pSQL($payPalOrderCapture->getSellerReceivableBreakdown()), + ] + ); + } + + /** + * @param string $payPalOrderId + * + * @return PayPalOrderCapture[] + * + * @throws EntityNotFoundException + * @throws PrestaShopDatabaseException + */ + public function getPayPalOrderCaptures($payPalOrderId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_CAPTURE, 'c') + ->where('c.`id_order` = ' . pSQL($payPalOrderId)); + $queryResult = $this->db->executeS($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + + if (array_key_exists(0, $queryResult)) { + $queryResult = [$queryResult]; + } + + return array_map(function ($capture) { + return new PayPalOrderCapture( + $capture['id'], + $capture['id_order'], + $capture['status'], + $capture['final_capture'], + $capture['created_at'], + $capture['updated_at'], + $capture['seller_protection'], + $capture['seller_receivable_breakdown'] + ); + }, $queryResult); + } + + /** + * @param PayPalOrderCapture $payPalOrderCapture + * + * @return bool + */ + public function updateCapture(PayPalOrderCapture $payPalOrderCapture) + { + return $this->db->update( + self::TABLE_CAPTURE, + [ + 'status' => pSQL($payPalOrderCapture->getStatus()), + 'final_capture' => pSQL($payPalOrderCapture->getFinalCapture()), + 'created_at' => pSQL($payPalOrderCapture->getCreatedAt()), + 'updated_at' => pSQL($payPalOrderCapture->getUpdatedAt()), + 'seller_protection' => pSQL($payPalOrderCapture->getSellerProtection()), + 'seller_receivable_breakdown' => pSQL($payPalOrderCapture->getSellerReceivableBreakdown()), + ], + '`id` = ' . pSQL($payPalOrderCapture->getId()) + ); + } + + /** + * @param PayPalOrderRefund $payPalOrderRefund + * + * @return bool + * + * @throws PrestaShopDatabaseException + */ + public function createPayPalOrderRefund(PayPalOrderRefund $payPalOrderRefund) + { + return $this->db->insert( + self::TABLE_REFUND, + [ + 'id' => pSQL($payPalOrderRefund->getId()), + 'id_order' => pSQL($payPalOrderRefund->getIdOrder()), + 'status' => pSQL($payPalOrderRefund->getStatus()), + 'invoice_id' => pSQL($payPalOrderRefund->getStatus()), + 'custom_id' => pSQL($payPalOrderRefund->getCustomId()), + 'acquirer_reference_number' => pSQL($payPalOrderRefund->getAcquirerReferenceNumber()), + 'seller_payable_breakdown' => pSQL($payPalOrderRefund->getSellerPayableBreakdown()), + 'id_order_slip' => (int) $payPalOrderRefund->getIdOrderSlip(), + ] + ); + } + + /** + * @param string $payPalOrderId + * + * @return PayPalOrderRefund[] + * + * @throws EntityNotFoundException + * @throws PrestaShopDatabaseException + */ + public function getPayPalOrderRefunds($payPalOrderId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_REFUND, 'r') + ->where('r.`id_order` = ' . pSQL($payPalOrderId)); + $queryResult = $this->db->executeS($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + if (array_key_exists(0, $queryResult)) { + $queryResult = [$queryResult]; + } + + return array_map(function ($refund) { + return new PayPalOrderRefund( + $refund['id'], + $refund['id_order'], + $refund['status'], + $refund['invoice_id'], + $refund['custom_id'], + $refund['acquirer_reference_number'], + $refund['seller_payable_breakdown'], + $refund['id_order_slip'] + ); + }, $queryResult); + } + + /** + * @param PayPalOrderRefund $payPalOrderRefund + * + * @return bool + */ + public function updateRefund(PayPalOrderRefund $payPalOrderRefund) + { + return $this->db->update( + self::TABLE_REFUND, + [ + 'status' => pSQL($payPalOrderRefund->getStatus()), + 'invoice_id' => pSQL($payPalOrderRefund->getInvoiceId()), + 'custom_id' => pSQL($payPalOrderRefund->getCustomId()), + 'acquirer_reference_number' => pSQL($payPalOrderRefund->getAcquirerReferenceNumber()), + 'seller_payable_breakdown' => pSQL($payPalOrderRefund->getSellerPayableBreakdown()), + ], + '`id` = ' . pSQL($payPalOrderRefund->getId()) + ); + } + + public function createPayPalOrderPurchaseUnit(PayPalOrderPurchaseUnit $payPalOrderPurchaseUnit) + { + return $this->db->insert( + self::TABLE_REFUND, + [ + 'id_order' => pSQL($payPalOrderPurchaseUnit->getIdOrder()), + 'checksum' => pSQL($payPalOrderPurchaseUnit->getChecksum()), + 'reference_id' => pSQL($payPalOrderPurchaseUnit->getReferenceId()), + 'items' => pSQL($payPalOrderPurchaseUnit->getItems()), + ] + ); + } + + /** + * @param string $payPalOrderId + * + * @return PayPalOrderPurchaseUnit[] + * + * @throws EntityNotFoundException + * @throws PrestaShopDatabaseException + */ + public function getPayPalOrderPurchaseUnits($payPalOrderId) + { + $query = new DbQuery(); + $query->select('*') + ->from(self::TABLE_PURCHASE_UNIT, 'p') + ->where('p.`id_order` = ' . pSQL($payPalOrderId)); + $queryResult = $this->db->executeS($query); + if (!$queryResult) { + throw new EntityNotFoundException('PayPal Order not found'); + } + if (array_key_exists(0, $queryResult)) { + $queryResult = [$queryResult]; + } + + return array_map(function ($purchaseUnit) { + return new PayPalOrderPurchaseUnit( + $purchaseUnit['id_order'], + $purchaseUnit['checksum'], + $purchaseUnit['reference_id'], + $purchaseUnit['items'] + ); + }, $queryResult); + } + + /** + * @param PayPalOrderPurchaseUnit $payPalOrderPurchaseUnit + * + * @return bool + */ + public function updatePurchaseUnit(PayPalOrderPurchaseUnit $payPalOrderPurchaseUnit) + { + return $this->db->update( + self::TABLE_PURCHASE_UNIT, + [ + 'checksum' => $payPalOrderPurchaseUnit->getChecksum(), + 'items' => $payPalOrderPurchaseUnit->getItems(), + ], + '`id_order` = ' . pSQL($payPalOrderPurchaseUnit->getIdOrder() . ' AND `reference_id` = ' . $payPalOrderPurchaseUnit->getReferenceId()) + ); + } +} diff --git a/upgrade/upgrade-8.4.0.0.php b/upgrade/upgrade-8.4.0.0.php new file mode 100644 index 000000000..36be963fa --- /dev/null +++ b/upgrade/upgrade-8.4.0.0.php @@ -0,0 +1,100 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * Update main function for module version 8.4.0.0 + * + * @param Ps_checkout $module + * + * @return bool + */ +function upgrade_module_8_4_0_0($module) +{ + try { + $db = Db::getInstance(); + $db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_order` ( + `id` varchar(50) NOT NULL, + `id_cart` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `funding_source` varchar(50) NOT NULL, + `payment_source` text, + `environment` varchar(50) NOT NULL, + `is_card_fields` tinyint(1) NOT NULL, + `is_express_checkout` tinyint(1) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + '); + $db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_capture` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `final_capture` tinyint(1) NOT NULL, + `created_at` varchar(50) NOT NULL, + `updated_at` varchar(50) NOT NULL, + `seller_protection` varchar(50) NOT NULL, + `seller_receivable_breakdown` text, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + '); + $db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_refund` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `invoice_id` varchar(50) NOT NULL, + `custom_id` varchar(50) NOT NULL, + `acquirer_reference_number` varchar(50) NOT NULL, + `seller_payable_breakdown` text, + `id_order_slip` INT(10) UNSIGNED, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + '); + $db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_authorization` ( + `id` varchar(50) NOT NULL, + `id_order` varchar(50) NOT NULL, + `status` varchar(50) NOT NULL, + `expiration_time` varchar(50) NOT NULL, + `seller_protection` varchar(50) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + '); + $db->execute(' + CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pscheckout_purchase_unit` ( + `id_order` varchar(50) NOT NULL, + `checksum` varchar(50) NOT NULL, + `reference_id` varchar(50) NOT NULL, + `items` text, + PRIMARY KEY (`reference_id`, `id_order`) + ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8; + '); + } catch (Exception $exception) { + PrestaShopLogger::addLog($exception->getMessage(), 4, 1, 'Module', $module->id); + + return false; + } + + return true; +} From 1267349cf9080b9828815601f7be941e179a7f3e Mon Sep 17 00:00:00 2001 From: Laurynas Date: Tue, 5 Mar 2024 17:38:19 +0200 Subject: [PATCH 22/26] Updated PayPal order getters and removed PsCheckoutCart creation --- src/Entity/PayPalOrder.php | 4 ++-- src/PayPal/Order/Event/PayPalOrderCreatedEvent.php | 14 ++++++-------- .../EventSubscriber/PayPalOrderEventSubscriber.php | 14 ++++++++++++-- src/Repository/PayPalOrderRepository.php | 8 ++++---- 4 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/Entity/PayPalOrder.php b/src/Entity/PayPalOrder.php index 89432257f..b4594f926 100644 --- a/src/Entity/PayPalOrder.php +++ b/src/Entity/PayPalOrder.php @@ -215,7 +215,7 @@ public function setEnvironment($environment) /** * @return bool */ - public function getIsCardFields() + public function isCardFields() { return $this->isCardFields; } @@ -235,7 +235,7 @@ public function setIsCardFields($isCardFields) /** * @return bool */ - public function getIsExpressCheckout() + public function isExpressCheckout() { return $this->isExpressCheckout; } diff --git a/src/PayPal/Order/Event/PayPalOrderCreatedEvent.php b/src/PayPal/Order/Event/PayPalOrderCreatedEvent.php index 53c1e46ee..da19c5091 100644 --- a/src/PayPal/Order/Event/PayPalOrderCreatedEvent.php +++ b/src/PayPal/Order/Event/PayPalOrderCreatedEvent.php @@ -34,13 +34,11 @@ class PayPalOrderCreatedEvent extends PayPalOrderEvent /** * @var bool */ - private $isHostedFields; - + private $isCardFields; /** * @var bool */ private $isExpressCheckout; - /** * @var string */ @@ -50,18 +48,18 @@ class PayPalOrderCreatedEvent extends PayPalOrderEvent * @param string $orderPayPalId * @param array $orderPayPal * @param int $cartId - * @param bool $isHostedFields + * @param bool $isCardFields * @param bool $isExpressCheckout * @param string $fundingSource * * @throws CartException * @throws PayPalOrderException */ - public function __construct($orderPayPalId, $orderPayPal, $cartId, $isHostedFields, $isExpressCheckout, $fundingSource) + public function __construct($orderPayPalId, $orderPayPal, $cartId, $isCardFields, $isExpressCheckout, $fundingSource) { parent::__construct($orderPayPalId, $orderPayPal); $this->cartId = new CartId($cartId); - $this->isHostedFields = $isHostedFields; + $this->isCardFields = $isCardFields; $this->isExpressCheckout = $isExpressCheckout; $this->fundingSource = $fundingSource; } @@ -77,9 +75,9 @@ public function getCartId() /** * @return bool */ - public function isHostedFields() + public function isCardFields() { - return $this->isHostedFields; + return $this->isCardFields; } /** diff --git a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php index 1d3709830..5291453aa 100644 --- a/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php +++ b/src/PayPal/Order/EventSubscriber/PayPalOrderEventSubscriber.php @@ -45,6 +45,7 @@ use PrestaShop\Module\PrestashopCheckout\PayPal\PayPalConfiguration; use PrestaShop\Module\PrestashopCheckout\Repository\PayPalOrderRepository; use PrestaShop\Module\PrestashopCheckout\Repository\PsCheckoutCartRepository; +use PrestaShop\PrestaShop\Core\Foundation\Database\EntityNotFoundException; use Ps_checkout; use Psr\SimpleCache\CacheInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; @@ -149,13 +150,22 @@ public function saveCreatedPayPalOrder(PayPalOrderCreatedEvent $event) { $order = $event->getOrderPayPal(); + try { // NOT SURE WHAT SHOULD HAPPEN IF ORDER WITH THAT ID ALREADY EXISTS + $payPalOrder = $this->payPalOrderRepository->getPayPalOrderById($event->getOrderPayPalId()->getValue()); + $this->payPalOrderRepository->deletePayPalOrder($payPalOrder->getId()); + } catch (EntityNotFoundException $e) { + } + $payPalOrder = new PayPalOrder( $order['id'], $event->getCartId(), $order['intent'], array_keys($order['payment_source'])[0], $order['status'], - json_encode($order['payment_source']) + json_encode($order['payment_source']), + $this->payPalConfiguration->getPaymentMode(), + $event->isCardFields(), + $event->isExpressCheckout() ); $this->payPalOrderRepository->createPayPalOrder($payPalOrder); @@ -167,7 +177,7 @@ public function saveCreatedPayPalOrder(PayPalOrderCreatedEvent $event) $order['intent'], $event->getFundingSource(), $event->isExpressCheckout(), - $event->isHostedFields(), + $event->isCardFields(), $this->payPalConfiguration->getPaymentMode() )); } diff --git a/src/Repository/PayPalOrderRepository.php b/src/Repository/PayPalOrderRepository.php index 34ffb71ee..92e6a5c84 100644 --- a/src/Repository/PayPalOrderRepository.php +++ b/src/Repository/PayPalOrderRepository.php @@ -66,8 +66,8 @@ public function createPayPalOrder(PayPalOrder $payPalOrder) 'status' => pSQL($payPalOrder->getStatus()), 'payment_source' => pSQL($payPalOrder->getPaymentSource()), 'environment' => pSQL($payPalOrder->getEnvironment()), - 'is_card_fields' => $payPalOrder->getIsCardFields(), - 'is_express_checkout' => $payPalOrder->getIsExpressCheckout(), + 'is_card_fields' => $payPalOrder->isCardFields(), + 'is_express_checkout' => $payPalOrder->isExpressCheckout(), ] ); } @@ -127,8 +127,8 @@ public function updatePayPalOrder(PayPalOrder $payPalOrder) 'funding_source' => pSQL($payPalOrder->getFundingSource()), 'status' => pSQL($payPalOrder->getStatus()), 'payment_source' => pSQL($payPalOrder->getPaymentSource()), - 'is_card_fields' => $payPalOrder->getIsCardFields(), - 'is_express_checkout' => $payPalOrder->getIsExpressCheckout(), + 'is_card_fields' => $payPalOrder->isCardFields(), + 'is_express_checkout' => $payPalOrder->isExpressCheckout(), ], '`id` = ' . pSQL($payPalOrder->getId()) ); From 8547e256e8cbe2fe33573cbc78b23c0534850e66 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Thu, 7 Mar 2024 13:37:18 +0200 Subject: [PATCH 23/26] Fixed oldPaymentClient --- src/Api/Payment/Client/OldPaymentClient.php | 179 +++++++++++++++++++- 1 file changed, 170 insertions(+), 9 deletions(-) diff --git a/src/Api/Payment/Client/OldPaymentClient.php b/src/Api/Payment/Client/OldPaymentClient.php index 031705987..8a4719df2 100755 --- a/src/Api/Payment/Client/OldPaymentClient.php +++ b/src/Api/Payment/Client/OldPaymentClient.php @@ -20,27 +20,188 @@ namespace PrestaShop\Module\PrestashopCheckout\Api\Payment\Client; -use PrestaShop\Module\PrestashopCheckout\Http\PsrClientAdapter; -use Psr\Http\Message\RequestInterface; +use Context; +use GuzzleHttp\Event\Emitter; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Subscriber\Log\Formatter; +use GuzzleHttp\Subscriber\Log\LogSubscriber; +use GuzzleLogMiddleware\LogMiddleware; +use Link; +use Module; +use PrestaShop\Module\PrestashopCheckout\Api\GenericClient; +use PrestaShop\Module\PrestashopCheckout\Environment\PaymentEnv; +use PrestaShop\Module\PrestashopCheckout\Exception\HttpTimeoutException; +use PrestaShop\Module\PrestashopCheckout\Exception\PsCheckoutException; +use PrestaShop\Module\PrestashopCheckout\Logger\LoggerConfiguration; +use PrestaShop\Module\PrestashopCheckout\Routing\Router; +use PrestaShop\Module\PrestashopCheckout\ShopContext; +use PrestaShop\Module\PrestashopCheckout\Version\Version; +use Prestashop\ModuleLibGuzzleAdapter\ClientFactory; +use Ps_checkout; +use Psr\Log\LoggerInterface; /** * Construct the client used to make call to maasland */ class OldPaymentClient extends GenericClient { - /** @var PsrClientAdapter */ - private $client; + /** + * @param Link $link + * @param object|null $client + */ + public function __construct(Link $link, $client = null) + { + parent::__construct(); + + $this->setLink($link); + + // Client can be provided for tests + if (null === $client) { + /** @var Ps_checkout $module */ + $module = Module::getInstanceByName('ps_checkout'); + + /** @var Version $version */ + $version = $module->getService('ps_checkout.module.version'); + + /** @var LoggerConfiguration $loggerConfiguration */ + $loggerConfiguration = $module->getService('ps_checkout.logger.configuration'); + + /** @var LoggerInterface $logger */ + $logger = $module->getService('ps_checkout.logger'); - public function __construct(PaymentClientConfigurationBuilder $configurationBuilder) + /** @var Router $router */ + $router = $module->getService('ps_checkout.prestashop.router'); + + $clientConfiguration = [ + 'base_url' => (new PaymentEnv())->getPaymentApiUrl(), + 'verify' => $this->getVerify(), + 'timeout' => $this->timeout, + 'exceptions' => $this->catchExceptions, + 'headers' => [ + 'Content-Type' => 'application/vnd.checkout.v1+json', // api version to use (psl side) + 'Accept' => 'application/json', + 'Authorization' => 'Bearer ' . $this->token, // Token we get from PsAccounts + 'Shop-Id' => $this->shopUid, // Shop UUID we get from PsAccounts + 'Hook-Url' => $router->getDispatchWebhookLink((int) Context::getContext()->shop->id), + 'Bn-Code' => (new ShopContext())->getBnCode(), + 'Module-Version' => $version->getSemVersion(), // version of the module + 'Prestashop-Version' => _PS_VERSION_, // prestashop version + ], + ]; + + if ( + $loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION') + && class_exists(HandlerStack::class) + && class_exists(LogMiddleware::class) + ) { + $handlerStack = HandlerStack::create(); + $handlerStack->push(new LogMiddleware($logger)); + $clientConfiguration['handler'] = $handlerStack; + } elseif ( + $loggerConfiguration->isHttpEnabled() + && defined('\GuzzleHttp\ClientInterface::VERSION') + && class_exists(Emitter::class) + && class_exists(LogSubscriber::class) + && class_exists(Formatter::class) + ) { + $emitter = new Emitter(); + $emitter->attach(new LogSubscriber( + $logger, + Formatter::DEBUG + )); + + $clientConfiguration['emitter'] = $emitter; + } + + $client = (new ClientFactory())->getClient($clientConfiguration); + } + + $this->setClient($client); + } + + /** + * @param array $options + * + * @return array + * + * @throws HttpTimeoutException + */ + protected function post(array $options = []) { - $this->client = new PsrClientAdapter($configurationBuilder->build()); + $delay = isset($options['delay']) ? (int) $options['delay'] : 2; + $retries = isset($options['retries']) ? (int) $options['retries'] : 2; + unset($options['delay'], $options['retries']); + + return $this->postWithRetry($options, $delay, $retries); } /** - * {@inheritdoc} + * @param array $options + * @param int $delay + * @param int $retries + * + * @return array + * + * @throws HttpTimeoutException + * @throws PsCheckoutException */ - public function sendRequest(RequestInterface $request) + private function postWithRetry(array $options, $delay = 2, $retries = 2) { - return $this->client->sendRequest($request); + try { + $response = parent::post($options); + + if ($response['httpCode'] === 401 || false !== strpos($response['exceptionMessage'], 'Unauthorized')) { + throw new PsCheckoutException('Unauthorized', PsCheckoutException::PSCHECKOUT_HTTP_UNAUTHORIZED); + } + + if (false !== $response['status']) { + return $response; + } + + if ( + isset($response['exceptionCode']) + && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION + && false !== strpos($response['exceptionMessage'], 'cURL error 28') + ) { + throw new HttpTimeoutException($response['exceptionMessage'], PsCheckoutException::PSL_TIMEOUT); + } elseif ( + isset($response['exceptionCode']) + && $response['exceptionCode'] === PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION + ) { + throw new PsCheckoutException($response['exceptionMessage'], PsCheckoutException::PSCHECKOUT_HTTP_EXCEPTION); + } + + if ( + isset($response['body']['message']) + && ($response['body']['message'] === 'Error: ETIMEDOUT' || $response['body']['message'] === 'Error: ESOCKETTIMEDOUT') + ) { + throw new HttpTimeoutException($response['body']['message'], PsCheckoutException::PSL_TIMEOUT); + } + } catch (HttpTimeoutException $exception) { + if ($this->isRouteRetryable() && $retries > 0) { + sleep($delay); + + return $this->postWithRetry($options, $delay, $retries - 1); + } + + throw $exception; + } + + return $response; + } + + /** + * @return bool + */ + private function isRouteRetryable() + { + switch ($this->getRoute()) { + case '/payments/order/capture': + case '/payments/order/refund': + return false; + } + + return true; } } From 3f09c3690e16c7723130393a3c3e3a51d7c02499 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 6 Mar 2024 15:56:40 +0200 Subject: [PATCH 24/26] Added Draft for CreatePayPalOrderPayloadBuilder --- config/common.yml | 5 +- .../CreatePayPalOrderPayloadBuilder.php | 322 ++++++++++++++++++ ...eatePayPalOrderPayloadBuilderInterface.php | 3 +- src/PayPal/Order/DTO/AddressRequest.php | 36 +- src/PayPal/Order/DTO/Amount.php | 8 +- src/PayPal/Order/DTO/AmountBreakdown.php | 28 +- src/PayPal/Order/DTO/AmountWithBreakdown.php | 4 +- .../Order/DTO/ApplicationContextRequest.php | 4 +- .../Order/DTO/CreatePayPalOrderRequest.php | 42 ++- src/PayPal/Order/DTO/ItemRequest.php | 28 +- src/PayPal/Order/DTO/Name.php | 28 +- src/PayPal/Order/DTO/PayeeRequest.php | 8 +- src/PayPal/Order/DTO/Payer.php | 14 + src/PayPal/Order/DTO/PurchaseUnitRequest.php | 40 ++- src/PayPal/Order/DTO/ShippingRequest.php | 16 +- .../Order/DTO/StoredPaymentSourceRequest.php | 16 +- 16 files changed, 541 insertions(+), 61 deletions(-) create mode 100644 src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php diff --git a/config/common.yml b/config/common.yml index d4ca063cf..8006410af 100644 --- a/config/common.yml +++ b/config/common.yml @@ -589,7 +589,7 @@ services: public: true arguments: - '@?' - - '@?' + - '@PrestaShop\Module\PrestashopCheckout\PayPal\Order\Builder\Payload\CreatePayPalOrderPayloadBuilder' - '@ps_checkout.event.dispatcher' - '@PrestaShop\Module\PrestashopCheckout\Api\Payment\PaymentService' - '@PrestaShop\Module\PrestashopCheckout\Serializer\ObjectSerializer' @@ -789,3 +789,6 @@ services: public: true arguments: - "@ps_checkout.http.client" + + PrestaShop\Module\PrestashopCheckout\PayPal\Order\Builder\Payload\CreatePayPalOrderPayloadBuilder: + class: 'PrestaShop\Module\PrestashopCheckout\PayPal\Order\Builder\Payload\CreatePayPalOrderPayloadBuilder' diff --git a/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php new file mode 100644 index 000000000..7933196be --- /dev/null +++ b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php @@ -0,0 +1,322 @@ + + * @copyright Since 2007 PrestaShop SA and Contributors + * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 + */ + +namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\Builder\Payload; + +use PrestaShop\Module\PrestashopCheckout\Cart\CartInterface; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\CreatePayPalOrderPayloadBuilderInterface; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AddressRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Amount; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AmountBreakdown; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AmountWithBreakdown; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ApplicationContextRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ItemRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Name; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PayeeRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Payer; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PurchaseUnitRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ShippingRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\StoredPaymentSourceRequest; + +class CreatePayPalOrderPayloadBuilder implements CreatePayPalOrderPayloadBuilderInterface +{ + /** @var CreatePayPalOrderRequest */ + private $payload; + /** + * @var array + */ + private $data; + + /** + * {@inheritDoc} + */ + public function build(CartInterface $cart, $fundingSource, $data) + { + $this->data = $data; + $this->buildBaseNode(); + $this->buildPurchaseUnitsNode(); + if (empty($this->data['ps_checkout']['isExpressCheckout']) && empty($this->data['ps_checkout']['isUpdate'])) { + $this->buildPayerNode(); + } + + if (empty($this->data['ps_checkout']['isUpdate'])) { + $this->buildApplicationContextNode(); + } + + return $this->payload; + } + + /** + * Build payload without cart details + */ + public function buildMinimalPayload() + { + $this->buildBaseNode(); + $this->buildPurchaseUnitsNode(); + + if (empty($this->data['ps_checkout']['isExpressCheckout']) && empty($this->data['ps_checkout']['isUpdate'])) { + $this->buildPayerNode(); + } + + if (empty($this->data['ps_checkout']['isUpdate'])) { + $this->buildApplicationContextNode(); + } + } + + /** + * Build the basic payload + */ + public function buildBaseNode() + { + $this->payload = (new CreatePayPalOrderRequest())->setIntent($this->data['ps_checkout']['intent']); +// if (empty($this->data['ps_checkout']['isUpdate']) && !empty($this->data['ps_checkout']['token'])) { +// $node['token'] = $this->data['ps_checkout']['token']; +// } +// +// if (empty($this->data['ps_checkout']['isUpdate'])) { +// $node['roundingConfig'] = $this->data['ps_checkout']['roundType'] . '-' . $this->data['ps_checkout']['roundMode']; +// } + } + + /** + * Build shipping node + */ + public function buildShippingNode(PurchaseUnitRequest $purchaseUnit) + { + $shipping = new ShippingRequest(); + $shipping->setName( + (new Name())->setFullName(trim( + (!empty($this->data['deliveryAddress']['firstname']) ? $this->data['deliveryAddress']['firstname'] : '') + . ' ' + . (!empty($this->data['deliveryAddress']['lastname']) ? $this->data['deliveryAddress']['lastname'] : '') + )) + )->setAddress($this->buildAddress($this->data['deliveryAddress'], $this->data['deliveryAddressCountry'], $this->data['deliveryAddressState'])); + $purchaseUnit->setShipping($shipping); + } + + /** + * Build payer node + */ + public function buildPayerNode() + { + $payer = new Payer(); + $payer->setName( + (new Name()) + ->setGivenName(!empty($this->data['invoiceAddress']['firstname']) ? $this->data['invoiceAddress']['firstname'] : '') + ->setSurname(!empty($this->data['invoiceAddress']['lastname']) ? $this->data['invoiceAddress']['lastname'] : '') + ) + ->setEmailAddress(!empty($this->data['customer']['email']) ? $this->data['customer']['email'] : '') + ->setAddress($this->buildAddress($this->data['invoiceAddress'], $this->data['invoiceAddressCountry'], $this->data['invoiceAddressState'])); + + // Add optional birthdate if provided + if (!empty($this->data['customer']['birthday']) && $this->data['customer']['birthday'] !== '0000-00-00') { + $payer->setBirthDate($this->data['customer']['birthday']); + } + + $this->payload->setPayer($payer); + } + + /** + * @param array $address + * + * @return AddressRequest + */ + private function buildAddress($address, $country, $state) + { + return (new AddressRequest()) + ->setAddressLine1(!empty($address['address1']) ? $address['address1'] : '') + ->setAddressLine2(!empty($address['address2']) ? $address['address2'] : '') + ->setAdminArea1(!empty($state['name']) ? $state['name'] : '') + ->setAdminArea2(!empty($address['city']) ? $address['city'] : '') + ->setCountryCode(!empty($country['iso_code']) ? $country['iso_code'] : '') + ->setPostalCode(!empty($address['postcode']) ? $address['postcode'] : ''); + } + + /** + * Build application context node + * + * NO_SHIPPING: The client can customize his address int the paypal pop-up (used in express checkout mode) + * SET_PROVIDED_ADDRESS: The address is provided by prestashop and the client + * cannot change/edit his address in the paypal pop-up + */ + public function buildApplicationContextNode() + { + $applicationContext = (new ApplicationContextRequest()) + ->setStoredPaymentSource( + (new StoredPaymentSourceRequest()) + ->setPaymentType('ONE_TIME') + ->setPaymentInitiator('MERCHANT') + ); + // DEPRECATED +// $node['application_context'] = [ +// 'brand_name' => $this->data['shop']['name'], +// 'shipping_preference' => empty($this->data['ps_checkout']['isExpressCheckout']) ? 'SET_PROVIDED_ADDRESS' : 'GET_FROM_FILE', +// ]; + $this->payload->setApplicationContext($applicationContext); + } + + public function buildPurchaseUnitsNode() + { + $purchaseUnit = (new PurchaseUnitRequest()) + ->setPayee((new PayeeRequest())->setMerchantId($this->data['ps_checkout']['merchant_id'])) + ->setDescription($this->truncate( + 'Checking out with your cart ' . $this->data['cart']['id'] . ' from ' . $this->data['shop']['name'], + 127 + )) + ->setCustomId((string) $this->data['cart']['id']) + ->setInvoiceId(''); + $this->buildAmountBreakdownNode($purchaseUnit); + + if ($this->payload->getIntent() === 'CAPTURE') { +// $purchaseUnit->setPaymentInstruction(); // TODO: Need to add? + } + + if (empty($this->data['ps_checkout']['isExpressCheckout'])) { + $this->buildShippingNode($purchaseUnit); + } + + $this->payload->setPurchaseUnits([$purchaseUnit]); + } + + /** + * Build the amount breakdown node + */ + public function buildAmountBreakdownNode(PurchaseUnitRequest $purchaseUnit) + { + $items = []; + $amountTotal = $this->data['totalWithTaxes']; + $breakdownItemTotal = 0; + $breakdownTaxTotal = 0; + $breakdownShipping = $this->data['totalShippingWithTaxes']; + $breakdownHandling = 0; + $breakdownDiscount = 0; + $currencyCode = $this->data['currency']['iso_code']; + + foreach ($this->data['products'] as $product) { + $sku = ''; + $totalWithoutTax = $product['total']; + $totalWithTax = $product['total_wt']; + $totalTax = $totalWithTax - $totalWithoutTax; + $quantity = $product['quantity']; + $unitPriceWithoutTax = $this->formatAmount($totalWithoutTax / $quantity); + $unitTax = $this->formatAmount($totalTax / $quantity); + $breakdownItemTotal += $unitPriceWithoutTax * $quantity; + $breakdownTaxTotal += $unitTax * $quantity; + + if (!empty($product['reference'])) { + $sku = $product['reference']; + } + + if (!empty($product['ean13'])) { + $sku = $product['ean13']; + } + + if (!empty($product['isbn'])) { + $sku = $product['isbn']; + } + + if (!empty($product['upc'])) { + $sku = $product['upc']; + } + + $paypalItem = (new ItemRequest()) + ->setName($this->truncate($product['name'], 127)) + ->setDescription(!empty($product['attributes']) ? $this->truncate($product['attributes'], 127) : '') + ->setSku($this->truncate($sku, 127)) + ->setUnitAmount((new Amount())->setValue($unitPriceWithoutTax)->setCurrencyCode($currencyCode)) + ->setTax((new Amount())->setValue($unitTax)->setCurrencyCode($currencyCode)) + ->setQuantity($quantity) + ->setCategory($product['is_virtual'] === '1' ? 'DIGITAL_GOODS' : 'PHYSICAL_GOODS'); + + $items[] = $paypalItem; + } + + $purchaseUnit->setItems($items); + + // set handling cost id needed -> principally used in case of gift_wrapping + if (!empty($this->data['totalGiftWrappingWithTaxes'])) { + $breakdownHandling += $this->data['totalGiftWrappingWithTaxes']; + } + + $remainderValue = $amountTotal - $breakdownItemTotal - $breakdownTaxTotal - $breakdownShipping - $breakdownHandling; + + // In case of rounding issue, if remainder value is negative we use discount value to deduct remainder and if remainder value is positive we use handling value to add remainder + if ($remainderValue < 0) { + $breakdownDiscount += abs($remainderValue); + } else { + $breakdownHandling += $remainderValue; + } + + $amountBreakdown = (new AmountBreakdown()) + ->setItemTotal((new Amount())->setValue($this->formatAmount($breakdownItemTotal))->setCurrencyCode($currencyCode)) + ->setShipping((new Amount())->setValue($this->formatAmount($breakdownShipping))->setCurrencyCode($currencyCode)) + ->setTaxTotal((new Amount())->setValue($this->formatAmount($breakdownTaxTotal))->setCurrencyCode($currencyCode)) + ->setDiscount((new Amount())->setValue($this->formatAmount($breakdownDiscount))->setCurrencyCode($currencyCode)) + ->setHandling((new Amount())->setValue($this->formatAmount($breakdownHandling))->setCurrencyCode($currencyCode)); + + $purchaseUnit->setAmount( + (new AmountWithBreakdown()) + ->setValue($this->formatAmount($this->data['totalWithTaxes'])) + ->setCurrencyCode($currencyCode) + ->setBreakdown($amountBreakdown) + ); + } + + /** + * Get decimal to round correspondent to the payment currency used + * Advise from PayPal: Always round to 2 decimals except for HUF, JPY and TWD + * currencies which require a round with 0 decimal + * + * @return int + */ + private function getNbDecimalToRound() + { + if (in_array($this->data['currency']['iso_code'], ['HUF', 'JPY', 'TWD'], true)) { + return 0; + } + + return 2; + } + + /** + * @param float|int|string $amount + * + * @return string + */ + private function formatAmount($amount) + { + return sprintf("%01.{$this->getNbDecimalToRound()}f", $amount); + } + + /** + * Function that allow to truncate fields to match the + * paypal api requirements + * + * @param string $str + * @param int $limit + * + * @return string + */ + private function truncate($str, $limit) + { + return mb_substr($str, 0, $limit); + } +} diff --git a/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php b/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php index 55be44e6c..9254840d4 100644 --- a/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php +++ b/src/PayPal/Order/CreatePayPalOrderPayloadBuilderInterface.php @@ -28,8 +28,9 @@ interface CreatePayPalOrderPayloadBuilderInterface /** * @param CartInterface $cart * @param string $fundingSource + * @param array $data * * @return CreatePayPalOrderRequest */ - public function build(CartInterface $cart, $fundingSource); + public function build(CartInterface $cart, $fundingSource, $data); } diff --git a/src/PayPal/Order/DTO/AddressRequest.php b/src/PayPal/Order/DTO/AddressRequest.php index 17e1c4f04..63682dc91 100644 --- a/src/PayPal/Order/DTO/AddressRequest.php +++ b/src/PayPal/Order/DTO/AddressRequest.php @@ -78,11 +78,13 @@ public function getAddressLine1() /** * @param string $address_line_1 * - * @return void + * @return self */ public function setAddressLine1($address_line_1) { $this->address_line_1 = $address_line_1; + + return $this; } /** @@ -96,11 +98,13 @@ public function getAddressLine2() /** * @param string $address_line_2 * - * @return void + * @return self */ public function setAddressLine2($address_line_2) { $this->address_line_2 = $address_line_2; + + return $this; } /** @@ -114,11 +118,13 @@ public function getAddressLine3() /** * @param string $address_line_3 * - * @return void + * @return self */ public function setAddressLine3($address_line_3) { $this->address_line_3 = $address_line_3; + + return $this; } /** @@ -132,11 +138,13 @@ public function getAdminArea1() /** * @param string $admin_area_1 * - * @return void + * @return self */ public function setAdminArea1($admin_area_1) { $this->admin_area_1 = $admin_area_1; + + return $this; } /** @@ -150,11 +158,13 @@ public function getAdminArea2() /** * @param string $admin_area_2 * - * @return void + * @return self */ public function setAdminArea2($admin_area_2) { $this->admin_area_2 = $admin_area_2; + + return $this; } /** @@ -168,11 +178,13 @@ public function getAdminArea3() /** * @param string $admin_area_3 * - * @return void + * @return self */ public function setAdminArea3($admin_area_3) { $this->admin_area_3 = $admin_area_3; + + return $this; } /** @@ -186,11 +198,13 @@ public function getAdminArea4() /** * @param string $admin_area_4 * - * @return void + * @return self */ public function setAdminArea4($admin_area_4) { $this->admin_area_4 = $admin_area_4; + + return $this; } /** @@ -204,11 +218,13 @@ public function getPostalCode() /** * @param string $postal_code * - * @return void + * @return self */ public function setPostalCode($postal_code) { $this->postal_code = $postal_code; + + return $this; } /** @@ -222,10 +238,12 @@ public function getCountryCode() /** * @param string $country_code * - * @return void + * @return self */ public function setCountryCode($country_code) { $this->country_code = $country_code; + + return $this; } } diff --git a/src/PayPal/Order/DTO/Amount.php b/src/PayPal/Order/DTO/Amount.php index 12d0cd1c0..aa6ba0ee2 100644 --- a/src/PayPal/Order/DTO/Amount.php +++ b/src/PayPal/Order/DTO/Amount.php @@ -43,11 +43,13 @@ public function getCurrencyCode() /** * @param string $currency_code * - * @return void + * @return self */ public function setCurrencyCode($currency_code) { $this->currency_code = $currency_code; + + return $this; } /** @@ -61,10 +63,12 @@ public function getValue() /** * @param string $value * - * @return void + * @return self */ public function setValue($value) { $this->value = $value; + + return $this; } } diff --git a/src/PayPal/Order/DTO/AmountBreakdown.php b/src/PayPal/Order/DTO/AmountBreakdown.php index 0d556843a..a7bf538d7 100644 --- a/src/PayPal/Order/DTO/AmountBreakdown.php +++ b/src/PayPal/Order/DTO/AmountBreakdown.php @@ -62,11 +62,13 @@ public function getItemTotal() /** * @param Amount $item_total * - * @return void + * @return self */ public function setItemTotal(Amount $item_total) { $this->item_total = $item_total; + + return $this; } /** @@ -80,11 +82,13 @@ public function getShipping() /** * @param Amount $shipping * - * @return void + * @return self */ public function setShipping(Amount $shipping) { $this->shipping = $shipping; + + return $this; } /** @@ -98,11 +102,13 @@ public function getHandling() /** * @param Amount $handling * - * @return void + * @return self */ public function setHandling(Amount $handling) { $this->handling = $handling; + + return $this; } /** @@ -116,11 +122,13 @@ public function getTaxTotal() /** * @param Amount $tax_total * - * @return void + * @return self */ public function setTaxTotal(Amount $tax_total) { $this->tax_total = $tax_total; + + return $this; } /** @@ -134,11 +142,13 @@ public function getInsurance() /** * @param Amount $insurance * - * @return void + * @return self */ public function setInsurance(Amount $insurance) { $this->insurance = $insurance; + + return $this; } /** @@ -152,11 +162,13 @@ public function getShippingDiscount() /** * @param Amount $shipping_discount * - * @return void + * @return self */ public function setShippingDiscount(Amount $shipping_discount) { $this->shipping_discount = $shipping_discount; + + return $this; } /** @@ -170,10 +182,12 @@ public function getDiscount() /** * @param Amount $discount * - * @return void + * @return self */ public function setDiscount(Amount $discount) { $this->discount = $discount; + + return $this; } } diff --git a/src/PayPal/Order/DTO/AmountWithBreakdown.php b/src/PayPal/Order/DTO/AmountWithBreakdown.php index 039fcc1e4..35395cbe1 100644 --- a/src/PayPal/Order/DTO/AmountWithBreakdown.php +++ b/src/PayPal/Order/DTO/AmountWithBreakdown.php @@ -38,10 +38,12 @@ public function getBreakdown() /** * @param AmountBreakdown $breakdown * - * @return void + * @return self */ public function setBreakdown(AmountBreakdown $breakdown) { $this->breakdown = $breakdown; + + return $this; } } diff --git a/src/PayPal/Order/DTO/ApplicationContextRequest.php b/src/PayPal/Order/DTO/ApplicationContextRequest.php index 47b152ba9..31f586d0b 100644 --- a/src/PayPal/Order/DTO/ApplicationContextRequest.php +++ b/src/PayPal/Order/DTO/ApplicationContextRequest.php @@ -38,10 +38,12 @@ public function getStoredPaymentSource() /** * @param StoredPaymentSourceRequest $stored_payment_source * - * @return void + * @return self */ public function setStoredPaymentSource(StoredPaymentSourceRequest $stored_payment_source) { $this->stored_payment_source = $stored_payment_source; + + return $this; } } diff --git a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php index 2c2fe973a..a69d66501 100644 --- a/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php +++ b/src/PayPal/Order/DTO/CreatePayPalOrderRequest.php @@ -28,6 +28,10 @@ class CreatePayPalOrderRequest implements CreatePayPalOrderRequestInterface * @var string */ private $intent; + /** + * @var Payer + */ + private $payer; /** * @var PurchaseUnitRequest[] */ @@ -56,11 +60,13 @@ public function getIntent() /** * @param string $intent * - * @return void + * @return self */ public function setIntent($intent) { $this->intent = $intent; + + return $this; } /** @@ -74,11 +80,13 @@ public function getPurchaseUnits() /** * @param PurchaseUnitRequest[] $purchase_units * - * @return void + * @return self */ public function setPurchaseUnits(array $purchase_units) { $this->purchase_units = $purchase_units; + + return $this; } /** @@ -92,11 +100,13 @@ public function getPaymentSource() /** * @param PaymentSourceRequest $payment_source * - * @return void + * @return self */ public function setPaymentSource(PaymentSourceRequest $payment_source) { $this->payment_source = $payment_source; + + return $this; } /** @@ -110,11 +120,13 @@ public function getApplicationContext() /** * @param ApplicationContextRequest $application_context * - * @return void + * @return self */ public function setApplicationContext(ApplicationContextRequest $application_context) { $this->application_context = $application_context; + + return $this; } /** @@ -128,10 +140,30 @@ public function getProcessingInstruction() /** * @param string $processing_instruction * - * @return void + * @return self */ public function setProcessingInstruction($processing_instruction) { $this->processing_instruction = $processing_instruction; + + return $this; + } + + /** + * @return Payer + */ + public function getPayer() + { + return $this->payer; + } + + /** + * @param Payer $payer + */ + public function setPayer($payer) + { + $this->payer = $payer; + + return $this; } } diff --git a/src/PayPal/Order/DTO/ItemRequest.php b/src/PayPal/Order/DTO/ItemRequest.php index fe50e7ded..51d5319fd 100644 --- a/src/PayPal/Order/DTO/ItemRequest.php +++ b/src/PayPal/Order/DTO/ItemRequest.php @@ -62,11 +62,13 @@ public function getName() /** * @param string $name * - * @return void + * @return self */ public function setName($name) { $this->name = $name; + + return $this; } /** @@ -80,11 +82,13 @@ public function getUnitAmount() /** * @param Amount $unit_amount * - * @return void + * @return self */ public function setUnitAmount(Amount $unit_amount) { $this->unit_amount = $unit_amount; + + return $this; } /** @@ -98,11 +102,13 @@ public function getTax() /** * @param Amount $tax * - * @return void + * @return self */ public function setTax(Amount $tax) { $this->tax = $tax; + + return $this; } /** @@ -116,11 +122,13 @@ public function getQuantity() /** * @param string $quantity * - * @return void + * @return self */ public function setQuantity($quantity) { $this->quantity = $quantity; + + return $this; } /** @@ -134,11 +142,13 @@ public function getDescription() /** * @param string $description * - * @return void + * @return self */ public function setDescription($description) { $this->description = $description; + + return $this; } /** @@ -152,11 +162,13 @@ public function getSku() /** * @param string $sku * - * @return void + * @return self */ public function setSku($sku) { $this->sku = $sku; + + return $this; } /** @@ -170,10 +182,12 @@ public function getCategory() /** * @param string $category * - * @return void + * @return self */ public function setCategory($category) { $this->category = $category; + + return $this; } } diff --git a/src/PayPal/Order/DTO/Name.php b/src/PayPal/Order/DTO/Name.php index 2ef3b62c7..d672e61a5 100644 --- a/src/PayPal/Order/DTO/Name.php +++ b/src/PayPal/Order/DTO/Name.php @@ -62,11 +62,13 @@ public function getPrefix() /** * @param string $prefix * - * @return void + * @return self */ public function setPrefix($prefix) { $this->prefix = $prefix; + + return $this; } /** @@ -80,11 +82,13 @@ public function getGivenName() /** * @param string $given_name * - * @return void + * @return self */ public function setGivenName($given_name) { $this->given_name = $given_name; + + return $this; } /** @@ -98,11 +102,13 @@ public function getSurname() /** * @param string $surname * - * @return void + * @return self */ public function setSurname($surname) { $this->surname = $surname; + + return $this; } /** @@ -116,11 +122,13 @@ public function getMiddleName() /** * @param string $middle_name * - * @return void + * @return self */ public function setMiddleName($middle_name) { $this->middle_name = $middle_name; + + return $this; } /** @@ -134,11 +142,13 @@ public function getSuffix() /** * @param string $suffix * - * @return void + * @return self */ public function setSuffix($suffix) { $this->suffix = $suffix; + + return $this; } /** @@ -152,11 +162,13 @@ public function getAlternateFullName() /** * @param string $alternate_full_name * - * @return void + * @return self */ public function setAlternateFullName($alternate_full_name) { $this->alternate_full_name = $alternate_full_name; + + return $this; } /** @@ -170,10 +182,12 @@ public function getFullName() /** * @param string $full_name * - * @return void + * @return self */ public function setFullName($full_name) { $this->full_name = $full_name; + + return $this; } } diff --git a/src/PayPal/Order/DTO/PayeeRequest.php b/src/PayPal/Order/DTO/PayeeRequest.php index b854f98aa..6177ecd39 100644 --- a/src/PayPal/Order/DTO/PayeeRequest.php +++ b/src/PayPal/Order/DTO/PayeeRequest.php @@ -42,11 +42,13 @@ public function getEmailAddress() /** * @param string $email_address * - * @return void + * @return self */ public function setEmailAddress($email_address) { $this->email_address = $email_address; + + return $this; } /** @@ -60,10 +62,12 @@ public function getMerchantId() /** * @param string $merchant_id * - * @return void + * @return self */ public function setMerchantId($merchant_id) { $this->merchant_id = $merchant_id; + + return $this; } } diff --git a/src/PayPal/Order/DTO/Payer.php b/src/PayPal/Order/DTO/Payer.php index 9702a12b7..115a4dcb7 100644 --- a/src/PayPal/Order/DTO/Payer.php +++ b/src/PayPal/Order/DTO/Payer.php @@ -65,6 +65,8 @@ public function getEmailAddress() public function setEmailAddress($email_address) { $this->email_address = $email_address; + + return $this; } /** @@ -81,6 +83,8 @@ public function getPayerId() public function setPayerId($payer_id) { $this->payer_id = $payer_id; + + return $this; } /** @@ -97,6 +101,8 @@ public function getName() public function setName($name) { $this->name = $name; + + return $this; } /** @@ -113,6 +119,8 @@ public function getPhone() public function setPhone($phone) { $this->phone = $phone; + + return $this; } /** @@ -129,6 +137,8 @@ public function getBirthDate() public function setBirthDate($birth_date) { $this->birth_date = $birth_date; + + return $this; } /** @@ -145,6 +155,8 @@ public function getTaxInfo() public function setTaxInfo($tax_info) { $this->tax_info = $tax_info; + + return $this; } /** @@ -161,5 +173,7 @@ public function getAddress() public function setAddress($address) { $this->address = $address; + + return $this; } } diff --git a/src/PayPal/Order/DTO/PurchaseUnitRequest.php b/src/PayPal/Order/DTO/PurchaseUnitRequest.php index e8ce815a9..0e54177fc 100644 --- a/src/PayPal/Order/DTO/PurchaseUnitRequest.php +++ b/src/PayPal/Order/DTO/PurchaseUnitRequest.php @@ -74,11 +74,13 @@ public function getReferenceId() /** * @param string $reference_id * - * @return void + * @return self */ public function setReferenceId($reference_id) { $this->reference_id = $reference_id; + + return $this; } /** @@ -92,11 +94,13 @@ public function getAmount() /** * @param AmountWithBreakdown $amount * - * @return void + * @return self */ public function setAmount(AmountWithBreakdown $amount) { $this->amount = $amount; + + return $this; } /** @@ -110,11 +114,13 @@ public function getPayee() /** * @param PayeeRequest $payee * - * @return void + * @return self */ public function setPayee(PayeeRequest $payee) { $this->payee = $payee; + + return $this; } /** @@ -128,11 +134,13 @@ public function getDescription() /** * @param string $description * - * @return void + * @return self */ public function setDescription($description) { $this->description = $description; + + return $this; } /** @@ -146,11 +154,13 @@ public function getCustomId() /** * @param string $custom_id * - * @return void + * @return self */ public function setCustomId($custom_id) { $this->custom_id = $custom_id; + + return $this; } /** @@ -164,11 +174,13 @@ public function getInvoiceId() /** * @param string $invoice_id * - * @return void + * @return self */ public function setInvoiceId($invoice_id) { $this->invoice_id = $invoice_id; + + return $this; } /** @@ -182,11 +194,13 @@ public function getSoftDescriptor() /** * @param string $soft_descriptor * - * @return void + * @return self */ public function setSoftDescriptor($soft_descriptor) { $this->soft_descriptor = $soft_descriptor; + + return $this; } /** @@ -200,11 +214,13 @@ public function getItems() /** * @param ItemRequest[] $items * - * @return void + * @return self */ public function setItems(array $items) { $this->items = $items; + + return $this; } /** @@ -218,11 +234,13 @@ public function getShipping() /** * @param ShippingRequest $shipping * - * @return void + * @return self */ public function setShipping(ShippingRequest $shipping) { $this->shipping = $shipping; + + return $this; } /** @@ -236,10 +254,12 @@ public function getSupplementaryData() /** * @param SupplementaryDataRequest $supplementary_data * - * @return void + * @return self */ public function setSupplementaryData(SupplementaryDataRequest $supplementary_data) { $this->supplementary_data = $supplementary_data; + + return $this; } } diff --git a/src/PayPal/Order/DTO/ShippingRequest.php b/src/PayPal/Order/DTO/ShippingRequest.php index 92061c8e5..96e40d3ec 100644 --- a/src/PayPal/Order/DTO/ShippingRequest.php +++ b/src/PayPal/Order/DTO/ShippingRequest.php @@ -50,11 +50,13 @@ public function getName() /** * @param Name $name * - * @return void + * @return self */ public function setName(Name $name) { $this->name = $name; + + return $this; } /** @@ -68,11 +70,13 @@ public function getType() /** * @param string $type * - * @return void + * @return self */ public function setType($type) { $this->type = $type; + + return $this; } /** @@ -86,11 +90,13 @@ public function getOptions() /** * @param ShippingOptionRequest[] $options * - * @return void + * @return self */ public function setOptions(array $options) { $this->options = $options; + + return $this; } /** @@ -104,10 +110,12 @@ public function getAddress() /** * @param AddressRequest $address * - * @return void + * @return self */ public function setAddress(AddressRequest $address) { $this->address = $address; + + return $this; } } diff --git a/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php b/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php index c194d77eb..d737ae533 100644 --- a/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php +++ b/src/PayPal/Order/DTO/StoredPaymentSourceRequest.php @@ -50,11 +50,13 @@ public function getPaymentInitiator() /** * @param string $payment_initiator * - * @return void + * @return self */ public function setPaymentInitiator($payment_initiator) { $this->payment_initiator = $payment_initiator; + + return $this; } /** @@ -68,11 +70,13 @@ public function getPaymentType() /** * @param string $payment_type * - * @return void + * @return self */ public function setPaymentType($payment_type) { $this->payment_type = $payment_type; + + return $this; } /** @@ -86,11 +90,13 @@ public function getUsage() /** * @param string $usage * - * @return void + * @return self */ public function setUsage($usage) { $this->usage = $usage; + + return $this; } /** @@ -104,10 +110,12 @@ public function getPreviousNetworkTransactionReference() /** * @param PreviousNetworkTransactionReferenceRequest $previous_network_transaction_reference * - * @return void + * @return self */ public function setPreviousNetworkTransactionReference(PreviousNetworkTransactionReferenceRequest $previous_network_transaction_reference) { $this->previous_network_transaction_reference = $previous_network_transaction_reference; + + return $this; } } From 64404f75f6139c7e907cfe3f4134c6cc3bb98148 Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 6 Mar 2024 16:10:22 +0200 Subject: [PATCH 25/26] Added temporary data attribute to builder --- .../Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php | 2 +- .../Order/CommandHandler/CreatePayPalOrderCommandHandler.php | 2 +- src/PayPal/Order/DTO/Amount.php | 4 ++-- src/PayPal/Order/DTO/AmountWithBreakdown.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php index 7933196be..b1b1d52f1 100644 --- a/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php +++ b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php @@ -274,9 +274,9 @@ public function buildAmountBreakdownNode(PurchaseUnitRequest $purchaseUnit) $purchaseUnit->setAmount( (new AmountWithBreakdown()) + ->setBreakdown($amountBreakdown) ->setValue($this->formatAmount($this->data['totalWithTaxes'])) ->setCurrencyCode($currencyCode) - ->setBreakdown($amountBreakdown) ); } diff --git a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php index 0faf45ca1..15934dd19 100644 --- a/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php +++ b/src/PayPal/Order/CommandHandler/CreatePayPalOrderCommandHandler.php @@ -88,7 +88,7 @@ public function __construct( public function handle(CreatePayPalOrderCommand $command) { $cart = $this->cartRepository->getCartById($command->getCartId()); - $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource()); + $payload = $this->createPayPalOrderPayloadBuilder->build($cart, $command->getFundingSource(), []); $order = $this->paymentService->createOrder($payload); $this->eventDispatcher->dispatch(new PayPalOrderCreatedEvent( $order->getId(), diff --git a/src/PayPal/Order/DTO/Amount.php b/src/PayPal/Order/DTO/Amount.php index aa6ba0ee2..7a759e200 100644 --- a/src/PayPal/Order/DTO/Amount.php +++ b/src/PayPal/Order/DTO/Amount.php @@ -43,7 +43,7 @@ public function getCurrencyCode() /** * @param string $currency_code * - * @return self + * @return $this */ public function setCurrencyCode($currency_code) { @@ -63,7 +63,7 @@ public function getValue() /** * @param string $value * - * @return self + * @return $this */ public function setValue($value) { diff --git a/src/PayPal/Order/DTO/AmountWithBreakdown.php b/src/PayPal/Order/DTO/AmountWithBreakdown.php index 35395cbe1..f375a9adf 100644 --- a/src/PayPal/Order/DTO/AmountWithBreakdown.php +++ b/src/PayPal/Order/DTO/AmountWithBreakdown.php @@ -38,7 +38,7 @@ public function getBreakdown() /** * @param AmountBreakdown $breakdown * - * @return self + * @return $this */ public function setBreakdown(AmountBreakdown $breakdown) { From 92751f6d5fe50bf10db007e38f12834920cf094b Mon Sep 17 00:00:00 2001 From: Laurynas Date: Wed, 6 Mar 2024 17:52:36 +0200 Subject: [PATCH 26/26] Added payment source and supplementary data --- .../CreatePayPalOrderPayloadBuilder.php | 106 +++++++++-- .../Order/DTO/CardAttributesRequest.php | 12 +- src/PayPal/Order/DTO/CardRequest.php | 24 ++- .../DTO/CardSupplementaryDataRequest.php | 8 +- src/PayPal/Order/DTO/CardVerification.php | 4 +- src/PayPal/Order/DTO/ItemRequest.php | 14 +- .../DTO/Level2CardProcessingDataRequest.php | 8 +- .../DTO/Level3CardProcessingDataRequest.php | 24 ++- src/PayPal/Order/DTO/LineItemRequest.php | 172 ++---------------- src/PayPal/Order/DTO/PaymentSourceRequest.php | 4 +- .../Order/DTO/SupplementaryDataRequest.php | 4 +- 11 files changed, 176 insertions(+), 204 deletions(-) diff --git a/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php index b1b1d52f1..bfe7977df 100644 --- a/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php +++ b/src/PayPal/Order/Builder/Payload/CreatePayPalOrderPayloadBuilder.php @@ -27,14 +27,23 @@ use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AmountBreakdown; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\AmountWithBreakdown; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ApplicationContextRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CardAttributesRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CardRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CardSupplementaryDataRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CardVerification; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\CreatePayPalOrderRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ItemRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Level2CardProcessingDataRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Level3CardProcessingDataRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\LineItemRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Name; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PayeeRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\Payer; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PaymentSourceRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\PurchaseUnitRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\ShippingRequest; use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\StoredPaymentSourceRequest; +use PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO\SupplementaryDataRequest; class CreatePayPalOrderPayloadBuilder implements CreatePayPalOrderPayloadBuilderInterface { @@ -52,7 +61,12 @@ public function build(CartInterface $cart, $fundingSource, $data) { $this->data = $data; $this->buildBaseNode(); - $this->buildPurchaseUnitsNode(); + $this->buildPurchaseUnitsNode($fundingSource); + + if ($fundingSource === 'card') { + $this->buildCardPaymentSourceNode(); + } + if (empty($this->data['ps_checkout']['isExpressCheckout']) && empty($this->data['ps_checkout']['isUpdate'])) { $this->buildPayerNode(); } @@ -67,19 +81,19 @@ public function build(CartInterface $cart, $fundingSource, $data) /** * Build payload without cart details */ - public function buildMinimalPayload() - { - $this->buildBaseNode(); - $this->buildPurchaseUnitsNode(); - - if (empty($this->data['ps_checkout']['isExpressCheckout']) && empty($this->data['ps_checkout']['isUpdate'])) { - $this->buildPayerNode(); - } - - if (empty($this->data['ps_checkout']['isUpdate'])) { - $this->buildApplicationContextNode(); - } - } +// public function buildMinimalPayload() +// { +// $this->buildBaseNode(); +// $this->buildPurchaseUnitsNode(); +// +// if (empty($this->data['ps_checkout']['isExpressCheckout']) && empty($this->data['ps_checkout']['isUpdate'])) { +// $this->buildPayerNode(); +// } +// +// if (empty($this->data['ps_checkout']['isUpdate'])) { +// $this->buildApplicationContextNode(); +// } +// } /** * Build the basic payload @@ -122,7 +136,7 @@ public function buildPayerNode() (new Name()) ->setGivenName(!empty($this->data['invoiceAddress']['firstname']) ? $this->data['invoiceAddress']['firstname'] : '') ->setSurname(!empty($this->data['invoiceAddress']['lastname']) ? $this->data['invoiceAddress']['lastname'] : '') - ) + ) ->setEmailAddress(!empty($this->data['customer']['email']) ? $this->data['customer']['email'] : '') ->setAddress($this->buildAddress($this->data['invoiceAddress'], $this->data['invoiceAddressCountry'], $this->data['invoiceAddressState'])); @@ -173,7 +187,12 @@ public function buildApplicationContextNode() $this->payload->setApplicationContext($applicationContext); } - public function buildPurchaseUnitsNode() + /** + * @param string $fundingSource + * + * @return void + */ + public function buildPurchaseUnitsNode($fundingSource) { $purchaseUnit = (new PurchaseUnitRequest()) ->setPayee((new PayeeRequest())->setMerchantId($this->data['ps_checkout']['merchant_id'])) @@ -193,6 +212,10 @@ public function buildPurchaseUnitsNode() $this->buildShippingNode($purchaseUnit); } + if ($fundingSource === 'card') { + $this->buildSupplementaryDataNode($purchaseUnit); + } + $this->payload->setPurchaseUnits([$purchaseUnit]); } @@ -280,6 +303,57 @@ public function buildAmountBreakdownNode(PurchaseUnitRequest $purchaseUnit) ); } + private function buildCardPaymentSourceNode() + { + $paymentSource = (new PaymentSourceRequest()) + ->setCard( + (new CardRequest()) + ->setName($this->data['invoiceAddress']['firstname'] . ' ' . $this->data['invoiceAddress']['lastname']) + ->setBillingAddress($this->buildAddress($this->data['invoiceAddress'], $this->data['invoiceAddressCountry'], $this->data['invoiceAddressState'])) + ->setAttributes( + (new CardAttributesRequest()) + ->setVerification((new CardVerification())->setMethod($this->data['ps_checkout']['3DS'])) + ) + ); + + $this->payload->setPaymentSource($paymentSource); + } + + private function buildSupplementaryDataNode(PurchaseUnitRequest $purchaseUnit) + { + $level3CardLineItems = array_map(function (ItemRequest $item) { + return (new LineItemRequest()) + ->setName($item->getName()) + ->setUnitAmount($item->getUnitAmount()) + ->setTax($item->getTax()) + ->setQuantity($item->getQuantity()) + ->setDescription($item->getDescription()) + ->setSku($item->getSku()) + ->setCategory($item->getCategory()); + }, $purchaseUnit->getItems()); + + $supplementaryData = (new SupplementaryDataRequest())->setCard( + (new CardSupplementaryDataRequest()) + ->setLevel2( + (new Level2CardProcessingDataRequest())->setTaxTotal($purchaseUnit->getAmount()->getBreakdown()->getTaxTotal()) + ) + ->setLevel3( + (new Level3CardProcessingDataRequest()) + ->setShippingAmount($purchaseUnit->getAmount()->getBreakdown()->getShipping()) + ->setDutyAmount( + (new Amount()) + ->setValue($purchaseUnit->getAmount()->getValue()) + ->setCurrencyCode($purchaseUnit->getAmount()->getCurrencyCode()) + ) + ->setDiscountAmount($purchaseUnit->getAmount()->getBreakdown()->getDiscount()) + ->setShippingAddress($purchaseUnit->getShipping()->getAddress()) + ->setLineItems($level3CardLineItems) + ) + ); + + $purchaseUnit->setSupplementaryData($supplementaryData); + } + /** * Get decimal to round correspondent to the payment currency used * Advise from PayPal: Always round to 2 decimals except for HUF, JPY and TWD diff --git a/src/PayPal/Order/DTO/CardAttributesRequest.php b/src/PayPal/Order/DTO/CardAttributesRequest.php index bb941cf6d..4a9cc07ba 100644 --- a/src/PayPal/Order/DTO/CardAttributesRequest.php +++ b/src/PayPal/Order/DTO/CardAttributesRequest.php @@ -46,11 +46,13 @@ public function getCustomer() /** * @param CustomerRequest $customer * - * @return void + * @return $this */ public function setCustomer(CustomerRequest $customer) { $this->customer = $customer; + + return $this; } /** @@ -64,11 +66,13 @@ public function getVault() /** * @param VaultAttributesRequest $vault * - * @return void + * @return $this */ public function setVault(VaultAttributesRequest $vault) { $this->vault = $vault; + + return $this; } /** @@ -82,10 +86,12 @@ public function getVerification() /** * @param CardVerification $verification * - * @return void + * @return $this */ public function setVerification(CardVerification $verification) { $this->verification = $verification; + + return $this; } } diff --git a/src/PayPal/Order/DTO/CardRequest.php b/src/PayPal/Order/DTO/CardRequest.php index be0a2d6bd..19c4c0725 100644 --- a/src/PayPal/Order/DTO/CardRequest.php +++ b/src/PayPal/Order/DTO/CardRequest.php @@ -58,11 +58,13 @@ public function getName() /** * @param string $name * - * @return void + * @return $this */ public function setName($name) { $this->name = $name; + + return $this; } /** @@ -76,11 +78,13 @@ public function getBillingAddress() /** * @param AddressRequest $billing_address * - * @return void + * @return $this */ public function setBillingAddress(AddressRequest $billing_address) { $this->billing_address = $billing_address; + + return $this; } /** @@ -94,11 +98,13 @@ public function getAttributes() /** * @param CardAttributesRequest $attributes * - * @return void + * @return $this */ public function setAttributes(CardAttributesRequest $attributes) { $this->attributes = $attributes; + + return $this; } /** @@ -112,11 +118,13 @@ public function getVaultId() /** * @param string $vault_id * - * @return void + * @return $this */ public function setVaultId($vault_id) { $this->vault_id = $vault_id; + + return $this; } /** @@ -130,11 +138,13 @@ public function getStoredCredentials() /** * @param CardStoredCredentialsRequest $stored_credentials * - * @return void + * @return $this */ public function setStoredCredentials(CardStoredCredentialsRequest $stored_credentials) { $this->stored_credentials = $stored_credentials; + + return $this; } /** @@ -148,10 +158,12 @@ public function getExperienceContext() /** * @param CardExperienceContextRequest $experience_context * - * @return void + * @return $this */ public function setExperienceContext(CardExperienceContextRequest $experience_context) { $this->experience_context = $experience_context; + + return $this; } } diff --git a/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php b/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php index 04b76b9a5..622db1e5d 100644 --- a/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php +++ b/src/PayPal/Order/DTO/CardSupplementaryDataRequest.php @@ -42,11 +42,13 @@ public function getLevel2() /** * @param Level2CardProcessingDataRequest $level_2 * - * @return void + * @return $this */ public function setLevel2(Level2CardProcessingDataRequest $level_2) { $this->level_2 = $level_2; + + return $this; } /** @@ -60,10 +62,12 @@ public function getLevel3() /** * @param Level3CardProcessingDataRequest $level_3 * - * @return void + * @return $this */ public function setLevel3(Level3CardProcessingDataRequest $level_3) { $this->level_3 = $level_3; + + return $this; } } diff --git a/src/PayPal/Order/DTO/CardVerification.php b/src/PayPal/Order/DTO/CardVerification.php index 8891eddac..6ebd90009 100644 --- a/src/PayPal/Order/DTO/CardVerification.php +++ b/src/PayPal/Order/DTO/CardVerification.php @@ -38,10 +38,12 @@ public function getMethod() /** * @param string $method * - * @return void + * @return $this */ public function setMethod($method) { $this->method = $method; + + return $this; } } diff --git a/src/PayPal/Order/DTO/ItemRequest.php b/src/PayPal/Order/DTO/ItemRequest.php index 51d5319fd..cc656e84f 100644 --- a/src/PayPal/Order/DTO/ItemRequest.php +++ b/src/PayPal/Order/DTO/ItemRequest.php @@ -62,7 +62,7 @@ public function getName() /** * @param string $name * - * @return self + * @return $this */ public function setName($name) { @@ -82,7 +82,7 @@ public function getUnitAmount() /** * @param Amount $unit_amount * - * @return self + * @return $this */ public function setUnitAmount(Amount $unit_amount) { @@ -102,7 +102,7 @@ public function getTax() /** * @param Amount $tax * - * @return self + * @return $this */ public function setTax(Amount $tax) { @@ -122,7 +122,7 @@ public function getQuantity() /** * @param string $quantity * - * @return self + * @return $this */ public function setQuantity($quantity) { @@ -142,7 +142,7 @@ public function getDescription() /** * @param string $description * - * @return self + * @return $this */ public function setDescription($description) { @@ -162,7 +162,7 @@ public function getSku() /** * @param string $sku * - * @return self + * @return $this */ public function setSku($sku) { @@ -182,7 +182,7 @@ public function getCategory() /** * @param string $category * - * @return self + * @return $this */ public function setCategory($category) { diff --git a/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php b/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php index 755d53217..b639799e7 100644 --- a/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php +++ b/src/PayPal/Order/DTO/Level2CardProcessingDataRequest.php @@ -42,11 +42,13 @@ public function getInvoiceId() /** * @param string $invoice_id * - * @return void + * @return $this */ public function setInvoiceId($invoice_id) { $this->invoice_id = $invoice_id; + + return $this; } /** @@ -60,10 +62,12 @@ public function getTaxTotal() /** * @param Amount $tax_total * - * @return void + * @return $this */ public function setTaxTotal(Amount $tax_total) { $this->tax_total = $tax_total; + + return $this; } } diff --git a/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php b/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php index 606cfe58d..8540fc561 100644 --- a/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php +++ b/src/PayPal/Order/DTO/Level3CardProcessingDataRequest.php @@ -58,11 +58,13 @@ public function getShippingAmount() /** * @param Amount $shipping_amount * - * @return void + * @return $this */ public function setShippingAmount(Amount $shipping_amount) { $this->shipping_amount = $shipping_amount; + + return $this; } /** @@ -76,11 +78,13 @@ public function getDutyAmount() /** * @param Amount $duty_amount * - * @return void + * @return $this */ public function setDutyAmount(Amount $duty_amount) { $this->duty_amount = $duty_amount; + + return $this; } /** @@ -94,11 +98,13 @@ public function getDiscountAmount() /** * @param Amount $discount_amount * - * @return void + * @return $this */ public function setDiscountAmount(Amount $discount_amount) { $this->discount_amount = $discount_amount; + + return $this; } /** @@ -112,11 +118,13 @@ public function getShippingAddress() /** * @param AddressRequest $shipping_address * - * @return void + * @return $this */ public function setShippingAddress(AddressRequest $shipping_address) { $this->shipping_address = $shipping_address; + + return $this; } /** @@ -130,11 +138,13 @@ public function getShipsFromPostalCode() /** * @param string $ships_from_postal_code * - * @return void + * @return $this */ public function setShipsFromPostalCode($ships_from_postal_code) { $this->ships_from_postal_code = $ships_from_postal_code; + + return $this; } /** @@ -148,10 +158,12 @@ public function getLineItems() /** * @param LineItemRequest[] $line_items * - * @return void + * @return $this */ public function setLineItems(array $line_items) { $this->line_items = $line_items; + + return $this; } } diff --git a/src/PayPal/Order/DTO/LineItemRequest.php b/src/PayPal/Order/DTO/LineItemRequest.php index dec30d352..b999dd285 100644 --- a/src/PayPal/Order/DTO/LineItemRequest.php +++ b/src/PayPal/Order/DTO/LineItemRequest.php @@ -20,36 +20,8 @@ namespace PrestaShop\Module\PrestashopCheckout\PayPal\Order\DTO; -class LineItemRequest +class LineItemRequest extends ItemRequest { - /** - * @var string - */ - private $name; - /** - * @var Amount - */ - private $unit_amount; - /** - * @var Amount - */ - private $tax; - /** - * @var string - */ - private $quantity; - /** - * @var string - */ - private $description; - /** - * @var string - */ - private $sku; - /** - * @var string - */ - private $category; /** * @var string */ @@ -67,132 +39,6 @@ class LineItemRequest */ private $unit_of_measure; - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - * - * @return void - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return Amount - */ - public function getUnitAmount() - { - return $this->unit_amount; - } - - /** - * @param Amount $unit_amount - * - * @return void - */ - public function setUnitAmount(Amount $unit_amount) - { - $this->unit_amount = $unit_amount; - } - - /** - * @return Amount - */ - public function getTax() - { - return $this->tax; - } - - /** - * @param Amount $tax - * - * @return void - */ - public function setTax(Amount $tax) - { - $this->tax = $tax; - } - - /** - * @return string - */ - public function getQuantity() - { - return $this->quantity; - } - - /** - * @param string $quantity - * - * @return void - */ - public function setQuantity($quantity) - { - $this->quantity = $quantity; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } - - /** - * @param string $description - * - * @return void - */ - public function setDescription($description) - { - $this->description = $description; - } - - /** - * @return string - */ - public function getSku() - { - return $this->sku; - } - - /** - * @param string $sku - * - * @return void - */ - public function setSku($sku) - { - $this->sku = $sku; - } - - /** - * @return string - */ - public function getCategory() - { - return $this->category; - } - - /** - * @param string $category - * - * @return void - */ - public function setCategory($category) - { - $this->category = $category; - } - /** * @return string */ @@ -204,11 +50,13 @@ public function getCommodityCode() /** * @param string $commodity_code * - * @return void + * @return $this */ public function setCommodityCode($commodity_code) { $this->commodity_code = $commodity_code; + + return $this; } /** @@ -222,11 +70,13 @@ public function getDiscountAmount() /** * @param Amount $discount_amount * - * @return void + * @return $this */ public function setDiscountAmount(Amount $discount_amount) { $this->discount_amount = $discount_amount; + + return $this; } /** @@ -240,11 +90,13 @@ public function getTotalAmount() /** * @param Amount $total_amount * - * @return void + * @return $this */ public function setTotalAmount(Amount $total_amount) { $this->total_amount = $total_amount; + + return $this; } /** @@ -258,10 +110,12 @@ public function getUnitOfMeasure() /** * @param string $unit_of_measure * - * @return void + * @return $this */ public function setUnitOfMeasure($unit_of_measure) { $this->unit_of_measure = $unit_of_measure; + + return $this; } } diff --git a/src/PayPal/Order/DTO/PaymentSourceRequest.php b/src/PayPal/Order/DTO/PaymentSourceRequest.php index 691a6f444..8ce0a880f 100644 --- a/src/PayPal/Order/DTO/PaymentSourceRequest.php +++ b/src/PayPal/Order/DTO/PaymentSourceRequest.php @@ -90,11 +90,13 @@ public function getCard() /** * @param CardRequest $card * - * @return void + * @return $this */ public function setCard(CardRequest $card) { $this->card = $card; + + return $this; } /** diff --git a/src/PayPal/Order/DTO/SupplementaryDataRequest.php b/src/PayPal/Order/DTO/SupplementaryDataRequest.php index 5e848be5a..0e404faba 100644 --- a/src/PayPal/Order/DTO/SupplementaryDataRequest.php +++ b/src/PayPal/Order/DTO/SupplementaryDataRequest.php @@ -38,10 +38,12 @@ public function getCard() /** * @param CardSupplementaryDataRequest $card * - * @return void + * @return $this */ public function setCard(CardSupplementaryDataRequest $card) { $this->card = $card; + + return $this; } }