Skip to content

Commit

Permalink
Simpla 2.3.8
Browse files Browse the repository at this point in the history
Новые платежные модули: Альфа-Банк, Промсвязьбанк, РФИ банк,
MandarinBank, Assist, ChronoPay, NetPay, Paysera, Uniteller
  • Loading branch information
pikusov committed Apr 24, 2017
1 parent fb717b4 commit 9fefafa
Show file tree
Hide file tree
Showing 35 changed files with 3,881 additions and 2 deletions.
4 changes: 2 additions & 2 deletions api/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* В отличие от класса Settings, Config оперирует низкоуровневыми настройками, например найстройками базы данных.
*
*
* @copyright 2014 Denis Pikusov
* @copyright 2017 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
Expand All @@ -15,7 +15,7 @@

class Config
{
public $version = '2.3.7';
public $version = '2.3.8';

// Файл для хранения настроек
public $config_file = 'config/config.php';
Expand Down
91 changes: 91 additions & 0 deletions payment/Alfabank/Alfabank.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

/**
* Simpla CMS
*
* @copyright 2017 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* Платежный шлюз для Альфа-Банка
*
*/

require_once('api/Simpla.php');

class Alfabank extends Simpla
{
public $getaway_url = 'https://test.paymentgate.ru/testpayment/rest/';

public function checkout_form($order_id, $button_text = null)
{
if($this->request->method('post') && $this->request->post('go'))
{
$this->redirect($order_id);
}
else
{
$button = "<form method=POST>".
"<input name=go type=submit class=checkout_button
value='Перейти к оплате &#8594;'>".
"</form>";
return $button;
}
}

public function redirect($order_id)
{
$order = $this->orders->get_order((int)$order_id);
$payment_method = $this->payment->get_payment_method($order->payment_method_id);
$payment_settings = $this->payment->get_payment_settings($payment_method->id);
if(!empty($payment_settings['alfabank_server']))
$this->getaway_url = $payment_settings['alfabank_server'];
$price = $this->money->convert($order->total_price, $payment_method->currency_id, false);
$return_url = $this->config->root_url.'/payment/Alfabank/callback.php?o='.$order->id;

$data = array(
'userName' => $payment_settings['alfabank_login'],
'password' => $payment_settings['alfabank_password'],
'orderNumber' => $order->id,
'amount' => $price*100,
'returnUrl' => $return_url
);

$response = $this->gateway('register.do', $data);
if ($response['errorCode'] != 0)
{
print($response['errorMessage']);
}
else
{
print "REDIRECT";
header('Location: '.$response['formUrl']);
exit;
}

return $button;
}


public function gateway($method, $data)
{
$curl = curl_init(); // Инициализируем запрос
curl_setopt_array($curl, array(
CURLOPT_URL => $this->getaway_url.$method,
CURLOPT_RETURNTRANSFER => true, // Возвращать ответ
CURLOPT_POST => true, // Метод POST
CURLOPT_POSTFIELDS => http_build_query($data) // Данные в запросе
));

$response = curl_exec($curl); // Выполненяем запрос
$response = json_decode($response, true); // Декодируем из JSON в массив
$err = curl_error($curl);
if($err)
{
print $err;
}
curl_close($curl); // Закрываем соединение
return $response; // Возвращаем ответ
}

}
73 changes: 73 additions & 0 deletions payment/Alfabank/callback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

/**
* Simpla CMS
*
* @copyright 2017 Denis Pikusov
* @link http://simplacms.ru
* @author Denis Pikusov
*
* К этому скрипту обращается Альфа-Банк в процессе оплаты
*
*/

// Работаем в корневой директории
chdir ('../../');
require_once('payment/Alfabank/Alfabank.php');
$alfa = new Alfabank();

$external_order_id = $_GET['orderId'];
$order_id = intval($_GET['o']);

$order = $alfa->orders->get_order(intval($order_id));
if(empty($order))
errorlink('Оплачиваемый заказ не найден');

// Нельзя оплатить уже оплаченный заказ
if($order->paid)
errorlink('Этот заказ уже оплачен');

$method = $alfa->payment->get_payment_method(intval($order->payment_method_id));
if(empty($method))
errorlink("Неизвестный метод оплаты");

$settings = unserialize($method->settings);
if(!empty($settings['alfabank_server']))
$alfa->getaway_url = $settings['alfabank_server'];


$data = array(
'userName' => $settings['alfabank_login'],
'password' => $settings['alfabank_password'],
'orderId' => $external_order_id
);

$response = $alfa->gateway('getOrderStatus.do', $data);

if ($response['ErrorCode'] !== 0)
{
errorlink($response['ErrorMessage']);
}

if($response['Amount'] != 100*$alfa->money->convert($order->total_price, $method->currency_id, false) || $response['Amount']<=0)
errorlink("incorrect price\n");

if($response['OrderNumber'] != $order->id)
errorlink("incorrect order number\n");

// Установим статус оплачен
$alfa->orders->update_order(intval($order->id), array('paid'=>1));

// Спишем товары
$alfa->orders->close(intval($order->id));
$alfa->notify->email_order_user(intval($order->id));
$alfa->notify->email_order_admin(intval($order->id));

header("Location: ".$alfa->config->root_url.'/order/'.$order->url);

function errorlink($message)
{
print "$message<br>";
print "<a href='".$alfa->config->root_url."/order/".$order->url."'>Вернуться на страницу заказа</a>";
die();
}
19 changes: 19 additions & 0 deletions payment/Alfabank/settings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<module>
<name>
Альфа-Банк
</name>
<settings>
<variable>alfabank_login</variable>
<name>Логин от API</name>
</settings>
<settings>
<variable>alfabank_password</variable>
<name>Пароль от API</name>
</settings>
<settings>
<variable>alfabank_server</variable>
<name>Адрес сервера</name>
<default>https://test.paymentgate.ru/testpayment/rest/</default>
</settings>
</module>
58 changes: 58 additions & 0 deletions payment/Assist/Assist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

require_once('api/Simpla.php');

class Assist extends Simpla
{
public function checkout_form($order_id, $button_text = null)
{
if(empty($button_text))
$button_text = 'Перейти к оплате';

$order = $this->orders->get_order((int)$order_id);
$payment_method = $this->payment->get_payment_method($order->payment_method_id);
$payment_currency = $this->money->get_currency(intval($payment_method->currency_id));
$settings = $this->payment->get_payment_settings($payment_method->id);

$price = round($this->money->convert($order->total_price, $payment_method->currency_id, false), 2);

// описание заказа
// order description

$return_url = $this->config->root_url.'/order/'.$order->url;

$hashcode = strtoupper(md5(strtoupper(md5( $settings['assist_key'] ).md5( $settings['assist_merchant_id'] . $order->id . $order->total_price . str_replace("RUR", "RUB", $payment_currency->code)))));


$fio_arr = explode(" ", $order->name);
$firstname = $fio_arr[0];
$lastname = $fio_arr[1];

if (trim($firstname) == "") {
$firstname = "---";
}
if (trim($lastname) == "") {
$lastname = "---";
}


$button = '<form action="'.$settings['assist_url'].'" method="POST"/>'.
'<input type="hidden" name="Merchant_ID" value="'.$settings['assist_merchant_id'].'" />'.
'<input type="hidden" name="OrderNumber" value="'.$order->id.'" />'.
'<input type="hidden" name="OrderAmount" value="'.$order->total_price.'" />'.
'<input type="hidden" name="url" value="'.$return_url.'" />'.
'<input type="hidden" name="CheckValue" value="'.$hashcode.'" />'.
'<input type="hidden" name="OrderCurrency" value="'.str_replace("RUR", "RUB", $payment_currency->code).'" />'.
'<input type="hidden" name="LastName" value="'.$lastname.'" />'.
'<input type="hidden" name="FirstName" value="'.$firstname.'" />'.
'<input type="hidden" name="Language" value="RU" />'.
'<input type="hidden" name="URL_RETURN_OK" value="'.$return_url.'" />'.
'<input type="hidden" name="URL_RETURN_NO" value="'.$return_url.'" />'.
'<input type="hidden" name="Email" value="'.$order->email.'" />'.
'<input type="hidden" name="MobilePhone" value="'.$order->phone.'" />'.
'<input type="hidden" name="OrderComment" value="'.$order->comment.'" />'.
'<input type=submit class=checkout_button value="'.$button_text.'">'.
'</form>';
return $button;
}
}
71 changes: 71 additions & 0 deletions payment/Assist/callback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

// Работаем в корневой директории
chdir ('../../');
require_once('api/Simpla.php');
$simpla = new Simpla();

$data_return = $_POST;

// Сумма, которую заплатил покупатель. Дробная часть отделяется точкой.
$amount = $data_return['orderamount'];

// Внутренний номер покупки продавца
// В этом поле передается id заказа в нашем магазине.
$order_id = intval($data_return['ordernumber']);

// Проверим статус
if($data_return['orderstate'] !== 'Approved')
die('Incorrect Status');

////////////////////////////////////////////////
// Выберем заказ из базы
////////////////////////////////////////////////
$order = $simpla->orders->get_order(intval($order_id));
if(empty($order))
die('Оплачиваемый заказ не найден');

// Нельзя оплатить уже оплаченный заказ
if($order->paid)
die('Этот заказ уже оплачен');


////////////////////////////////////////////////
// Выбираем из базы соответствующий метод оплаты
////////////////////////////////////////////////
$method = $simpla->payment->get_payment_method(intval($order->payment_method_id));
if(empty($method))
die("Неизвестный метод оплаты");

$settings = unserialize($method->settings);

// Проверяем контрольную подпись
$my_sign = strtoupper(md5(strtoupper(md5($settings['assist_key']).md5($data_return['merchant_id'].$data_return['ordernumber'].$data_return['orderamount'].$data_return['ordercurrency'].$data_return['orderstate']))));
if($data_return['checkvalue'] !== $my_sign)
die("bad sign\n");

if($amount != $simpla->money->convert($order->total_price, $method->currency_id, false) || $amount<=0)
die("incorrect price\n");

////////////////////////////////////
// Проверка наличия товара
////////////////////////////////////
$purchases = $simpla->orders->get_purchases(array('order_id'=>intval($order->id)));
foreach($purchases as $purchase)
{
$variant = $simpla->variants->get_variant(intval($purchase->variant_id));
if(empty($variant) || (!$variant->infinity && $variant->stock < $purchase->amount))
{
die("Нехватка товара $purchase->product_name $purchase->variant_name");
}
}

// Установим статус оплачен
$simpla->orders->update_order(intval($order->id), array('paid'=>1));

// Спишем товары
$simpla->orders->close(intval($order->id));
$simpla->notify->email_order_user(intval($order->id));
$simpla->notify->email_order_admin(intval($order->id));

die("OK".$order_id."\n");
Binary file added payment/Assist/example.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions payment/Assist/settings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<module>
<name>
Assist
</name>
<settings>
<variable>assist_key</variable>
<name>Секретное слово</name>
</settings>
<settings>
<variable>assist_merchant_id</variable>
<name>ID магазина</name>
</settings>
<settings>
<variable>assist_url</variable>
<name>URL</name>
</settings>
</module>
Loading

0 comments on commit 9fefafa

Please sign in to comment.