Skip to content

Commit 8374bc6

Browse files
committed
new methods: oneTimeTokenPayment, getSession
1 parent 84f52b6 commit 8374bc6

11 files changed

Lines changed: 296 additions & 3 deletions

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ require vendor/autoload.php;
3737
7. [Проверка статуса платежа](src/Examples/paymentGetStatus.php)
3838
7. [Выплаты на банковские карты](src/Examples/payoutCreate.php)
3939
8. [Запрос отчёта](src/Examples/getReport.php)
40+
8. [Создание сессии](src/Examples/getSessionId.php)
4041
9. [Страница после оплаты](src/Examples/returnPage.php)
4142

4243
## Ссылки

example.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343
case 'paymentRefund':
4444
case 'paymentRefundMarketplace':
4545
case 'getReport':
46+
case 'getSession':
47+
case 'oneTimeTokenPayment':
4648
case 'returnPage':
4749
require './src/Examples/start.php';
4850
@include './src/Examples/'.$_GET['function'] . '__prepend.php';

example_list.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,18 @@
8282
'docLink' => 'https://dev.ypmn.ru/ru/documents/api-dlia-otchetov/',
8383
'link' => '',
8484
],
85+
'getSession' => [
86+
'name' => 'Создание сессии',
87+
'about' => 'Создание уникальной сессии YPMN',
88+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Sessions/paths/~1v4~1payments~1sessions/post',
89+
'link' => '',
90+
],
91+
'oneTimeTokenPayment' => [
92+
'name' => 'Оплата одноразовым токеном',
93+
'about' => 'Оплата одноразовым токеном',
94+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1authorize/post',
95+
'link' => '',
96+
],
8597
'returnPage' => [
8698
'name' => 'Страница после оплаты',
8799
'about' => 'Это пример странцы, на которую плательщик возвращается после совершения платежа.',

src/ApiRequest.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class ApiRequest implements ApiRequestInterface
1818
const STATUS_API = '/api/v4/payments/status';
1919
const PAYOUT_CREATE_API = '/api/v4/payout';
2020
const REPORTS_ORDERS_API = '/reports/orders';
21+
const SESSION_API = '/api/v4/payments/sessions';
2122
const HOST = 'https://secure.ypmn.ru';
2223
const SANDBOX_HOST = 'https://sandbox.ypmn.ru';
2324
const LOCAL_HOST = 'http://localhost';
@@ -309,10 +310,8 @@ private function sendPostRequest(JsonSerializable $data, string $api): array
309310
echo '<br><a href="https://github.com/yourpayments/php-api-client/issues">Оставить заявку на улучшение</a>';
310311
echo '<br><a href="https://ypmn.ru/ru/contacts/">Контакты</a>';
311312
} else {
312-
313313
$cpanel_url = 'https://' . ($this->getSandboxMode() ? 'sandbox' : 'secure' ). '.ypmn.ru/cpanel/';
314314

315-
316315
if ($this->getSandboxMode()) {
317316
echo Std::alert([
318317
'type' => 'warning',
@@ -344,6 +343,14 @@ private function sendPostRequest(JsonSerializable $data, string $api): array
344343
return ['response' => $response, 'error' => $err];
345344
}
346345

346+
/** @inheritdoc
347+
* @throws PaymentException
348+
*/
349+
public function sendSessionRequest(SessionRequest $sessionRequest): array
350+
{
351+
return $this->sendPostRequest($sessionRequest, self::SESSION_API);
352+
}
353+
347354
/** @inheritdoc */
348355
public function sendAuthRequest(PaymentInterface $payment): array
349356
{
@@ -380,6 +387,7 @@ public function sendTokenPaymentRequest(MerchantToken $tokenHash): array
380387
return $this->sendPostRequest($tokenHash, self::AUTHORIZE_API);
381388
}
382389

390+
/** @inheritDoc */
383391
public function sendPayoutCreateRequest(PayoutInterface $payout)
384392
{
385393
return $this->sendPostRequest($payout, self::PAYOUT_CREATE_API);

src/ApiRequestInterface.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ interface ApiRequestInterface
1010
*/
1111
function __construct(MerchantInterface $merchant);
1212

13+
/**
14+
* Запрос ID сессии
15+
* @param SessionRequest $sessionRequest
16+
* @return array
17+
*/
18+
function sendSessionRequest(SessionRequest $sessionRequest): array;
19+
1320
/**
1421
* Отправить Запрос на Оплату
1522
* @param PaymentInterface $payment Оплата

src/Authorization.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace Ypmn;
44

5+
/**
6+
* Авторизация платежа
7+
*/
58
class Authorization implements AuthorizationInterface
69
{
710
const TYPE_CCVISAMC = 'CCVISAMC';
@@ -23,6 +26,9 @@ class Authorization implements AuthorizationInterface
2326
/** @var PaymentPageOptions|null */
2427
private ?PaymentPageOptions $paymentPageOptions = null;
2528

29+
/** @var OneTimeUseToken|null Одноразовый токен оплаты */
30+
private ?OneTimeUseToken $oneTimeUseToken;
31+
2632
/**
2733
* Создать Платёжную Авторизацию
2834
* @param string $paymentMethodType Метод оплаты (из справочника)
@@ -91,7 +97,7 @@ public function getCardDetails(): ?CardDetailsInterface
9197
}
9298

9399
/** @inheritDoc */
94-
public function setCardDetails(CardDetailsInterface $cardDetails): self
100+
public function setCardDetails(?CardDetailsInterface $cardDetails): self
95101
{
96102
if (is_null($this->merchantToken) && $this->usePaymentPage === false) {
97103
$this->cardDetails = $cardDetails;
@@ -108,6 +114,15 @@ public function getMerchantToken(): ?MerchantTokenInterface
108114
return $this->merchantToken;
109115
}
110116

117+
public function setOneTimeUseToken(?OneTimeUseToken $oneTimeUseToken): self
118+
{
119+
$this->setCardDetails(null);
120+
$this->setUsePaymentPage(false);
121+
$this->oneTimeUseToken = $oneTimeUseToken;
122+
123+
return $this;
124+
}
125+
111126
/**
112127
* @inheritDoc
113128
* @throws PaymentException
@@ -151,6 +166,10 @@ public function arraySerialize(): array
151166
$resultArray['cardDetails'] = $this->cardDetails->toArray();
152167
}
153168

169+
if (!is_null($this->oneTimeUseToken)) {
170+
$resultArray['oneTimeUseToken'] = $this->oneTimeUseToken->toArray();
171+
}
172+
154173
if (!is_null($this->merchantToken)) {
155174
$resultArray['merchantToken'] = $this->merchantToken->toArray();
156175
}

src/Examples/getSession.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Ypmn\ApiRequest;
6+
use Ypmn\SessionRequest;
7+
8+
// Подключим файл, в котором заданы параметры мерчанта
9+
include_once 'start.php';
10+
11+
// Запрос на сессию со временем жизни = полчаса
12+
$sessionRequest = new SessionRequest(30);
13+
14+
// Отправим запрос
15+
$apiRequest = new ApiRequest($merchant);
16+
$apiRequest->setSandboxMode();
17+
$apiRequest->setDebugMode();
18+
19+
try {
20+
$session = $apiRequest->sendSessionRequest($sessionRequest);
21+
22+
} catch (\Ypmn\PaymentException $e) {
23+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Ypmn\Authorization;
6+
use Ypmn\MerchantToken;
7+
use Ypmn\OneTimeUseToken;
8+
use Ypmn\Payment;
9+
use Ypmn\Client;
10+
use Ypmn\Billing;
11+
use Ypmn\ApiRequest;
12+
use Ypmn\PaymentException;
13+
use Ypmn\Product;
14+
use Ypmn\Std;
15+
16+
// Подключим файл, в котором заданы параметры мерчанта
17+
include_once 'start.php';
18+
19+
// Оплата по токену
20+
// Установим номер (ID) заказа (номер заказа в вашем магазине, должен быть уникален в вашей системе)
21+
$merchantPaymentReference = "order_id_" . time();
22+
$orderAsProduct = new Product([
23+
'name' => 'Заказ №' . $merchantPaymentReference,
24+
'sku' => $merchantPaymentReference,
25+
'unitPrice' => 1.42,
26+
'quantity' => 2,
27+
]);
28+
29+
// Опишем Биллинговую (платёжную) информацию
30+
$billing = new Billing;
31+
// Установим Код страны
32+
$billing->setCountryCode('RU');
33+
// Установим Имя Плательщика
34+
$billing->setFirstName('Иван');
35+
// Установим Фамилия Плательщика
36+
$billing->setLastName('Петров');
37+
// Установим Email Плательщика
38+
$billing->setEmail('test1@ypmn.ru');
39+
// Установим Телефон Плательщика
40+
$billing->setPhone('+7-800-555-35-35');
41+
// Установим Город
42+
$billing->setCity('Москва');
43+
44+
// Создадим клиентское подключение
45+
$client = new Client;
46+
// Установим биллинг
47+
$client->setBilling($billing);
48+
49+
// Создадим платёж
50+
$payment = new Payment;
51+
// Установим позиции
52+
$payment->addProduct($orderAsProduct);
53+
// Установим валюту
54+
$payment->setCurrency('RUB');
55+
56+
// токен
57+
$oneTimeUseToken = new OneTimeUseToken($_REQUEST['token'] ?? 'some token', $_REQUEST['sessionId'] ?? 'test session id');
58+
59+
$auth = new Authorization();
60+
$auth->setUsePaymentPage(false);
61+
$auth->setPaymentMethod('CCVISAMC');
62+
$auth->setOneTimeUseToken($oneTimeUseToken);
63+
64+
// Создадим и установим авторизацию по типу платежа
65+
$payment->setAuthorization($auth);
66+
67+
// Установим номер заказа (должен быть уникальным в вашей системе)
68+
$payment->setMerchantPaymentReference($merchantPaymentReference);
69+
// Установим адрес перенаправления пользователя после оплаты
70+
$payment->setReturnUrl('https://test.u2go.ru/php-api-client/?function=returnPage');
71+
// Установим клиентское подключение
72+
$payment->setClient($client);
73+
74+
// Создадим HTTP-запрос к API
75+
$apiRequest = new ApiRequest($merchant);
76+
// Включить режим отладки (закомментируйте или удалите в рабочей программе!)
77+
$apiRequest->setDebugMode();
78+
// Переключиться на тестовый сервер (закомментируйте или удалите в рабочей программе!)
79+
$apiRequest->setSandboxMode();
80+
81+
$responseData = $apiRequest->sendAuthRequest($payment);
82+
// Преобразуем ответ из JSON в массив
83+
try {
84+
$responseData = json_decode((string) $responseData["response"], true);
85+
86+
} catch (Exception $exception) {
87+
//TODO: обработка исключения
88+
echo Std::alert([
89+
'text' => '
90+
Извините, платёжный метод временно недоступен.<br>
91+
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
92+
<br>
93+
<pre>' . $exception->getMessage() . '</pre>',
94+
'type' => 'danger',
95+
]);
96+
97+
throw new PaymentException('Платёжный метод временно недоступен');
98+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<div class="card mt-3 mb-5">
2+
<div class="card-body">
3+
<form method="post">
4+
<div class="form-group">
5+
<label for="i1">Одноразовый токен</label>
6+
<input type="text" class="form-control" id="i1" autofocus required>
7+
</div>
8+
<div class="form-group">
9+
<label for="i2">ID сессии</label>
10+
<input type="text" class="form-control" id="i2" required>
11+
</div>
12+
<button type="submit" class="btn btn-primary mt-2">Отправить</button>
13+
</form>
14+
</div>
15+
</div>

src/OneTimeUseToken.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Ypmn;
4+
5+
/**
6+
* Это класс для одноразовых токенов
7+
**/
8+
class OneTimeUseToken
9+
{
10+
/** @var string Сам токен */
11+
private string $token;
12+
13+
/** @var string Id сеси */
14+
private string $sessionId;
15+
16+
/**
17+
* @param string $token
18+
* @param string $sessionId
19+
*/
20+
public function __construct(string $token, string $sessionId)
21+
{
22+
$this->setToken($token);
23+
$this->setSessionId($sessionId);
24+
}
25+
26+
/**
27+
* @return string
28+
*/
29+
public function getToken(): string
30+
{
31+
return $this->token;
32+
}
33+
34+
/**
35+
* @param string $token
36+
* @return OneTimeUseToken
37+
*/
38+
public function setToken(string $token): self
39+
{
40+
$this->token = $token;
41+
42+
return $this;
43+
}
44+
45+
/**
46+
* @return string
47+
*/
48+
public function getSessionId(): string
49+
{
50+
return $this->sessionId;
51+
}
52+
53+
/**
54+
* @param string $sessionId
55+
* @return OneTimeUseToken
56+
*/
57+
public function setSessionId(string $sessionId): self
58+
{
59+
$this->sessionId = $sessionId;
60+
61+
return $this;
62+
}
63+
64+
public function toArray()
65+
{
66+
return [
67+
'token' => $this->getToken(),
68+
'sessionId' => $this->getSessionId(),
69+
];
70+
}
71+
}

0 commit comments

Comments
 (0)