Skip to content

Commit a93b852

Browse files
committed
added orderTimeout example
1 parent 9481da5 commit a93b852

18 files changed

+744
-8
lines changed

example.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,14 @@
3838
case 'paymentByToken':
3939
case 'paymentCapture':
4040
case 'paymentGetStatus':
41+
case 'payoutCreate':
4142
case 'paymentWebhook':
4243
case 'paymentRefund':
4344
case 'paymentRefundMarketplace':
4445
case 'returnPage':
45-
include './src/Examples/start.php';
46-
include './src/Examples/'.$_GET['function'] . '.php';
46+
require './src/Examples/start.php';
47+
@include './src/Examples/'.$_GET['function'] . '__prepend.php';
48+
require './src/Examples/'.$_GET['function'] . '.php';
4749
break;
4850

4951
default:

example_header.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,8 @@
8888
'text' => $examples[ $_GET['function'] ]['about'] . '
8989
<br>
9090
<br>
91-
<a target="_blank" href="https://github.com/yourpayments/php-api-client/blob/main/src/Examples/'. $_GET['function'] .'.php" class="alert-link">Адрес этого примера на Github</a>
91+
<a class="btn btn-outline-success mr-3" target="_blank" href="https://github.com/yourpayments/php-api-client/blob/main/src/Examples/'. $_GET['function'] .'.php" class="alert-link">Адрес этого примера на Github</a>
92+
'.( !$examples[ $_GET['function'] ]['docLink'] ? '' : '<a class="btn btn-outline-success m-3" target="_blank" href="'.$examples[ $_GET['function'] ]['docLink'].'" class="alert-link">Документация API</a>' ).'
9293
',
9394
]);
9495
}

example_list.php

