Skip to content

Commit bc735d8

Browse files
committed
added reports api
1 parent 988164d commit bc735d8

File tree

6 files changed

+180
-23
lines changed

6 files changed

+180
-23
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ composer.phar
44
# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
55
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
66
# composer.lock
7+
8+
.ai

example.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
case 'paymentWebhook':
4343
case 'paymentRefund':
4444
case 'paymentRefundMarketplace':
45+
case 'getReport':
4546
case 'returnPage':
4647
require './src/Examples/start.php';
4748
@include './src/Examples/'.$_GET['function'] . '__prepend.php';

example_list.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,16 @@
7272
],
7373
'payoutCreate' => [
7474
'name' => 'Создание выплаты',
75-
'about' => 'Запрос к YPMN для совершения выплаты на карту. У вас должно быть достаточно средств на специальном счету для выплат.<br><br>Тестовая карта (для выплат на тестовом контуре): 4149605380309302',
75+
'about' => 'Запрос к YPMN для совершения выплаты на карту (для компаний, сертифицированных по PCI-DSS). У вас должно быть достаточно средств на специальном счету для выплат.<br><br>Тестовая карта (для выплат на тестовом контуре): 4149605380309302',
7676
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payouts-API',
7777
'link' => '',
7878
],
79+
'getReport' => [
80+
'name' => 'Запрос отчёта',
81+
'about' => 'Запрос к YPMN для генерации отчёта',
82+
'docLink' => 'https://dev.ypmn.ru/ru/documents/api-dlia-otchetov/',
83+
'link' => '',
84+
],
7985
'returnPage' => [
8086
'name' => 'Страница после оплаты',
8187
'about' => 'Это пример странцы, на которую плательщик возвращается после совершения платежа.',

src/ApiRequest.php

Lines changed: 128 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class ApiRequest implements ApiRequestInterface
1717
const REFUND_API = '/api/v4/payments/refund';
1818
const STATUS_API = '/api/v4/payments/status';
1919
const PAYOUT_CREATE_API = '/api/v4/payout';
20+
const REPORTS_ORDERS_API = '/reports/orders';
2021
const HOST = 'https://secure.ypmn.ru';
2122
const SANDBOX_HOST = 'https://sandbox.ypmn.ru';
2223
const LOCAL_HOST = 'http://localhost';
@@ -40,25 +41,141 @@ public function __construct(MerchantInterface $merchant)
4041
$this->merchant = $merchant;
4142
}
4243

