From f6ec02160d744c1c1568386594afa81e919ff44b Mon Sep 17 00:00:00 2001 From: aslangery Date: Tue, 11 Jan 2022 11:54:24 +0300 Subject: [PATCH 1/4] refactor for Google Pay --- composer.json | 5 +- src/Sberbank/Message/BindCardRequest.php | 2 +- src/Sberbank/Message/BindingsRequest.php | 2 +- src/Sberbank/Message/GooglePaymentRequest.php | 183 ++++++++++++++++++ src/Sberbank/Message/OrderStatusRequest.php | 2 +- .../Message/PaymentCancellationRequest.php | 2 +- src/Sberbank/Message/RefundRequest.php | 2 +- src/Sberbank/Message/RegisterOrderRequest.php | 2 +- src/Sberbank/Message/RequestAbstract.php | 4 +- src/Sberbank/Message/UnbindCardRequest.php | 2 +- src/Sberbank/RestGateway.php | 11 ++ 11 files changed, 206 insertions(+), 11 deletions(-) create mode 100644 src/Sberbank/Message/GooglePaymentRequest.php diff --git a/composer.json b/composer.json index 2f225dc..5caa8bd 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "3DaVinci/sberbank-gateway", + "name": "3davinci/sberbank-gateway", "version": "0.1.4", "description": "Sberbank REST client", "type": "library", @@ -15,7 +15,8 @@ "php": "^7", "php-http/message": "^1.5", "php-http/discovery": "^1.2.1", - "php-http/guzzle6-adapter": "^1.1" + "php-http/guzzle6-adapter": "^1.1", + "ext-mbstring": "*" }, "require-dev": { "phpunit/phpunit": "6.1", diff --git a/src/Sberbank/Message/BindCardRequest.php b/src/Sberbank/Message/BindCardRequest.php index 441fcab..21057e7 100644 --- a/src/Sberbank/Message/BindCardRequest.php +++ b/src/Sberbank/Message/BindCardRequest.php @@ -37,6 +37,6 @@ public function validate() */ public function getMethodName() { - return 'bindCard.do'; + return 'rest/bindCard.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/BindingsRequest.php b/src/Sberbank/Message/BindingsRequest.php index dfe2563..4ee709e 100644 --- a/src/Sberbank/Message/BindingsRequest.php +++ b/src/Sberbank/Message/BindingsRequest.php @@ -38,6 +38,6 @@ public function validate() */ public function getMethodName() { - return 'getBindings.do'; + return 'rest/getBindings.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/GooglePaymentRequest.php b/src/Sberbank/Message/GooglePaymentRequest.php new file mode 100644 index 0000000..c7089b3 --- /dev/null +++ b/src/Sberbank/Message/GooglePaymentRequest.php @@ -0,0 +1,183 @@ +setParameter('merchant', $value); + } + + /** + * Номер (идентификатор) заказа в системе магазина, уникален для каждого магазина в пределах системы + * + * @param string|int $value + * @return RequestAbstract + */ + public function setOrderNumber($value) + { + return $this->setParameter('orderNumber', $value); + } + + /** + * Номер (идентификатор) заказа в системе магазина, уникален для каждого магазина в пределах системы + * + * @param string|int $value + * @return RequestAbstract + */ + public function setProtocolVersion($value) + { + return $this->setParameter('protocolVersion', $value); + } + + + /** + * Описание заказа в свободной форме + * + * @param string $value + * @return RequestAbstract + */ + public function setDescription(string $value) + { + return $this->setParameter('description', mb_substr($value, 0, 512)); + } + + /** + * Код валюты платежа ISO 4217. Если не указан, считается равным коду валюты по умолчанию. + * + * @param string $value + * @return RequestAbstract + */ + public function setCurrencyCode(string $value) + { + return $this->setParameter('currencyCode', $value); + } + + /** + * Язык в кодировке ISO 639-1. Если не указан, будет использован язык, указанный в настройках магазина как язык по умолчанию (default language). + * + * @param string $value + * @return RequestAbstract + */ + public function setLanguage(string $value) + { + return $this->setParameter('language', $value); + } + + /** + * Номер (идентификатор) клиента в системе магазина. Используется для реализации функционала связок. + * Может присутствовать, если магазину разрешено создание связок. + * + * @param string $value + * @return RequestAbstract + */ + public function setClientId(string $value) + { + return $this->setParameter('clientId', $value); + } + + /** + * Сумма платежа в копейках (или центах) + * + * @param int $value + * @return RequestAbstract + */ + public function setAmount(int $value) + { + return $this->setParameter('amount', $value); + } + + /** + * Адрес, на который требуется перенаправить пользователя в случае успешной оплаты. Адрес должен быть указан полностью, + * включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет + * перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>. + * + * @param string $value + * @return RequestAbstract + */ + public function setReturnUrl(string $value) + { + return $this->setParameter('returnUrl', $value); + } + + /** + * Адрес, на который требуется перенаправить пользователя в случае неуспешной оплаты. Адрес должен быть указан полностью, + * включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет + * перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>. + * + * @param string $value + * @return RequestAbstract + */ + public function setFailUrl(string $value) + { + return $this->setParameter('failUrl', $value); + } + + /** + * Номер телефона клиента. Может быть следующего формата: ^((+7|7|8)?([0-9]){10})$. + * + * @param string $value + * @return RequestAbstract + */ + public function setPhone(string $value) + { + return $this->setParameter('phone', $value); + } + + /** + * Адрес электронной почты покупателя. + * + * @param string $value + * @return RequestAbstract + */ + public function setEmail(string $value) + { + return $this->setParameter('email', $value); + } + + /** + * Токен, полученный от Google Pay и закодированный в Base64. + * + * @param string $value + * @return RequestAbstract + */ + public function setPaymentToken(string $value) + { + return $this->setParameter('paymentToken', $value); + } + + /** + * @throws \Sberbank\Exception\InvalidRequestException + */ + public function validate() + { + parent::validate('merchant', 'orderNumber', 'paymentToken', 'amount'); + } + + public function getMethodName() + { + return 'google/payment.do'; + } + + public function send() + { + /** @var \Psr\Http\Message\ResponseInterface $httpResponse */ + $httpResponse = $this->sberbankClient->get( + $this->getUrl() . '?' . http_build_query($this->getParameters()), + ['Content-type' => 'application/json'] + ); + + $body = $httpResponse->getBody(); + $jsonToArrayResponse = !empty($body) ? json_decode((string) $body, true) : []; + $responseClassName = $this->responseClassName; + + return $this->response = new $responseClassName($this, $jsonToArrayResponse, $httpResponse->getStatusCode()); + } +} \ No newline at end of file diff --git a/src/Sberbank/Message/OrderStatusRequest.php b/src/Sberbank/Message/OrderStatusRequest.php index 097c6f6..4881190 100644 --- a/src/Sberbank/Message/OrderStatusRequest.php +++ b/src/Sberbank/Message/OrderStatusRequest.php @@ -35,6 +35,6 @@ public function validate() */ public function getMethodName() { - return 'getOrderStatus.do'; + return 'rest/getOrderStatus.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/PaymentCancellationRequest.php b/src/Sberbank/Message/PaymentCancellationRequest.php index 254658c..862416a 100644 --- a/src/Sberbank/Message/PaymentCancellationRequest.php +++ b/src/Sberbank/Message/PaymentCancellationRequest.php @@ -37,6 +37,6 @@ public function validate() */ public function getMethodName() { - return 'reverse.do'; + return 'rest/reverse.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/RefundRequest.php b/src/Sberbank/Message/RefundRequest.php index 39a42de..8237e37 100644 --- a/src/Sberbank/Message/RefundRequest.php +++ b/src/Sberbank/Message/RefundRequest.php @@ -44,6 +44,6 @@ public function validate() */ public function getMethodName() { - return 'refund.do'; + return 'rest/refund.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/RegisterOrderRequest.php b/src/Sberbank/Message/RegisterOrderRequest.php index 98f2f30..71185ce 100644 --- a/src/Sberbank/Message/RegisterOrderRequest.php +++ b/src/Sberbank/Message/RegisterOrderRequest.php @@ -200,6 +200,6 @@ public function validate() */ public function getMethodName() { - return 'register.do'; + return 'rest/register.do'; } } \ No newline at end of file diff --git a/src/Sberbank/Message/RequestAbstract.php b/src/Sberbank/Message/RequestAbstract.php index 016c43d..767cd96 100644 --- a/src/Sberbank/Message/RequestAbstract.php +++ b/src/Sberbank/Message/RequestAbstract.php @@ -17,8 +17,8 @@ */ abstract class RequestAbstract implements RequestInterface { - protected $liveUrl = 'https://securepayments.sberbank.ru/payment/rest/'; - protected $testUrl = 'https://3dsec.sberbank.ru/payment/rest/'; + protected $liveUrl = 'https://securepayments.sberbank.ru/payment/'; + protected $testUrl = 'https://3dsec.sberbank.ru/payment/'; /** * The request parameters diff --git a/src/Sberbank/Message/UnbindCardRequest.php b/src/Sberbank/Message/UnbindCardRequest.php index 31822d1..f9f2c17 100644 --- a/src/Sberbank/Message/UnbindCardRequest.php +++ b/src/Sberbank/Message/UnbindCardRequest.php @@ -37,6 +37,6 @@ public function validate() */ public function getMethodName() { - return 'unBindCard.do'; + return 'rest/unBindCard.do'; } } \ No newline at end of file diff --git a/src/Sberbank/RestGateway.php b/src/Sberbank/RestGateway.php index 8bc1688..198b9a6 100644 --- a/src/Sberbank/RestGateway.php +++ b/src/Sberbank/RestGateway.php @@ -56,6 +56,17 @@ public function registerOrder(array $parameters = []) return $this->createRequest('RegisterOrder', $parameters); } + /** + * Запрос оплаты заказа через GooglePay + * + * @param array $parameters + * @return RequestAbstract + */ + public function googlePayment(array $parameters = []) + { + return $this->createRequest('GooglePayment', $parameters); + } + /** * Запрос отмены оплаты заказа * From 31524ecf8fbc4699f08f02e0c5e271b6ac8268d0 Mon Sep 17 00:00:00 2001 From: aslangery Date: Tue, 18 Jan 2022 12:02:55 +0300 Subject: [PATCH 2/4] fix: cart items in order. --- src/Sberbank/Http/Client.php | 16 ++++++++++ src/Sberbank/Message/RegisterOrderRequest.php | 31 +++++++++++++++++++ src/Sberbank/Message/RequestAbstract.php | 18 +++++++++-- 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/Sberbank/Http/Client.php b/src/Sberbank/Http/Client.php index 0e0e87b..dd07d58 100644 --- a/src/Sberbank/Http/Client.php +++ b/src/Sberbank/Http/Client.php @@ -75,6 +75,22 @@ public function get($uri, array $headers = []): ResponseInterface return $this->sendRequest($request); } + /** + * Send a POST request. + * + * @param UriInterface|string $uri + * @param array $headers + * @param null $body + * @return ResponseInterface + * @throws Exception + */ + public function post($uri, array $headers = [], $body = null): ResponseInterface + { + $request = $this->createRequest('POST', $uri, $headers, $body); + + return $this->sendRequest($request); + } + /** * @return HttpClient */ diff --git a/src/Sberbank/Message/RegisterOrderRequest.php b/src/Sberbank/Message/RegisterOrderRequest.php index dbd464e..e0a35aa 100644 --- a/src/Sberbank/Message/RegisterOrderRequest.php +++ b/src/Sberbank/Message/RegisterOrderRequest.php @@ -215,4 +215,35 @@ public function getMethodName(): string { return 'rest/register.do'; } + + public function send(): ResponseInterface + { + $httpResponse = $this->sberbankClient->post( + $this->getUrl() . '?' . http_build_query($this->getParameters([ + 'userName', + 'password', + 'orderNumber', + 'amount', + 'returnUrl', + 'failUrl', + 'pageView', + 'sessionTimeoutSecs', + 'currency', + 'language', + 'merchantLogin', + 'bindingId', + 'description', + 'phone', + 'email' + ])), + ['Content-type' => 'application/json'], + json_encode($this->getParameters(['orderBundle'])) + ); + + $body = $httpResponse->getBody(); + $jsonToArrayResponse = !empty($body) ? json_decode((string) $body, true) : []; + $responseClassName = $this->responseClassName; + + return $this->response = new $responseClassName($this, $jsonToArrayResponse, $httpResponse->getStatusCode()); + } } \ No newline at end of file diff --git a/src/Sberbank/Message/RequestAbstract.php b/src/Sberbank/Message/RequestAbstract.php index a06e2ec..f2a2715 100644 --- a/src/Sberbank/Message/RequestAbstract.php +++ b/src/Sberbank/Message/RequestAbstract.php @@ -115,13 +115,25 @@ public function setTestMode(bool $value): RequestAbstract } /** - * Get all parameters + * Return parameters listed in $keys + * Return all parameters if $keys empty * + * @param array $keys * @return array */ - public function getParameters(): array + public function getParameters(array $keys = []): array { - return $this->parameters; + if (empty($keys)) { + + return $this->parameters; + } else { + $params = []; + foreach ($keys as $key) { + $params[$key] = $this->getParameter($key); + } + + return $params; + } } /** From 2e1ba2d866f4f9ef7135576233dbaa61ae9ae473 Mon Sep 17 00:00:00 2001 From: aslangery Date: Tue, 18 Jan 2022 12:03:32 +0300 Subject: [PATCH 3/4] feat: Google Pay request and response --- src/Sberbank/Message/GooglePaymentRequest.php | 9 ++++---- .../Message/GooglePaymentResponse.php | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 src/Sberbank/Message/GooglePaymentResponse.php diff --git a/src/Sberbank/Message/GooglePaymentRequest.php b/src/Sberbank/Message/GooglePaymentRequest.php index c7089b3..a4effb9 100644 --- a/src/Sberbank/Message/GooglePaymentRequest.php +++ b/src/Sberbank/Message/GooglePaymentRequest.php @@ -166,12 +166,13 @@ public function getMethodName() return 'google/payment.do'; } - public function send() + public function send(): ResponseInterface { /** @var \Psr\Http\Message\ResponseInterface $httpResponse */ - $httpResponse = $this->sberbankClient->get( - $this->getUrl() . '?' . http_build_query($this->getParameters()), - ['Content-type' => 'application/json'] + $httpResponse = $this->sberbankClient->post( + $this->getUrl(), + ['Content-type' => 'application/json'], + json_encode($this->getParameters(['orderBundle'])) ); $body = $httpResponse->getBody(); diff --git a/src/Sberbank/Message/GooglePaymentResponse.php b/src/Sberbank/Message/GooglePaymentResponse.php new file mode 100644 index 0000000..51da8f1 --- /dev/null +++ b/src/Sberbank/Message/GooglePaymentResponse.php @@ -0,0 +1,22 @@ + 'Обработка запроса прошла без системных ошибок', + 1 => 'Недостаточно средств на карте', + 5 => 'Доступ запрещён.', + 7 => 'Системная ошибка', + 10 => 'Некорректное значение параметра' + ]; + + /** + * @return string|null + */ + public function getOrderId(): ?string + { + return $this->data['orderId'] ?? null; + } +} \ No newline at end of file From 446da5b96115306f5d269c850edb510c91f245ab Mon Sep 17 00:00:00 2001 From: aslangery Date: Tue, 18 Jan 2022 12:04:09 +0300 Subject: [PATCH 4/4] change version to 0.2.2 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 8b0ffad..1f2f8ab 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "3davinci/sberbank-gateway", - "version": "0.2.0", + "version": "0.2.2", "description": "Sberbank REST client", "type": "library", "license": "MIT",