+14
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@
1717
'simpleGetPaymentLink' => [
1818
'name' => 'Самая простая кнопка оплаты',
1919
'about' => 'В этом примере показана самая простая реализация. С минимальным набором полей без детализации, просто оплата заказа c определённой суммой.',
20+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1authorize/post',
2021
'link' => '',
2122
],
2223
'getPaymentLink' => [
2324
'name' => 'Платёж со всеми подробностями',
2425
'about' => 'Это пример платежа с максимальным набором полей.',
26+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1authorize/post',
2527
'link' => '',
2628
],
2729
'getPaymentLinkMarketplace' => [
@@ -32,31 +34,43 @@
3234
'getToken' => [
3335
'name' => 'Создание токена',
3436
'about' => 'Приложение передаёт номер успешно оплаченного заказа в YPMN API, и получает в ответ платёжный токен',
37+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Token-API/paths/~1v4~1token/post',
3538
'link' => '',
3639
],
3740
'paymentByToken' => [
3841
'name' => 'Оплата токеном',
3942
'about' => 'Оплата с помощью токена (теперь не нужно повторно вводить данные банковской карты)',
43+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1authorize/post',
4044
'link' => '',
4145
],
4246
'paymentCapture' => [
4347
'name' => 'Списание средств',
4448
'about' => 'Списание ранее заблокированной на счету суммы. Не обязательно, если у Вас настроена оплата в 1 шаг.',
49+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1capture/post',
4550
'link' => '',
4651
],
4752
'paymentRefund' => [
4853
'name' => 'Возврат средств',
4954
'about' => 'Запрос на полный или частичный возврат средств.',
55+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1refund/post',
5056
'link' => '',
5157
],
5258
'paymentRefundMarketplace' => [
5359
'name' => 'Возврат средств со сплитом',
5460
'about' => 'Запрос на полный или частичный возврат средств с разделением на несколько получателей.',
61+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1refund/posts',
5562
'link' => '',
5663
],
5764
'paymentGetStatus' => [
5865
'name' => 'Проверка статуса платежа',
5966
'about' => 'Запрос к YPMN API о состоянии платежа.',
67+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payment-API/paths/~1v4~1payments~1status~1{merchantPaymentReference}/get',
68+
'link' => '',
69+
],
70+
'payoutCreate' => [
71+
'name' => 'Создание выплаты',
72+
'about' => 'Запрос к YPMN для совершения выплаты на карту. У вас должно быть достаточно средств на специальном счету для выплат.',
73+
'docLink' => 'https://secure.ypmn.ru/docs/#tag/Payouts-API',
6074
'link' => '',
6175
],
6276
'returnPage' => [

src/Amount.php

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Ypmn;
4+
5+
/**
6+
* Это класс Баланса (сколько + валюта)
7+
**/
8+
class Amount implements AmountInterface
9+
{
10+
private float $value;
11+
private string $currency = 'RUB';
12+
13+
/** @throws PaymentException */
14+
public function __construct(float $value, $currency='RUB')
15+
{
16+
$this->setValue($value);
17+
18+
$this->setCurrency($currency);
19+
}
20+
21+
/** @inheritdoc */
22+
public function getValue(): float
23+
{
24+
return $this->value;
25+
}
26+
27+
/** @inheritdoc
28+
*/
29+
public function setValue(float $value): self
30+
{
31+
if ($value < 1) {
32+
throw new PaymentException('Слишком маленькая выплата');
33+
}
34+
35+
$this->value = $value;
36+
37+
return $this;
38+
}
39+
40+
/** @inheritdoc */
41+
public function getCurrency(): string
42+
{
43+
return $this->currency;
44+
}
45+
46+
/** @inheritdoc */
47+
public function setCurrency(string $currency): self
48+
{
49+
$this->currency = $currency;
50+
51+
return $this;
52+
}
53+
54+
/** @inheritdoc */
55+
public function arraySerialize() : array
56+
{
57+
return [
58+
"currency" => $this->getCurrency() ?? 'RUB',
59+
"value" => $this->getValue()
60+
];
61+
}
62+
}

src/AmountInterface.php

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Ypmn;
4+
5+
interface AmountInterface
6+
{
7+
8+
/**
9+
* @return float
10+
*/
11+
public function getValue(): float;
12+
13+
14+
/**
15+
* @param float $value
16+
* @return Amount
17+
* @throws PaymentException
18+
*/
19+
public function setValue(float $value): self;
20+
21+
/**
22+
* @return string
23+
*/
24+
public function getCurrency(): string;
25+
26+
/**
27+
* @param string $currency
28+
* @return Amount
29+
*/
30+
public function setCurrency(string $currency): self;
31+
32+
33+
34+
35+
36+
37+
}

src/ApiRequest.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ class ApiRequest implements ApiRequestInterface
1616
const TOKEN_API = '/api/v4/token';
1717
const REFUND_API = '/api/v4/payments/refund';
1818
const STATUS_API = '/api/v4/payments/status';
19+
const PAYOUT_CREATE_API = '/api/v4/payout';
1920
const HOST = 'https://secure.ypmn.ru';
2021
const SANDBOX_HOST = 'https://sandbox.ypmn.ru';
2122

23+
2224
/** @var MerchantInterface Мерчант, от имени которого отправляется запрос */
2325
private MerchantInterface $merchant;
2426

25-
/** @var bool Режим Песочницы (тестовая панель Ypmn */
27+
/** @var bool Режим Песочницы (тестовая панель Ypmn) */
2628
private bool $sandboxModeIsOn = false;
2729

2830
/** @var bool Режим Отладки (вывод системных сообщений) */
@@ -251,6 +253,11 @@ public function sendTokenPaymentRequest(MerchantToken $tokenHash): array
251253
return $this->sendPostRequest($tokenHash, self::AUTHORIZE_API);
252254
}
253255

256+
public function sendPayoutCreateRequest(PayoutInterface $payout)
257+
{
258+
return $this->sendPostRequest($payout, self::PAYOUT_CREATE_API);
259+
}
260+
254261
/**
255262
* Подпись запроса
256263
* @param MerchantInterface $merchant Мерчант
@@ -321,4 +328,5 @@ class="w-100 d-block"
321328
>'.print_r($mixedInput, true).'</pre>';
322329
}
323330
}
331+
324332
}

src/Billing.php

+18-1
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
class Billing implements BillingInterface
66
{
7+
/** @var string Тип */
8+
private string $type = 'individual';
9+
710
/** @var string Имя */
811
private string $firstName;
912

10-
/** @var string Фамилия */
13+
/** @var ?string Фамилия */
1114
private string $lastName;
1215

1316
/** @var string Email */
@@ -212,4 +215,18 @@ public function getIdentityDocument(): ?IdentityDocumentInterface
212215
{
213216
return $this->identityDocument ?? null;
214217
}
218+
219+
/** @inheritdoc */
220+
public function getType(): string
221+
{
222+
return $this->type;
223+
}
224+
225+
/** @inheritdoc */
226+
public function setType(string $type): self
227+
{
228+
$this->type = $type;
229+
230+
return $this;
231+
}
215232
}