44+
public function getHost() : string
45+
{
46+
if ($this->localModeIsOn) {
47+
return self::LOCAL_HOST;
48+
} else {
49+
return ($this->getSandboxMode() ? self::SANDBOX_HOST : self::HOST);
50+
}
51+
}
52+
53+
public function sendGetReportRequest(?string $startDate = null, ?string $endDate = null, ?array $orderStatus = null): string
54+
{
55+
//проверить даты
56+
if ($startDate !== null) {
57+
if (($startDate = strtotime($startDate)) === false) {
58+
throw new \Exception('Неверная дата для формирования запроса');
59+
} else {
60+
$startDate = date('Y-m-d', $startDate);
61+
}
62+
} else {
63+
$startDate = date('Y-m-d', strtotime('today'));
64+
}
65+
66+
if ($endDate !== null) {
67+
if (($endDate = strtotime($endDate)) === false) {
68+
throw new \Exception('Неверная дата для формирования запроса');
69+
} else {
70+
$endDate = date('Y-m-d', $endDate);
71+
}
72+
} else {
73+
$endDate = date('Y-m-d', strtotime('tomorrow'));
74+
}
75+
76+
$merchant = $this->merchant->getCode();
77+
$timeStamp = time();
78+
79+
// $parameters = compact('merchant', 'startDate', 'endDate', 'orderStatus', 'timeStamp');
80+
$parameters = compact('merchant', 'startDate', 'endDate', 'timeStamp');
81+
82+
83+
//сформировать URL
84+
$url = $this->getHost()
85+
. $this::REPORTS_ORDERS_API
86+
. '?'
87+
. http_build_query($parameters)
88+
. '&signature='
89+
. $this->reportsSign($parameters);
90+
91+
92+
if ($this->getDebugMode()) {
93+
echo Std::alert([
94+
'text' => $url,
95+
]);
96+
}
97+
98+
// отправить запрос
99+
$curl = curl_init();
100+
$requestHttpVerb = 'GET';
101+
102+
$date = (new DateTime())->format(DateTimeInterface::ATOM);
103+
$setopt_array = [
104+
CURLOPT_URL => $url,
105+
CURLOPT_RETURNTRANSFER => true,
106+
CURLOPT_ENCODING => '',
107+
CURLOPT_MAXREDIRS => 10,
108+
CURLOPT_TIMEOUT => 30,
109+
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
110+
CURLOPT_CUSTOMREQUEST => $requestHttpVerb,
111+
CURLOPT_HTTPHEADER => [
112+
'Accept: application/json',
113+
'Content-Type: application/json',
114+
'X-Header-Date: ' . $date,
115+
// 'X-Header-Merchant: ' . $this->merchant->getCode()
116+
]
117+
];
118+
119+
curl_setopt_array($curl, $setopt_array);
120+
121+
$response = curl_exec($curl);
122+
$err = curl_error($curl);
123+
curl_close($curl);
124+
125+
if ($this->getDebugMode()) {
126+
$this->echoDebugMessage('Ответ от ' . $this->getHost() . ':');
127+
$this->echoDebugMessage(Std::json_fix_cyr($response));
128+
129+
if ($err) {
130+
$this->echoDebugMessage('Ошибка:');
131+
$this->echoDebugMessage($err);
132+
}
133+
}
134+
135+
// вернуть результат
136+
return Std::json_fix_cyr($response);
137+
}
138+
139+
private function buildReportsSourceString($parameters)
140+
{
141+
$hashString = '';
142+
143+
foreach ($parameters as $currentData) {
144+
// if (is_array($currentData)) {
145+
// //TODO
146+
// $currentData = '';
147+
// }
148+
149+
if (strlen($currentData) > 0) {
150+
$hashString .= strlen($currentData);
151+
$hashString .= $currentData;
152+
}
153+
}
154+
155+
return $hashString;
156+
}
157+
158+
private function reportsSign($parameters)
159+
{
160+
$sourceString = $this->buildReportsSourceString($parameters);
161+
162+
return hash_hmac('MD5', $sourceString, $this->merchant->getSecret());
163+
}
164+
43165
/**
44166
* Отправка GET-запроса
45167
* @param string $api адрес API (URI)
46168
* @return array ответ сервера Ypmn
169+
* @throws PaymentException
47170
*/
48171
private function sendGetRequest(string $api): array
49172
{
50173
$curl = curl_init();
51174
$date = (new DateTime())->format(DateTimeInterface::ATOM);
52175
$requestHttpVerb = 'GET';
53176

54-
if ($this->localModeIsOn) {
55-
$urlToPostTo = self::LOCAL_HOST . $api;
56-
} else {
57-
$urlToPostTo = ($this->getSandboxMode() ? self::SANDBOX_HOST : self::HOST) . $api;
58-
}
59-
60177
$setopt_array = [
61-
CURLOPT_URL => $urlToPostTo,
178+
CURLOPT_URL => $this->getHost() . $api,
62179
CURLOPT_RETURNTRANSFER => true,
63180
CURLOPT_ENCODING => '',
64181
CURLOPT_MAXREDIRS => 10,
@@ -73,7 +190,7 @@ private function sendGetRequest(string $api): array
73190
'X-Header-Signature:' . $this->getSignature(
74191
$this->merchant,
75192
$date,
76-
$urlToPostTo,
193+
$this->getHost() . $api,
77194
$requestHttpVerb,
78195
md5(''),
79196
)
@@ -88,7 +205,7 @@ private function sendGetRequest(string $api): array
88205

89206
if (true === $this->getDebugMode()) {
90207
$this->echoDebugMessage('GET-Запрос к серверу Ypmn:');
91-
$this->echoDebugMessage($urlToPostTo);
208+
$this->echoDebugMessage($this->getHost() . $api);
92209
$this->echoDebugMessage('Ответ от сервера Ypmn:');
93210
$this->echoDebugMessage(json_encode(json_decode($response), JSON_PRETTY_PRINT));
94211

@@ -149,14 +266,8 @@ private function sendPostRequest(JsonSerializable $data, string $api): array
149266
$date = (new DateTime())->format(DateTimeInterface::ATOM);
150267
$requestHttpVerb = 'POST';
151268

152-
if ($this->localModeIsOn) {
153-
$urlToPostTo = self::LOCAL_HOST . $api;
154-
} else {
155-
$urlToPostTo = ($this->getSandboxMode() ? self::SANDBOX_HOST : self::HOST) . $api;
156-
}
157-
158269
curl_setopt_array($curl, [
159-
CURLOPT_URL => $urlToPostTo,
270+
CURLOPT_URL => $this->getHost() . $api,
160271
CURLOPT_RETURNTRANSFER => true,
161272
CURLOPT_ENCODING => '',
162273
CURLOPT_MAXREDIRS => 10,
@@ -172,7 +283,7 @@ private function sendPostRequest(JsonSerializable $data, string $api): array
172283
'X-Header-Signature:' . $this->getSignature(
173284
$this->merchant,
174285
$date,
175-
$urlToPostTo,
286+
$this->getHost() . $api,
176287
$requestHttpVerb,
177288
$encodedJsonDataHash
178289
)

src/Examples/getPaymentLink.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@
123123
// Установим номер заказа (должен быть уникальным в вашей системе)
124124
$payment->setMerchantPaymentReference('primer_nomer__' . time());
125125
// Установим адрес перенаправления пользователя после оплаты
126-
$payment->setReturnUrl('https://test.u2go.ru/php-api-client/?function=returnPage');
126+
$payment->setReturnUrl('http://' . $_SERVER['SERVER_NAME'] . '/php-api-client/?function=returnPage');
127127
// Установим клиентское подключение
128128
$payment->setClient($client);
129129

@@ -151,10 +151,10 @@
151151
//TODO: обработка исключения
152152
echo Std::alert([
153153
'text' => '
154-
Извините, платёжный метод временно недоступен.<br>
155-
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
156-
<br>
157-
<pre>' . $exception->getMessage() . '</pre>',
154+
Извините, платёжный метод временно недоступен.<br>
155+
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
156+
<br>
157+
<pre>' . $exception->getMessage() . '</pre>',
158158
'type' => 'danger',
159159
]);
160160

src/Examples/getReport.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Ypmn\ApiRequest;
6+
use Ypmn\Report;
7+
8+
// Подключим файл, в котором заданы параметры мерчанта
9+
include_once 'start.php';
10+
11+
// Хотим получить токен
12+
// Создадим HTTP-запрос к API
13+
$apiRequest = new ApiRequest($merchant);
14+
// Включить режим отладки (закомментируйте или удалите в рабочей программе)
15+
$apiRequest->setDebugMode();
16+
// Переключиться на тестовый сервер (закомментируйте или удалите в рабочей программе)
17+
$apiRequest->setSandboxMode();
18+
19+
// Выберем даты
20+
$startDate = date('Y-m-d');
21+
$endDate = date('Y-m-d');
22+
23+
// Выберем, какие транзакции нам интересны
24+
$transactionStatuses = [
25+
'COMPLETE',
26+
];
27+
28+
// TODO: refactor
29+
30+
// отправим запрос
31+
$result = $apiRequest->sendGetReportRequest(
32+
$startDate,
33+
$endDate,
34+
$transactionStatuses
35+
);
36+
37+
$report = new Report($result);

0 commit comments

Comments
 (0)