447 lines
17 KiB
PHP
447 lines
17 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/vendor/Moneta/autoload.php';
|
|
require_once __DIR__ . '/classes/monetaShopOrderGateway.class.php';
|
|
require_once __DIR__ . '/classes/monetaShopReturnPage.class.php';
|
|
require_once __DIR__ . '/classes/monetaSettingsControls.class.php';
|
|
|
|
use Moneta\Callback\CallbackOutcome;
|
|
use Moneta\Callback\CallbackProcessor;
|
|
use Moneta\Callback\FileLogThrottle;
|
|
use Moneta\Customer\SubscriberId;
|
|
use Moneta\Form\PaymentForm;
|
|
use Moneta\Form\ReturnUrls;
|
|
use Moneta\Plugin\Settings;
|
|
use Moneta\Plugin\SettingsException;
|
|
use Moneta\Protocol\AssistantProtocol;
|
|
use Moneta\Protocol\CallbackResponse;
|
|
use Moneta\Protocol\CmsInfo;
|
|
use Moneta\Protocol\Money;
|
|
use Moneta\Protocol\RequestField;
|
|
use Moneta\Protocol\TransactionId;
|
|
use Moneta\ReturnPage\ReturnType;
|
|
|
|
/**
|
|
* Плагин оплаты MONETA.RU (протокол MONETA.Assistant) для приложений Webasyst.
|
|
*
|
|
* Оболочка по конвенции Webasyst: достаёт данные из хоста и делегирует в классы `Moneta\`.
|
|
* Колбэк один на плагин (payments.php/moneta/): Check URL и Pay URL различаются по MNT_COMMAND.
|
|
* Поддерживается только приложение Shop-Script.
|
|
*/
|
|
class monetaPayment extends waPayment implements waIPayment
|
|
{
|
|
private ?monetaShopOrderGateway $orderGateway = null;
|
|
|
|
/**
|
|
* @return string[]
|
|
*/
|
|
public function allowedCurrency()
|
|
{
|
|
return [AssistantProtocol::CURRENCY_RUB];
|
|
}
|
|
|
|
/**
|
|
* Форма оплаты на странице «Заказ оформлен» и в «Мои заказы».
|
|
*
|
|
* @param array $payment_form_data
|
|
* @param waOrder|array $order_data
|
|
* @param bool $auto_submit
|
|
* @return string
|
|
* @throws waException
|
|
*/
|
|
public function payment($payment_form_data, $order_data, $auto_submit = false): string
|
|
{
|
|
$order = waOrder::factory($order_data);
|
|
|
|
$settings = $this->monetaSettings();
|
|
if (!$settings->isConfigured()) {
|
|
self::log($this->id, [
|
|
'error' => 'Не заданы номер счёта или код проверки целостности.',
|
|
'merchant_id' => $this->key,
|
|
]);
|
|
throw new waException('Оплата через MONETA.RU временно недоступна.');
|
|
}
|
|
|
|
$currency = AssistantProtocol::normalizeCurrency((string) $order->currency);
|
|
if ($currency === null) {
|
|
self::log($this->id, [
|
|
'error' => 'Валюта заказа не поддерживается: ' . $order->currency,
|
|
'order_id' => $order->id,
|
|
]);
|
|
throw new waException('Оплата через MONETA.RU временно недоступна.');
|
|
}
|
|
|
|
monetaShopReturnPage::rememberOrder((int) $order->id);
|
|
|
|
$amount = Money::fromFloat((float) $order->total);
|
|
$form = PaymentForm::create(
|
|
$settings,
|
|
(int) $order->id,
|
|
$amount,
|
|
$currency,
|
|
SubscriberId::fromCustomer(
|
|
(string) $order->getContactField('email'),
|
|
(string) $order->getContactField('phone'),
|
|
(int) $order->contact_id,
|
|
),
|
|
new DateTimeImmutable('now'),
|
|
new ReturnUrls(
|
|
$this->returnUrl(ReturnType::SUCCESS),
|
|
$this->returnUrl(ReturnType::FAIL),
|
|
$this->returnUrl(ReturnType::IN_PROGRESS),
|
|
$this->returnUrl(ReturnType::RETURN),
|
|
),
|
|
PaymentForm::description((string) $order->id_str),
|
|
$this->cmsInfo(),
|
|
AssistantProtocol::normalizeLocale((string) wa()->getLocale()),
|
|
);
|
|
|
|
$view = wa()->getView();
|
|
$view->assign([
|
|
'form_url' => $form->getAction(),
|
|
'form_fields' => $form->getFields(),
|
|
'button' => PaymentForm::buttonLabel($amount),
|
|
'auto_submit' => $auto_submit,
|
|
]);
|
|
|
|
return $view->fetch($this->path . '/templates/payment.html');
|
|
}
|
|
|
|
/**
|
|
* Приложение и экземпляр способа оплаты для колбэка. Источник истины — заказ из
|
|
* MNT_TRANSACTION_ID; если заказа нет или он другого способа оплаты — экземпляр с номером счёта
|
|
* из MNT_ID, чтобы ответить на Check URL подписанным отказом. MNT_ID входит в подпись, а её
|
|
* затем сверяет код найденного экземпляра.
|
|
*
|
|
* @param array $request
|
|
* @return waPayment
|
|
* @throws waException
|
|
*/
|
|
protected function callbackInit($request)
|
|
{
|
|
$this->app_id = monetaShopOrderGateway::APP_ID;
|
|
$this->merchant_id = null;
|
|
// Адаптер загружает приложение shop: без него модели Shop-Script в шлюзе не найдутся.
|
|
$this->getAdapter();
|
|
|
|
$transactionId = TransactionId::parse(RequestField::string((array) $request, 'MNT_TRANSACTION_ID'));
|
|
if ($transactionId !== null) {
|
|
$this->merchant_id = $this->orderGateway()->paymentInstanceOf($transactionId->getOrderId());
|
|
}
|
|
|
|
if ($this->merchant_id === null) {
|
|
$accountId = RequestField::string((array) $request, 'MNT_ID');
|
|
$this->merchant_id = $this->orderGateway()->paymentInstanceByAccount($accountId);
|
|
}
|
|
|
|
return parent::callbackInit($request);
|
|
}
|
|
|
|
/**
|
|
* Check URL и Pay URL ({@see CallbackProcessor::handle()}) или страница возврата покупателя.
|
|
* Ответ колбэка — сырой XML/JSON или текст FAIL, шаблон хоста не выводится.
|
|
*
|
|
* @param array $request GET и POST (waRequest::request())
|
|
* @return array
|
|
*/
|
|
protected function callbackHandler($request): array
|
|
{
|
|
$returnType = ReturnType::fromRequest(RequestField::string((array) $request, ReturnType::PARAMETER));
|
|
if ($returnType !== null) {
|
|
return $this->returnPage()->display($returnType, (array) $request);
|
|
}
|
|
|
|
$settings = $this->monetaSettings();
|
|
$processor = new CallbackProcessor($settings, $this->cmsInfo());
|
|
$outcome = $processor->handle((array) $request, (string) $this->key, $this->orderGateway());
|
|
|
|
// Без «Журнала уведомлений» плагин пишет только сбои — и без тела ответа (в нём данные покупателя).
|
|
if (!$settings->isNotificationLog()) {
|
|
return $outcome->isFailure()
|
|
? $this->callbackRespond($outcome, $request, false)
|
|
: $this->callbackOutput($outcome->getResponse());
|
|
}
|
|
|
|
if ($outcome->isUnsignedRejection()) {
|
|
return $this->rejectUnsigned($outcome, $request);
|
|
}
|
|
|
|
return $this->callbackRespond($outcome, $request, true);
|
|
}
|
|
|
|
/**
|
|
* Адрес возврата с платёжной формы.
|
|
*
|
|
* @param string $type ReturnType::SUCCESS…
|
|
* @return string
|
|
*/
|
|
private function returnUrl(string $type): string
|
|
{
|
|
return monetaShopReturnPage::returnUrl($this->getRelayUrl(), $type);
|
|
}
|
|
|
|
/**
|
|
* @return monetaShopReturnPage
|
|
* @throws waException
|
|
*/
|
|
private function returnPage(): monetaShopReturnPage
|
|
{
|
|
$log = function ($error) {
|
|
self::log($this->id, ['error' => $error]);
|
|
};
|
|
|
|
return new monetaShopReturnPage(
|
|
$this->path,
|
|
$this->getRelayUrl(),
|
|
$this->getAdapter(),
|
|
$this->orderGateway(),
|
|
$log,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Сбой вне штатных проверок: FAIL (MONETA.RU повторит уведомление), причина — в журнал.
|
|
*
|
|
* @param Exception $ex
|
|
* @return array
|
|
*/
|
|
protected function callbackExceptionHandler(Exception $ex): array
|
|
{
|
|
// Error (TypeError и т. п.) хост оборачивает в Exception (waPayment::callback()) — в журнал
|
|
// пишется исходная ошибка с местом, где она возникла.
|
|
$cause = ($ex->getPrevious() instanceof Error) ? $ex->getPrevious() : $ex;
|
|
$where = basename($cause->getFile()) . ':' . $cause->getLine();
|
|
self::log($this->id, ['error' => get_class($cause) . ': ' . $cause->getMessage() . ' (' . $where . ')']);
|
|
|
|
return $this->callbackOutput(CallbackResponse::fail());
|
|
}
|
|
|
|
/**
|
|
* Отказ до проверки подписи при включённом «Журнале уведомлений»: FAIL, причина — в журнал не чаще
|
|
* строки в минуту (FileLogThrottle), иначе пустые запросы и сканеры раздувают его. Сам запрос хост
|
|
* записывает в журнал всегда, до кода плагина (waPayment::callback()).
|
|
*
|
|
* @param CallbackOutcome $outcome
|
|
* @param array $request
|
|
* @return array
|
|
* @throws waException
|
|
*/
|
|
private function rejectUnsigned(CallbackOutcome $outcome, array $request): array
|
|
{
|
|
$throttle = new FileLogThrottle(wa()->getTempPath('payment', 'webasyst') . '/' . $this->id . '_rejections.txt');
|
|
$skipped = $throttle->next(time());
|
|
if ($skipped === null) {
|
|
return $this->callbackOutput($outcome->getResponse());
|
|
}
|
|
if ($skipped > 0) {
|
|
$outcome = CallbackOutcome::fail(
|
|
$outcome->getReason() . sprintf(' Ещё отказов до проверки подписи с прошлой записи: %d.', $skipped),
|
|
);
|
|
}
|
|
|
|
return $this->callbackRespond($outcome, $request, true);
|
|
}
|
|
|
|
/**
|
|
* Ответ с записью в журнал: причина решения, а при включённом «Журнале уведомлений» — и тело ответа.
|
|
*
|
|
* @param CallbackOutcome $outcome
|
|
* @param array $request
|
|
* @param bool $withResponse писать тело ответа (в нём ФИО, email и телефон покупателя из чека)
|
|
* @return array
|
|
*/
|
|
private function callbackRespond(CallbackOutcome $outcome, array $request, bool $withResponse): array
|
|
{
|
|
$entry = [
|
|
'command' => RequestField::string((array) $request, 'MNT_COMMAND') ?: 'PAY',
|
|
'MNT_TRANSACTION_ID' => RequestField::string((array) $request, 'MNT_TRANSACTION_ID'),
|
|
'merchant_id' => $this->key,
|
|
'result' => $outcome->getReason(),
|
|
];
|
|
if ($withResponse) {
|
|
$entry['response'] = $outcome->getResponse()->getBody();
|
|
}
|
|
self::log($this->id, $entry);
|
|
|
|
return $this->callbackOutput($outcome->getResponse());
|
|
}
|
|
|
|
/**
|
|
* Сырой ответ: хост при 'template' => false завершает запрос без своего шаблона.
|
|
*
|
|
* @param CallbackResponse $response
|
|
* @return array
|
|
*/
|
|
private function callbackOutput(CallbackResponse $response): array
|
|
{
|
|
if (!headers_sent()) {
|
|
header('Content-Type: ' . $response->getContentType());
|
|
}
|
|
echo $response->getBody();
|
|
|
|
return ['template' => false];
|
|
}
|
|
|
|
/**
|
|
* Проверка настроек перед сохранением; текст исключения хост показывает мерчанту.
|
|
* Новый способ оплаты (сохранённых настроек ещё нет) сохраняется без проверки.
|
|
*
|
|
* @param array $settings
|
|
* @return array
|
|
* @throws waException
|
|
*/
|
|
public function saveSettings($settings = []): array
|
|
{
|
|
try {
|
|
$settings = Settings::prepareForSave(
|
|
$settings,
|
|
(string) $this->getSettings(Settings::INTEGRITY_CODE),
|
|
$this->isNewInstance(),
|
|
);
|
|
} catch (SettingsException $ex) {
|
|
throw new waException($ex->getMessage());
|
|
}
|
|
|
|
return parent::saveSettings($settings);
|
|
}
|
|
|
|
/**
|
|
* Предупреждения ({@see Settings::warnings()}) над полями настроек.
|
|
*
|
|
* @param array $params
|
|
* @return string
|
|
* @throws waDbException
|
|
*/
|
|
public function getSettingsHTML($params = [])
|
|
{
|
|
// Адрес колбэка знает только экземпляр (getRelayUrl()), а контролы статические — передаётся значением поля.
|
|
if (!isset($params['value']) || !is_array($params['value'])) {
|
|
$params['value'] = [];
|
|
}
|
|
$params['value'][Settings::NOTIFY_URL_FIELD] = $this->getRelayUrl();
|
|
|
|
$html = parent::getSettingsHTML($params);
|
|
$warnings = '';
|
|
foreach ($this->monetaSettings()->warnings(monetaShopOrderGateway::taxRates()) as $warning) {
|
|
$warnings .= '<div class="alert warning small">'
|
|
. htmlspecialchars($warning, ENT_QUOTES, 'UTF-8')
|
|
. '</div>';
|
|
}
|
|
|
|
return $warnings . $html . $this->settingsAssets();
|
|
}
|
|
|
|
/**
|
|
* Стили и скрипт формы настроек (css/settings.css, js/settings.js),
|
|
* внутри HTML настроек: хост подключает отдельные файлы плагинов только своими средствами.
|
|
*
|
|
* @return string
|
|
*/
|
|
private function settingsAssets(): string
|
|
{
|
|
$info = waPayment::info($this->id);
|
|
$isNew = $this->isNewInstance();
|
|
|
|
$options = [
|
|
'fiscalization' => Settings::FISCALIZATION,
|
|
'receiptEmail' => Settings::RECEIPT_EMAIL,
|
|
'fiscalFields' => Settings::RECEIPT_FIELDS,
|
|
'defaultLogo' => ($isNew && !empty($info['logo'])) ? (string) $info['logo'] : null,
|
|
];
|
|
|
|
return '<style>' . file_get_contents($this->path . '/css/settings.css') . '</style>'
|
|
. '<script>' . file_get_contents($this->path . '/js/settings.js')
|
|
. 'window.monetaSettingsInit(' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
|
|
. ');</script>';
|
|
}
|
|
|
|
protected function initControls()
|
|
{
|
|
foreach (monetaSettingsControls::CONTROLS as $type => $method) {
|
|
$this->registerControl($type, ['monetaSettingsControls', $method]);
|
|
}
|
|
parent::initControls();
|
|
}
|
|
|
|
/**
|
|
* Шлюз к заказам Shop-Script — один на запрос. Сохранение транзакции, действие хоста и журнал у
|
|
* waPayment protected, поэтому шлюз получает их замыканиями.
|
|
*
|
|
* @return monetaShopOrderGateway
|
|
* @throws waException
|
|
*/
|
|
private function orderGateway(): monetaShopOrderGateway
|
|
{
|
|
if ($this->orderGateway === null) {
|
|
$this->orderGateway = new monetaShopOrderGateway(
|
|
$this,
|
|
$this->getAdapter(),
|
|
function (array $fields, array $raw) {
|
|
$transaction = $this->saveTransaction(array_merge($this->formalizeData([]), $fields), $raw);
|
|
|
|
return $this->execAppCallback(self::CALLBACK_PAYMENT, $transaction);
|
|
},
|
|
function (array $entry) {
|
|
self::log($this->id, $entry);
|
|
},
|
|
);
|
|
}
|
|
|
|
return $this->orderGateway;
|
|
}
|
|
|
|
/**
|
|
* Способ оплаты только создаётся: сохранённых настроек у экземпляра ещё нет.
|
|
*
|
|
* @return bool
|
|
* @throws waException
|
|
*/
|
|
private function isNewInstance(): bool
|
|
{
|
|
return !(array) $this->getAdapter()->getSettings($this->id, $this->key);
|
|
}
|
|
|
|
/**
|
|
* @return string MNT_CMS для формы и ответов колбэка
|
|
*/
|
|
private function cmsInfo(): string
|
|
{
|
|
return CmsInfo::format($this->shopVersion(), PHP_VERSION, $this->pluginVersion());
|
|
}
|
|
|
|
/**
|
|
* @return Settings настройки этого экземпляра способа оплаты
|
|
*/
|
|
private function monetaSettings(): Settings
|
|
{
|
|
return Settings::fromArray((array) $this->getSettings());
|
|
}
|
|
|
|
/**
|
|
* Версия Shop-Script из `app.php`: `wa()->getVersion()` дописывает номер сборки.
|
|
*
|
|
* @return string
|
|
* @throws waException
|
|
*/
|
|
private function shopVersion(): string
|
|
{
|
|
$info = wa()->getAppInfo('shop');
|
|
|
|
return isset($info['version']) ? (string) $info['version'] : '';
|
|
}
|
|
|
|
/**
|
|
* Версия из `plugin.php` как есть: `getProperties('version')` дописывает номер сборки.
|
|
*
|
|
* @return string
|
|
*/
|
|
private function pluginVersion(): string
|
|
{
|
|
$config = include $this->path . '/lib/config/plugin.php';
|
|
|
|
return is_array($config) && isset($config['version']) ? (string) $config['version'] : '';
|
|
}
|
|
}
|