Skip to content

Commit 0bee941

Browse files
author
Alexey Babak
committed
kopeiki prices fix
1 parent e1b772c commit 0bee941

File tree

7 files changed

+81
-43
lines changed

7 files changed

+81
-43
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"type": "package",
55
"keywords": ["payments", "processing"],
66
"require": {
7-
"php": ">=7.4.0",
7+
"php": ">=8.1.0",
88
"ext-json": "*",
99
"ext-curl": "*",
1010
"ext-mbstring": "*"

example.php

Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@
4242
$orderAsProduct = new Product([
4343
'name' => 'Заказ №' . $merchantPaymentReference,
4444
'sku' => $merchantPaymentReference,
45-
'unitPrice' => '1600',
46-
'quantity' => '1'
45+
'unitPrice' => '1.42',
46+
'quantity' => '2',
4747
]);
4848

4949
// Опишем Биллинговую (платёжную) информацию
@@ -90,18 +90,28 @@
9090
// Отправим запрос
9191
$responseData = $apiRequest->sendAuthRequest($payment, $merchant);
9292
// Преобразуем ответ из JSON в массив
93-
$responseData = json_decode((string) $responseData["response"], true);
94-
// Нарисуем кнопку оплаты
95-
echo '<a
96-
href="'.$responseData["paymentResult"]['url'].'"
97-
class="btn btn-success"
98-
target="_b"
99-
style="font-weight: bolder; color: green;"
100-
rel="noindex noopener">
101-
Оплата PayU
102-
</a>';
103-
// .. или сделаем редирект на форму оплаты (опционально)
104-
// header("Location: " . $responseData["paymentResult"]['url']);
93+
try {
94+
$responseData = json_decode((string) $responseData["response"], true);
95+
96+
// Нарисуем кнопку оплаты
97+
echo Std::drawPayuButton([
98+
'url' => $responseData["paymentResult"]['url'],
99+
'sum' => $payment->sumProductsAmount(),
100+
]);
101+
102+
// .. или сделаем редирект на форму оплаты (опционально)
103+
// Std::redirect($responseData["paymentResult"]['url']);
104+
} catch (Exception $exception) {
105+
//TODO: обработка исключения
106+
echo Std::alert([
107+
'text' => '
108+
Извините, платёжный метода временно недоступен.<br>
109+
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
110+
<br>
111+
<pre>' . $exception->getMessage() . '</pre>',
112+
'type' => 'danger',
113+
]);
114+
}
105115
break;
106116
case 'getPaymentLink':
107117
// Оплата по ссылке PayU
@@ -217,14 +227,28 @@ class="btn btn-success"
217227
// Отправим запрос
218228
$responseData = $apiRequest->sendAuthRequest($payment, $merchant);
219229
// Преобразуем ответ из JSON в массив
220-
$responseData = json_decode((string) $responseData["response"], true);
221-
// Нарисуем кнопку оплаты
222-
echo Std::drawPayuButton([
223-
'url' => $responseData["paymentResult"]['url'],
224-
'sum' => $payment->sumProductsAmount(),
225-
]);
226-
// Либо сделаем редирект (перенаправление) браузера по адресу оплаты:
227-
// echo Std::redirect($responseData["paymentResult"]['url']);
230+
try {
231+
$responseData = json_decode((string) $responseData["response"], true);
232+
233+
// Нарисуем кнопку оплаты
234+
echo Std::drawPayuButton([
235+
'url' => $responseData["paymentResult"]['url'],
236+
'sum' => $payment->sumProductsAmount(),
237+
]);
238+
239+
// Либо сделаем редирект (перенаправление) браузера по адресу оплаты:
240+
// echo Std::redirect($responseData["paymentResult"]['url']);
241+
} catch (Exception $exception) {
242+
//TODO: обработка исключения
243+
echo Std::alert([
244+
'text' => '
245+
<strong>Извините, платёжный метода временно недоступен.</strong><br>
246+
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
247+
<br>
248+
<pre>' . $exception->getMessage() . '</pre>',
249+
'type' => 'danger',
250+
]);
251+
}
228252
break;
229253

230254
case 'paymentCapture':

src/Payment.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ public function getProductsArray(): array
125125
}
126126

