· 4 years ago · Jan 19, 2021, 08:06 PM
1<?php
2
3class UnitPay
4{
5 private $event;
6
7 public function __construct(UnitPayEvent $event)
8 {
9 $this->event = $event;
10 }
11
12 public function getResult()
13 {
14 $request = $_GET;
15
16 if (empty($request['method'])
17 || empty($request['params'])
18 || !is_array($request['params'])
19 )
20 {
21 return $this->getResponseError('Invalid request');
22 }
23
24 $method = $request['method'];
25 $params = $request['params'];
26
27 if ($params['signature'] != $this->getSha256SignatureByMethodAndParams($method, $params, Config::SECRET_KEY))
28 {
29 return $this->getResponseError('Incorrect digital signature');
30 }
31
32 $unitPayModel = UnitPayModel::getInstance();
33
34 if ($method == 'check')
35 {
36 if ($unitPayModel->getPaymentByUnitpayId($params['unitpayId']))
37 {
38 // Платеж уже существует
39 return $this->getResponseSuccess('Payment already exists');
40 }
41
42 $itemsCount = floor($params['sum'] / Config::ITEM_PRICE);
43
44 if ($itemsCount <= 0)
45 {
46 return $this->getResponseError('Суммы ' . $params['sum'] . ' руб. не достаточно для оплаты товара ' .
47 'стоимостью ' . Config::ITEM_PRICE . ' руб.');
48 }
49
50 if (!$unitPayModel->createPayment(
51 $params['unitpayId'],
52 $params['account'],
53 $params['sum'],
54 $itemsCount
55 ))
56 {
57 return $this->getResponseError('Unable to create payment database');
58 }
59
60 $checkResult = $this->event->check($params);
61 if ($checkResult !== true)
62 {
63 return $this->getResponseError($checkResult);
64 }
65
66 return $this->getResponseSuccess('CHECK is successful');
67 }
68
69 if ($method == 'pay')
70 {
71 $payment = $unitPayModel->getPaymentByUnitpayId(
72 $params['unitpayId']
73 );
74
75 if ($payment && $payment->status == 1)
76 {
77 return $this->getResponseSuccess('Payment has already been paid');
78 }
79
80 if (!$unitPayModel->confirmPaymentByUnitpayId($params['unitpayId']))
81 {
82 return $this->getResponseError('Unable to confirm payment database');
83 }
84
85 $this->event
86 ->pay($params);
87
88 return $this->getResponseSuccess('PAY is successful');
89 }
90
91 return $this->getResponseError($method.' not supported');
92 }
93
94 private function getResponseSuccess($message)
95 {
96 return json_encode(
97 array(
98 'result' => array(
99 'message' => $message
100 )
101 )
102 );
103 }
104
105 private function getResponseError($message)
106 {
107 return json_encode(
108 array(
109 'error' => array(
110 'message' => $message
111 )
112 )
113 );
114 }
115
116 /**
117 * @param $method
118 * @param array $params
119 * @param $secretKey
120 *
121 * @return string
122 */
123 private function getSha256SignatureByMethodAndParams($method, array $params, $secretKey)
124 {
125 ksort($params);
126 unset($params['sign']);
127 unset($params['signature']);
128 array_push($params, $secretKey);
129 array_unshift($params, $method);
130
131 return hash('sha256', join('{up}', $params));
132 }
133}