Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test payments support #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';

}
2 changes: 1 addition & 1 deletion index.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function check($params)
return true;
}
return 'Character not found';
}catch(Exception $e){
} catch(Exception $e) {
return $e->getMessage();
}
}
Expand Down
138 changes: 79 additions & 59 deletions lib/UnitPay.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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,
));
}

/**
Expand Down
34 changes: 28 additions & 6 deletions lib/UnitPayModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -77,7 +93,7 @@ function confirmPaymentByUnitpayId($unitpayId)
return $this->mysqli->query($query);
}

function getAccountByName($account)
public function getAccountByName($account)
{
$sql = "
SELECT
Expand All @@ -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."
Expand Down