diff --git a/config.php b/config.php index 044e359..3882ed0 100644 --- a/config.php +++ b/config.php @@ -6,24 +6,26 @@ class Config const SECRET_KEY = ''; // Стоимость товара в руб. const ITEM_PRICE = 10; + // Разрешать записывать тестовые платежи в БД + const ALLOW_TEST_PAYMENTS = false; // Таблица начисления товара, например `users` const TABLE_ACCOUNT = ''; // Название поля из таблицы начисления товара по которому производится поиск аккаунта/счета, например `email` const TABLE_ACCOUNT_NAME = ''; - // Название поля из таблицы начисления товара которое будет увеличено на колличево оплаченого товара, например `sum`, `donate` + // Название поля из таблицы начисления товара которое будет увеличено на количество оплаченого товара, например `sum`, `donate` const TABLE_ACCOUNT_DONATE= ''; - // Параметры соединения с бд + // Параметры соединения с БД // Хост const DB_HOST = 'localhost'; // Имя пользователя const DB_USER = 'homestead'; // Пароль const DB_PASS = 'secret'; - // Назывние базы + // Название базы const DB_NAME = 'base_modul'; - // номер порта(необязательно) + // Номер порта (необязательно) const DB_PORT = ''; } \ No newline at end of file diff --git a/index.php b/index.php index 577adb6..572c46a 100644 --- a/index.php +++ b/index.php @@ -17,7 +17,7 @@ public function check($params) return true; } return 'Character not found'; - }catch(Exception $e){ + } catch(Exception $e) { return $e->getMessage(); } } diff --git a/lib/UnitPay.php b/lib/UnitPay.php index 2ad56a5..ce927ee 100644 --- a/lib/UnitPay.php +++ b/lib/UnitPay.php @@ -4,9 +4,16 @@ class UnitPay { private $event; + /** @var UnitPayModel */ + private $unitPayModel; + + /** @var array */ + private $params; + public function __construct(UnitPayEvent $event) { $this->event = $event; + $this->unitPayModel = UnitPayModel::getInstance(); } public function getResult() @@ -22,73 +29,74 @@ public function getResult() } $method = $request['method']; - $params = $request['params']; - - if ($params['signature'] != $this->getSha256SignatureByMethodAndParams($method, $params, Config::SECRET_KEY)) - { + $this->params = $request['params']; + if ($this->params['signature'] != $this->getSha256SignatureByMethodAndParams($method, $this->params, Config::SECRET_KEY)) { return $this->getResponseError('Incorrect digital signature'); } - $unitPayModel = UnitPayModel::getInstance(); + switch ($method) { + case 'check': + return $this->doCheck(); + case 'pay': + return $this->doPay(); + default: + return $this->getResponseError($method . ' is not supported'); + } + } - if ($method == 'check') - { - if ($unitPayModel->getPaymentByUnitpayId($params['unitpayId'])) - { - // Платеж уже существует - return $this->getResponseSuccess('Payment already exists'); - } - - $itemsCount = floor($params['sum'] / Config::ITEM_PRICE); - - if ($itemsCount <= 0) - { - return $this->getResponseError('Суммы ' . $params['sum'] . ' руб. не достаточно для оплаты товара ' . - 'стоимостью ' . Config::ITEM_PRICE . ' руб.'); - } - - if (!$unitPayModel->createPayment( - $params['unitpayId'], - $params['account'], - $params['sum'], - $itemsCount - )) - { - return $this->getResponseError('Unable to create payment database'); - } - - $checkResult = $this->event->check($params); - if ($checkResult !== true) - { - return $this->getResponseError($checkResult); - } - - return $this->getResponseSuccess('CHECK is successful'); + private function doCheck() + { + if ($record = $this->unitPayModel->getPaymentByUnitpayId($this->params['unitpayId'])) { + return $this->createResponseForPayment($record); } - if ($method == 'pay') - { - $payment = $unitPayModel->getPaymentByUnitpayId( - $params['unitpayId'] - ); + $itemsCount = floor($this->params['sum'] / Config::ITEM_PRICE); + + if ($itemsCount <= 0) { + return $this->getResponseError('Суммы ' . $this->params['sum'] . ' руб. не достаточно для оплаты товара ' . + 'стоимостью ' . Config::ITEM_PRICE . ' руб.'); + } + + if ($this->params['test'] == '1' && !Config::ALLOW_TEST_PAYMENTS) { + return $this->getResponseSuccess('Test payment received successfully'); + } + + if (!$this->unitPayModel->createPayment( + $this->params['unitpayId'], + $this->params['account'], + $this->params['sum'], + $itemsCount + )) { + return $this->getResponseError('Unable to create payment database'); + } + + $checkResult = $this->event->check($this->params); + if ($checkResult !== true) { + return $this->getResponseError($checkResult); + } + + return $this->createResponseForPayment($this->unitPayModel->getPaymentByUnitpayId($this->params['unitpayId'])); + } - if ($payment && $payment->status == 1) - { - return $this->getResponseSuccess('Payment has already been paid'); - } + private function doPay() + { + $payment = $this->unitPayModel->getPaymentByUnitpayId($this->params['unitpayId']); - if (!$unitPayModel->confirmPaymentByUnitpayId($params['unitpayId'])) - { - return $this->getResponseError('Unable to confirm payment database'); - } + if ($payment && $payment->status == 1) { + return $this->getResponseSuccess('Payment has already been paid'); + } - $this->event - ->pay($params); + if ($this->params['test'] == '1' && !Config::ALLOW_TEST_PAYMENTS) { + return $this->getResponseSuccess('Test payment received successfully'); + } - return $this->getResponseSuccess('PAY is successful'); + if (!$this->unitPayModel->confirmPaymentByUnitpayId($this->params['unitpayId'])) { + return $this->getResponseError('Unable to confirm payment database'); } - return $this->getResponseError($method.' not supported'); + $this->event->pay($this->params); + + return $this->getResponseSuccess('PAY is successful'); } private function getResponseSuccess($message) @@ -114,11 +122,23 @@ private function getResponseError($message) )); } - private function getMd5Sign($params, $secretKey) + + private function createResponseForPayment($payment) { - ksort($params); - unset($params['sign']); - return md5(join(null, $params).$secretKey); + return json_encode(array( + "jsonrpc" => "2.0", + "result" => array( + 'message' => 'CHECK is successful', + 'createdAt' => $payment->dateCreate, + 'completedAt' => $payment->dateComplete, + 'unitpayId' => $payment->unitpayId, + 'account' => $payment->account, + 'sum' => $payment->sum, + 'itemsCount' => $payment->itemsCount, + 'status' => $payment->status ? 'complete' : 'incomplete' + ), + 'id' => 1, + )); } /** diff --git a/lib/UnitPayModel.php b/lib/UnitPayModel.php index 9bab835..60a3348 100644 --- a/lib/UnitPayModel.php +++ b/lib/UnitPayModel.php @@ -24,7 +24,14 @@ private function __construct() } } - function createPayment($unitpayId, $account, $sum, $itemsCount) + /** + * @param int $unitpayId + * @param string $account + * @param int|float|string $sum + * @param int $itemsCount + * @return bool|mysqli_result + */ + public function createPayment($unitpayId, $account, $sum, $itemsCount) { $query = ' INSERT INTO @@ -43,7 +50,12 @@ function createPayment($unitpayId, $account, $sum, $itemsCount) return $this->mysqli->query($query); } - function getPaymentByUnitpayId($unitpayId) + /** + * @param int $unitpayId + * @return object|stdClass + * @throws Exception + */ + public function getPaymentByUnitpayId($unitpayId) { $query = ' SELECT * FROM @@ -62,7 +74,11 @@ function getPaymentByUnitpayId($unitpayId) return $result->fetch_object(); } - function confirmPaymentByUnitpayId($unitpayId) + /** + * @param int|string $unitpayId + * @return bool|mysqli_result + */ + public function confirmPaymentByUnitpayId($unitpayId) { $query = ' UPDATE @@ -77,7 +93,7 @@ function confirmPaymentByUnitpayId($unitpayId) return $this->mysqli->query($query); } - function getAccountByName($account) + public function getAccountByName($account) { $sql = " SELECT @@ -98,9 +114,15 @@ function getAccountByName($account) return $result->fetch_object(); } - - function donateForAccount($account, $count) + + /** + * @param string $account + * @param int $count + * @return bool|mysqli_result + */ + public function donateForAccount($account, $count) { + $query = " UPDATE ".Config::TABLE_ACCOUNT."