127127
/** @inheritdoc */
128-
public function sumProductsAmount() : int
128+
public function sumProductsAmount() : float
129129
{
130130
$sum = 0;
131131
foreach ($this->getProducts() as $product) {

src/PaymentInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ public function getProductsArray() : array;
105105
* @return int Итог
106106
* @throws PaymentException Ошибка оплаты
107107
*/
108-
public function sumProductsAmount() : int;
108+
public function sumProductsAmount() : float;
109109

110110
/**
111111
* @return string|bool

src/Product.php

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ class Product implements ProductInterface
1919
private string $sku;
2020

2121
/**
22-
* @var int Цена за 1 штуку
22+
* @var float Цена за 1 штуку
2323
*/
24-
private int $unitPrice;
24+
private float $unitPrice;
2525

2626
/**
2727
* @var int Количество
@@ -34,9 +34,9 @@ class Product implements ProductInterface
3434
private int $vat = 20;
3535

3636
/**
37-
* @var int Подитог
37+
* @var float Подитог
3838
*/
39-
private int $amount;
39+
private float $amount;
4040

4141
/**
4242
* @var string Любые доп. сведения
@@ -73,7 +73,7 @@ public function getName(): string
7373
}
7474

7575
/** @inheritDoc */
76-
public function setName(string $name): Product
76+
public function setName(string $name): self
7777
{
7878
$this->name = $name;
7979
return $this;
@@ -86,7 +86,7 @@ public function getSku(): string
8686
}
8787

8888
/** @inheritDoc */
89-
public function setSku(string $sku): Product
89+
public function setSku(string $sku): self
9090
{
9191
$this->sku = $sku;
9292
return $this;
@@ -99,9 +99,9 @@ public function getUnitPrice(): float
9999
}
100100

101101
/** @inheritDoc */
102-
public function setUnitPrice(float $unitPrice): Product
102+
public function setUnitPrice(float $unitPrice): self
103103
{
104-
$this->unitPrice = $unitPrice;
104+
$this->unitPrice = round($unitPrice, 2, PHP_ROUND_HALF_UP);
105105
return $this;
106106
}
107107

@@ -112,7 +112,7 @@ public function getQuantity(): int
112112
}
113113

114114
/** @inheritDoc */
115-
public function setQuantity(int $quantity): Product
115+
public function setQuantity(int $quantity): self
116116
{
117117
$this->quantity = $quantity;
118118
return $this;
@@ -125,7 +125,7 @@ public function getVat(): int
125125
}
126126

127127
/** @inheritDoc */
128-
public function setVat(int $vat): Product
128+
public function setVat(int $vat): self
129129
{
130130
$this->vat = $vat;
131131
return $this;
@@ -138,10 +138,10 @@ public function getAmount(): ?float
138138
}
139139

140140
/** @inheritDoc */
141-
public function setAmount(float $amount): Product
141+
public function setAmount(float $amount): self
142142
{
143143
//TODO: ВАЖНО: не должно превышать оригинальную стоимость (unitPrice * quantity) продукта при авторизации
144-
$this->amount = $amount;
144+
$this->amount = round($amount, 2, PHP_ROUND_HALF_UP);
145145
return $this;
146146
}
147147

@@ -152,7 +152,7 @@ public function getAdditionalDetails(): ?string
152152
}
153153

154154
/** @inheritDoc */
155-
public function setAdditionalDetails(string $additionalDetails): Product
155+
public function setAdditionalDetails(string $additionalDetails): self
156156
{
157157
$this->additionalDetails = $additionalDetails;
158158
return $this;
@@ -164,10 +164,10 @@ public function arraySerialize(): array
164164
return [
165165
'name' => $this->getName(),
166166
'sku' => $this->getSku(),
167-
'unitPrice' => $this->getUnitPrice(),
167+
'unitPrice' => number_format($this->getUnitPrice(), 2),
168168
'quantity' => $this->getQuantity(),
169169
'additionalDetails' => $this->getAdditionalDetails(),
170-
'amount' => $this->getAmount(),
170+
'amount' => (null !== $this->getAmount() ? number_format($this->getAmount(), 2) : null),
171171
'vat' => $this->getVat(),
172172
];
173173
}

src/ProductInterface.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public function setSku(string $sku) : self;
3737
public function getSku() : string;
3838

3939
/**
40-
* Установить Цена за 1 штуку
40+
* Установить Цена за 1 штуку, округление до копейки
4141
* @param float $unitPrice
4242
* @return $this Цена за 1 штуку
4343
*/
@@ -108,4 +108,4 @@ public function getAdditionalDetails() : ?string;
108108
* @return array Продукт в виде массива
109109
*/
110110
public function arraySerialize(): array;
111-
}
111+
}

src/Std.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ public static function redirect(string $url)
2121
exit();
2222
}
2323

24+
/**
25+
* @param array $params
26+
* @return string
27+
*/
28+
public static function alert(array $params)
29+
{
30+
return '
31+
<div class="alert alert-' . ($params['type'] ?? 'info') . '" role="alert">
32+
' . $params['text'] . '
33+
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
34+
</div>
35+
';
36+
}
37+
2438
/**
2539
* Удалить null-значения из массива
2640
* @param array $array
@@ -100,7 +114,7 @@ public static function drawPayuButton(array $params): string
100114
/>
101115
Оплатить
102116
'.(isset($params['sum']) ? '<br><strong>'
103-
. number_format($params['sum'], 0, '.', ' ')
117+
. number_format($params['sum'], 2, '.', ' ')
104118
. ' '
105119
. ( isset($params['currency']) ? htmlspecialchars($params['currency']) : '' ) .'</strong>' : '').'
106120
</a>

0 commit comments

Comments
 (0)