src/BillingInterface.php

+15
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,19 @@ public function setIdentityDocument(IdentityDocumentInterface $identityDocument)
172172
* @return null|IdentityDocumentInterface Удостоверение Личности
173173
*/
174174
public function getIdentityDocument(): ?IdentityDocumentInterface;
175+
176+
177+
/**
178+
* Получить тип биллинга
179+
* @return string
180+
*/
181+
public function getType(): string;
182+
183+
/**
184+
* Установить тип биллинга
185+
* @param string $type
186+
* @return Billing
187+
*/
188+
public function setType(string $type): self;
189+
175190
}

src/CardDetails.php

+2
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ public function getNumber(): string
4646
/** @inheritDoc */
4747
public function setNumber(string $number): self
4848
{
49+
//TODO: проверка на валидность
4950
$this->number = $number;
51+
5052
return $this;
5153
}
5254

src/Examples/payoutCreate.php

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php declare(strict_types=1);
2+
3+
use Ypmn\Amount;
4+
use Ypmn\ApiRequest;
5+
use Ypmn\Billing;
6+
use Ypmn\Payout;
7+
use Ypmn\PayoutDestination;
8+
use Ypmn\PayoutSource;
9+
10+
// Подключим файл, в котором заданы параметры мерчанта
11+
include_once 'start.php';
12+
13+
/**
14+
* Это файл с примером для создания выплат на карту физ. лицам
15+
**/
16+
17+
// Созданим выплату
18+
$payout = new Payout();
19+
20+
// Назначим ей уникальный номер выплаты
21+
// (повторно этот номер использовать нельзя,
22+
// даже если выплата неудачная
23+
$payout->setMerchantPayoutReference('payout__' . time());
24+
25+
// Назначим сумму
26+
$payout->setAmount(
27+
new Amount(15, 'RUB')
28+
);
29+
30+
// Назначим Описание
31+
$payout->setDescription('Тестовое Описание Платежа');
32+
33+
// Опишем и назначим Направление и Получателя платежа
34+
$destination = new PayoutDestination();
35+
// Назначим номер карты
36+
$destination->setCardNumber("4111111111111111");
37+
// Опишем получателя
38+
$recipient = new Billing();
39+
// E-mail получателя
40+
$recipient->setEmail('[email protected]');
41+
// Город получателя
42+
$recipient->setCity('Москва');
43+
// Адрес получателя
44+
$recipient->setAddressLine1('Арбат, 10');
45+
// Почтовый индекс получателя
46+
$recipient->setZipCode('121000');
47+
// Код страны получателя (2 буквы, на английском)
48+
$recipient->setCountryCode('RU');
49+
50+
// Имя получателя из GET-запроса
51+
$postRecipientName = explode(' ', @$_POST['reciever-name'] ?: '');
52+
// Установим Имя получателя для платежа
53+
$recipient->setFirstName(@$postRecipientName[0] ?: 'Иван');
54+
// Фамилия получателя
55+
$recipient->setLastName(@$postRecipientName[1] ?: @$postRecipientName[0] ?: 'Иванович');
56+
$destination->setRecipient($recipient);
57+
$payout->setDestination($destination);
58+
59+
// Опишем и назначим Источник платежа
60+
$source = new PayoutSource();
61+
// Опишем отправителя
62+
$sender = new Billing();
63+
// Имя отправителя
64+
$sender->setFirstName('Василий');
65+
// Фамилия отправителя
66+
$sender->setLastName('Петрович');
67+
// Телефон отправителя
68+
$sender->setPhone('0764111111');
69+
// Email отправителя
70+
$sender->setEmail('[email protected]');;
71+
$source->setSender($sender);
72+
$payout->setSource($source);
73+
74+
// Создадим HTTP-запрос к API
75+
$apiRequest = new ApiRequest($merchant);
76+
// Включить режим отладки (закомментируйте или удалите в рабочей программе!)
77+
$apiRequest->setDebugMode();
78+
// Переключиться на тестовый сервер (закомментируйте или удалите в рабочей программе!)
79+
$apiRequest->setSandboxMode();
80+
// Отправим запрос
81+
$responseData = $apiRequest->sendPayoutCreateRequest($payout);

0 commit comments

Comments
 (0)