Skip to content

Commit 6201c7a

Browse files
committed
Merge branch 'YP-1173' into 'main'
YP-1173 Add: Widget. See merge request ypmn-public/php-api-client!3
2 parents 6711b23 + 9055eb6 commit 6201c7a

File tree

3 files changed

+189
-0
lines changed

3 files changed

+189
-0
lines changed

example_list.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,4 +178,10 @@
178178
'docLink' => 'https://ypmn.ru/ru/documentation/#tag/qst-api/paths/~1v4~1qst~1list/get',
179179
'link' => '',
180180
],
181+
'getWidget' => [
182+
'name' => 'Получение виджета',
183+
'about' => 'В этом примере показано получение виджета.',
184+
'docLink' => 'https://ypmn.ru/ru/documentation/#tag/widget-integration',
185+
'link' => '',
186+
],
181187
];

src/Examples/getWidget.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Ypmn\Widget;
6+
7+
// Подключим файл, в котором заданы параметры мерчанта
8+
include_once 'start.php';
9+
10+
// Многократно используемые параметры виджета
11+
define("LABEL", "Купить в один клик");
12+
define("CLASSES", "button pay_button");
13+
14+
// Создадим экземпляр класса виджета.
15+
$widget = new Widget($merchant->getCode(), "RU", "RUB");
16+
?>
17+
18+
<!DOCTYPE html>
19+
<html lang="ru">
20+
<head>
21+
<meta charset="UTF-8">
22+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
23+
<title>Виджет YPMN</title>
24+
</head>
25+
<body>
26+
<h1>Пример работы виджета</h1>
27+
28+
<p>Полное описание товарной позиции номер один</p>
29+
<p><span>Товар номер один</span> - <?php
30+
// Выводим кнопку покупки на 199.99 рублей.
31+
echo $widget->makeBuyButton(199.99, "RUB", LABEL, CLASSES);
32+
?></p>
33+
34+
<p>Полное описание товарной позиции номер два</p>
35+
<p><span>Товар номер два</span> - <?php
36+
// Выводим кнопку покупки на 299.99 рублей.
37+
echo $widget->makeBuyButton(299.99, "RUB", LABEL, CLASSES);
38+
?></p>
39+
40+
<p>Полное описание товарной позиции номер три</p>
41+
<p><span>Товар номер три</span> - <?php
42+
// Выводим кнопку покупки на 399.99 рублей.
43+
echo $widget->makeBuyButton(399.99, "RUB", LABEL, CLASSES);
44+
?></p>
45+
46+
<?php echo $widget->makeBuyForm(); ?>
47+
</body>
48+
</html>

src/Widget.php

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Ypmn;
6+
7+
/**
8+
* Класс для работы с виджетом.
9+
*/
10+
final class Widget
11+
{
12+
// Код мерчанта.
13+
public string $merchantCode;
14+
// Код страны.
15+
public string $countryCode;
16+
// Имя.
17+
public string $firstName;
18+
// Фамилия.
19+
public string $lastName;
20+
// Email.
21+
public string $email;
22+
// Телефон.
23+
public string $phone;
24+
// Ссылка возврата.
25+
public string $returnUrl;
26+
27+
/**
28+
* @param string $merchantCode Код мерчанта.
29+
* @param string $countryCode Код страны.
30+
* @param string $firstName Имя.
31+
* @param string $lastName Фамилия.
32+
* @param string $email Email.
33+
* @param string $phone Телефон.
34+
* @param string $returnUrl Ссылка возврата.
35+
*/
36+
public function __construct(
37+
string $merchantCode,
38+
string $countryCode = "RU",
39+
string $firstName = "Not",
40+
string $lastName = "Set",
41+
string $email = "[email protected]",
42+
string $phone = "9990000000",
43+
string $returnUrl = "https://ya.ru/"
44+
) {
45+
$this->merchantCode = $merchantCode;
46+
$this->countryCode = $countryCode;
47+
$this->firstName = $firstName;
48+
$this->lastName = $lastName;
49+
$this->email = $email;
50+
$this->phone = $phone;
51+
$this->returnUrl = $returnUrl;
52+
}
53+
54+
/**
55+
* Метод возвращает кнопку покупки.
56+
*
57+
* @param float $amounts Сумма к оплате.
58+
* @param string $currency Валюта.
59+
* @param string $label Надпись на кнопке.
60+
* @param string $classes Классы кнопки.
61+
*
62+
* @return string
63+
*/
64+
public function makeBuyButton(
65+
float $amount,
66+
string $currency = "RUB",
67+
string $label = "Купить",
68+
string $classes = ""
69+
): string {
70+
$classes = trim("buyBtn " . $classes);
71+
$params = "data-amount='{$amount}' data-currency='{$currency}'";
72+
73+
return "<a href='#' class='{$classes}' {$params}>{$label}</a>";
74+
}
75+
76+
/**
77+
* Метод возвращает скрипты для вставки в html.
78+
*
79+
* @return string
80+
*/
81+
public function makeBuyForm(): string
82+
{
83+
return "<script src='https://secure.ypmn.ru/pay/widget/v1/js/YPMNFrames.js'></script>
84+
<script src='https://secure.ypmn.ru/assets/js/crypto-js/4.2.0/crypto-js.min.js'></script>
85+
<script>
86+
window.document.body.onload = function() {
87+
const payButtons = document.getElementsByClassName('buyBtn');
88+
for (let payButton of payButtons) {
89+
payButton.addEventListener('click', async () => {
90+
const ypmn = new YPMNFrames(
91+
{
92+
merchantCode: '{$this->merchantCode}',
93+
countryCode: '{$this->countryCode}',
94+
currency: payButton.getAttribute('data-currency'),
95+
merchantPaymentReference: '{$this->merchantCode}' + Math.floor(Math.random() * 1000) + Date.now(),
96+
firstName: '{$this->firstName}',
97+
lastName: '{$this->lastName}',
98+
email: '{$this->email}',
99+
phone: '{$this->phone}',
100+
paymentSum: payButton.getAttribute('data-amount'),
101+
returnUrl: '{$this->returnUrl}',
102+
paymentMethod: 'CCVISAMC',
103+
signature: '',
104+
},
105+
document.body.clientWidth,
106+
Math.max(document.body.scrollHeight, window.screen.availHeight)
107+
);
108+
// Подписываем параметры
109+
ypmn.data.payment.signature = doSigned(ypmn.data.payment);
110+
ypmn.start();
111+
});
112+
}
113+
};
114+
if (window.location.hash === '#close') {
115+
window.top.postMessage('SIGHUP', '*');
116+
}
117+
window.addEventListener('hashchange', (event) => {
118+
if (window.location.hash === '#close') {
119+
window.top.postMessage('SIGHUP', '*');
120+
}
121+
});
122+
function doSigned(params) {
123+
let raw = '';
124+
125+
Object.keys(params).forEach(k => {
126+
if (k !== 'returnUrl' && k !== 'signature') {
127+
raw += params[k];
128+
}
129+
});
130+
131+
return CryptoJS.SHA256(raw).toString();
132+
}
133+
</script>";
134+
}
135+
}

0 commit comments

Comments
 (0)