Skip to content
Snippets Groups Projects
Commit d6cee80c authored by Helena Zajika's avatar Helena Zajika
Browse files

Issue #3406123: Fix the issues reported by phpcs

parent e0aa9799
No related branches found
No related tags found
No related merge requests found
###### Change of parameters that go to the payment
```
<?php
function HOOK_monobank_payment_params_alter(&$params, $payment, &$config){
}
```
This module provides a [Drupal AlternativeCommerce (Basket)](https://www.drupal.org/project/basket) payment method to embed the payment services provided by [Monobank API](https://api.monobank.ua/docs/acquiring.html).
###### Call upon payment, when the payment is linked to the site
```
<?php
function HOOK_monobank_api_alter($payment, $fields){
## Dependencies
* [Drupal AlternativeCommerce (Basket)](https://www.drupal.org/project/basket)
}
```
\ No newline at end of file
## Setup
* After installation, go to the payment systems settings
page <code>/admin/basket/settings-payment</code>.
* Create a payment point and indicate in the service "Monobank".
* After you create, you will have a button to go to the settings
page of the payment gateway itself. Or you can follow
the link <code>/admin/config/development/monobank</code>.
* The module can also work in test mode.
#payment_form{
max-width: 960px;
margin: 0 auto;
background: #fff;
border: 1px solid #007bff;
border-radius: 15px;
box-shadow: 0 3px 10px 0 rgba(0,0,0,.1);
padding: 16px;
text-align: center;
}
\ No newline at end of file
#payment_form {
max-width: 960px;
margin: 0 auto;
background: #fff;
border: 1px solid #007bff;
border-radius: 15px;
box-shadow: 0 3px 10px 0 rgba(0,0,0,.1);
padding: 16px;
text-align: center;
}
<?php
/**
* @file
* Hooks provided by the monobank module.
*/
/**
* Change of parameters that go to the payment.
*
* @param array $params
* Params data.
* @param object $payment
* Payment object.
* @param array $config
* Config data.
*/
function hook_monobank_payment_params_alter(array &$params, $payment, array &$config) {
}
/**
* Alter API.
*
* @param object $payment
* Payment object.
* @param array $fields
* Payment fields.
*/
function hook_monobank_api_alter($payment, array $fields) {
}
......@@ -6,8 +6,4 @@ package: 'Online store'
configure: monobank.settings
'interface translation project': monobank
'interface translation server pattern': modules/basket/%project/translations/%project.%language.po
# Information added by Alternativecommerce.org packaging script on 2023-11-29
version: '1.1.0-rc7'
project: monobank
datestamp: 1701271278
\ No newline at end of file
project: monobank
\ No newline at end of file
<?php
function monobank_schema(){
$schema['payments_monobank'] = [
'fields' => [
'id' => [
'type' => 'serial',
'not null' => TRUE,
/**
* @file
* Install, update and uninstall functions for the Monobank module.
*/
/**
* Function to define the database schema for the 'payments_monobank' table.
*/
function monobank_schema() {
$schema['payments_monobank'] = [
'fields' => [
'id' => [
'type' => 'serial',
'not null' => TRUE,
],
'nid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE,
],
'nid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE
'sid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE,
],
'sid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE
'uid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE,
],
'uid' => [
'type' => 'int',
'size' => 'big',
'not null' => FALSE
'created' => [
'type' => 'int',
'not null' => FALSE,
'length' => 100,
],
'created' => [
'type' => 'int',
'not null' => FALSE,
'length' => 100
'paytime' => [
'type' => 'int',
'not null' => FALSE,
'length' => 100,
],
'paytime' => [
'type' => 'int',
'not null' => FALSE,
'length' => 100
'amount' => [
'type' => 'varchar',
'not null' => FALSE,
'length' => 255,
],
'amount' => [
'type' => 'varchar',
'not null' => FALSE,
'length' => 255
'currency' => [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
],
'currency' => [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE
'status' => [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
],
'status' => [
'type' => 'varchar',
'length' => 255,
'not null' => FALSE
'data' => [
'type' => 'text',
'size' => 'big',
'not null' => FALSE,
],
'data' => [
'type' => 'text',
'size' => 'big',
'not null' => FALSE
]
],
'primary key' => ['id'],
'indexes' => [
'nid' => ['nid'],
'sid' => ['sid'],
'uid' => ['uid'],
'currency' => ['currency'],
'created' => ['created'],
'paytime' => ['paytime'],
'status' => ['status'],
]
];
'primary key' => ['id'],
'indexes' => [
'nid' => ['nid'],
'sid' => ['sid'],
'uid' => ['uid'],
'currency' => ['currency'],
'created' => ['created'],
'paytime' => ['paytime'],
'status' => ['status'],
],
];
return $schema;
}
......@@ -2,4 +2,4 @@ css:
version: VERSION
css:
theme:
misc/styles.css: {}
\ No newline at end of file
misc/styles.css: {}
......@@ -8,40 +8,41 @@
/**
* Implements hook_basket_translate_context_alter().
*/
function monobank_basket_translate_context_alter(&$context){
$context[] = 'monobank';
function monobank_basket_translate_context_alter(&$context) {
$context[] = 'monobank';
}
/**
* Implements hook_theme().
*/
function monobank_theme(){
function monobank_theme() {
return [
'monobank_success_page' => [
'variables' => [
'monobank_success_page' => [
'variables' => [
'info' => NULL,
],
]
],
];
}
/**
* Implements hook_basket_noty_actions_alter().
*/
function monobank_basket_noty_actions_alter(&$actions){
$actions['change_monobank_status'] = \Drupal::service('Monobank')->t('Change payment status').' (Monobank)';
function monobank_basket_noty_actions_alter(&$actions) {
$actions['change_monobank_status'] = t('Change payment status', [], ['context' => 'monobank'])->__toString() . ' (Monobank)';
}
/**
* Implements hook_basket_noty_twig_tokens_alter().
*/
function monobank_basket_noty_twig_tokens_alter(&$tokens) {
$tokens['monobank_status'] = NULL;
if(!empty($tokens['order']->nid)){
$payment = \Drupal::service('Monobank')->load([
'nid' => $tokens['order']->nid
$tokens['monobank_status'] = NULL;
if (!empty($tokens['order']->nid)) {
$payment = \Drupal::getContainer()->get('Monobank')->load([
'nid' => $tokens['order']->nid,
]);
if(!empty($payment->status)){
$tokens['monobank_status'] = $payment->status;
if (!empty($payment->status)) {
$tokens['monobank_status'] = $payment->status;
}
}
}
......@@ -10,7 +10,7 @@ monobank.payments:
path: '/admin/config/development/monobank/payments'
defaults:
_title: 'Payments'
_form: '\Drupal\monobank\Form\monobankPaymentsForm'
_form: '\Drupal\monobank\Form\MonobankPaymentsForm'
requirements:
_permission: 'access monobank settings'
......
......@@ -2,11 +2,15 @@
namespace Drupal\monobank\Controller;
use Drupal\Core\Url;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class of Pages.
*/
class Pages {
/**
/**
* Monobank service.
*
* @var \Drupal\monobank\Monobank
......@@ -44,29 +48,38 @@ class Pages {
$this->config = \Drupal::config('monobank.settings');
}
public function title(array $_title_arguments = array(), $_title = ''){
return $this->monobank->t($_title);
/**
* {@inheritdoc}
*/
public function title(array $_title_arguments = [], $_title = '') {
return t($_title, $_title_arguments, ['context' => 'monobank']);
}
/**
* Retrieves the pages based on the page type.
*
* @param string $page_type
* The type of the page.
*/
public function pages($page_type) {
$element = [];
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
switch($page_type) {
case'pay':
switch ($page_type) {
case'pay':
$is_404 = TRUE;
$payment = $this->monobank->load([
'id' => $this->query['pay_id'] ?? '-'
'id' => $this->query['pay_id'] ?? '-',
]);
if(!empty($payment) && $payment->status == 'new') {
if (!empty($payment) && $payment->status == 'new') {
$is_404 = FALSE;
$element['form'] = \Drupal::formBuilder()->getForm('\Drupal\monobank\Form\PaymentForm', $payment);
}
if($is_404){
if ($is_404) {
throw new NotFoundHttpException();
}
break;
break;
case'status':
$_POST = @json_decode(file_get_contents('php://input'), true);
$_POST = @json_decode(file_get_contents('php://input'), TRUE);
if (empty($_POST['invoiceId'])) {
throw new NotFoundHttpException();
......@@ -74,43 +87,44 @@ class Pages {
$config = \Drupal::config('monobank.settings')->get('config');
$payment = $this->monobank->load([
'id' => $_GET['id'] ?? '-'
'id' => $_GET['id'] ?? '-',
]);
if(!empty($payment->currency) && (string) $payment->currency === (string) $_POST['ccy'] && (string) ($payment->amount * 100) === (string) $_POST['amount']) {
if (!empty($payment->currency) && (string) $payment->currency === (string) $_POST['ccy'] && (string) ($payment->amount * 100) === (string) $_POST['amount']) {
$prePay = @unserialize($payment->data);
if($prePay['insert']['invoiceId'] == (string) @$_POST['invoiceId']){
if ($prePay['insert']['invoiceId'] == (string) @$_POST['invoiceId']) {
$status = $_POST['status'] ?? '';
$prePay['status'] = $_POST;
$update = [
'id' => $payment->id,
'data' => serialize($prePay),
];
if($status == 'success'){
if ($status == 'success') {
$update['paytime'] = time();
}
if(!empty($status)){
if (!empty($status)) {
$update['status'] = $status;
}
$this->monobank->update((object) $update);
if($status == 'success'){
// ---
if(!empty($payment->nid) && !empty($this->basket)) {
if(method_exists($this->basket, 'paymentFinish')) {
if ($status == 'success') {
if (!empty($payment->nid) && !empty($this->basket)) {
if (method_exists($this->basket, 'paymentFinish')) {
$this->basket->paymentFinish($payment->nid);
}
}
// Alter
// Alter:
\Drupal::moduleHandler()->alter('monobank_api', $payment, $_POST);
// Trigger change payment status by order
if(!empty($payment->nid) && !empty($this->basket)){
// Trigger change payment status by order:
if (!empty($payment->nid) && !empty($this->basket)) {
$order = $this->basket->Orders(NULL, $payment->nid)->load();
if(!empty($order) && \Drupal::moduleHandler()->moduleExists('basket_noty')){
if (!empty($order) && \Drupal::moduleHandler()->moduleExists('basket_noty')) {
\Drupal::service('BasketNoty')->trigger('change_monobank_status', [
'order' => $order
'order' => $order,
]);
}
}
......@@ -119,79 +133,76 @@ class Pages {
}
}
exit('Sign wrong');
break;
case 'payment_result':
$element['#title'] = $this->monobank->t('Payment result');
$pid = $_GET['id'] ?? 0;
$payON = FALSE;
if(!empty($pid)){
if (!empty($pid)) {
$payment = $this->monobank->load(['id' => $pid]);
if(!empty($payment->status) && $payment->status == 'success'){
if (!empty($payment->status) && $payment->status == 'success') {
$payON = TRUE;
}
if(!$payON){
if (!$payON) {
$getStatus = $this->monobank->getStatus($pid);
if(!empty($getStatus) && $getStatus == 'success'){
if (!empty($getStatus) && $getStatus == 'success') {
$payON = TRUE;
}
}
if($payON){
if ($payON) {
$config = \Drupal::config('monobank.settings')->get('config');
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$success = !empty($config['success']) ? $config['success'] : '';
$element += [
'#theme' => 'monobank_success_page',
'#info' => [
'text' => [
'#type' => 'processed_text',
'#text' => !empty($success['value']) ? $success['value'] : '',
'#format' => !empty($success['format']) ? $success['format'] : NULL,
'#theme' => 'monobank_success_page',
'#info' => [
'text' => [
'#type' => 'processed_text',
'#text' => !empty($success['value']) ? $success['value'] : '',
'#format' => !empty($success['format']) ? $success['format'] : NULL,
],
'type' => 'success'
'type' => 'success',
],
'#attached' => [
'library' => ['monobank/css'],
],
'#attached' => [
'library' => [
'monobank/css'
]
]
];
} else {
}
else {
$element += [
'#theme' => 'monobank_success_page',
'#info' => [
'text' => [
'text' => [
'#type' => 'processed_text',
'#text' => '<p class="text-align-center"><strong>'.$this->monobank->t('No payment data.').'</strong></p>',
'#format' => 'full_html',
'#theme' => 'monobank_success_page',
'#info' => [
'text' => [
'text' => [
'#type' => 'processed_text',
'#text' => '<p class="text-align-center"><strong>' . $this->monobank->t('No payment data.') . '</strong></p>',
'#format' => 'full_html',
],
'link' => [
'#type' => 'link',
'#title' => $this->monobank->t('Repeat'),
'#url' => new \Drupal\Core\Url('monobank.pages', [
'page_type' => 'pay'
],[
'attributes' => [
'class' => ['form-submit']
'link' => [
'#type' => 'link',
'#title' => $this->monobank->t('Repeat'),
'#url' => new Url('monobank.pages', [
'page_type' => 'pay',
], [
'attributes' => [
'class' => ['form-submit'],
],
'query' => [
'pay_id' => $pid
]
])
'query' => [
'pay_id' => $pid,
],
]),
],
],
'type' => 'error'
'type' => 'error',
],
'#attached' => [
'library' => ['monobank/css'],
],
'#attached' => [
'library' => [
'monobank/css'
]
]
];
}
}
break;
}
return $element;
break;
}
return $element;
}
}
<?php
namespace Drupal\monobank\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Defines the Monobank Payments form.
*/
class MonobankPaymentsForm extends FormBase {
/**
* Monobank object.
*
* @var object|\Drupal\monobank\Monobank|null
*/
protected object $monobank;
const STATUSES = [
'new' => 'New',
'expired' => 'The validity period has expired',
'created' => 'Payment created successfully, payment pending',
'processing' => 'Payment is being processed',
'success' => 'Successful payment',
'failure' => 'Unsuccessful payment',
'reversed' => 'The payment has been returned',
];
/**
* Class constructor.
*/
public function __construct() {
$this->monobank = \Drupal::getContainer()->get('Monobank');
}
/**
* Returns the form ID for the Monobank Payments form.
*/
public function getFormId() {
return 'monobank_payments';
}
/**
* Build the form for payments.
*
* @param array $form
* The form definition array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$getCurrency = SettingsForm::getCurrency();
$form['#title'] = $this->monobank->t('Payments');
$form['filter'] = [
'#type' => 'details',
'#title' => $this->monobank->t('Filter'),
];
$form['filter']['status'] = [
'#type' => 'select',
'#title' => $this->monobank->t('Status'),
'#options' => $this->getOptionsStatus(),
'#empty_option' => t('All'),
'#default_value' => @$_GET['status'],
];
$form['filter']['submit'] = [
'#type' => 'submit',
'#value' => $this->monobank->t('Search'),
];
$form['table'] = [
'#type' => 'table',
'#header' => [
[
'data' => 'ID',
'field' => 'l.id',
'sort' => 'desc',
],
[
'data' => $this->monobank->t('Created'),
'field' => 'l.created',
],
[
'data' => 'NID',
'field' => 'l.nid',
],
[
'data' => 'SID',
'field' => 'l.sid',
],
[
'data' => $this->monobank->t('User ID'),
'field' => 'l.uid',
],
[
'data' => $this->monobank->t('Amount'),
'field' => 'l.amount',
],
[
'data' => $this->monobank->t('Status'),
'field' => 'l.status',
],
[
'data' => $this->monobank->t('Payment time'),
'field' => 'l.paytime',
],
],
];
foreach ($this->getPays($form['table']['#header']) as $row) {
$row->data = !empty($row->data) ? unserialize($row->data) : [];
$form['table'][$row->id]['id'] = [
'#markup' => $row->id,
];
$form['table'][$row->id]['created'] = [
'#markup' => date('d.m.Y H:i', $row->created),
];
$form['table'][$row->id]['nid'] = [
'#markup' => !empty($row->nid) ? $row->nid : '- - -',
];
$form['table'][$row->id]['sid'] = [
'#markup' => !empty($row->sid) ? $row->sid : '- - -',
];
$form['table'][$row->id]['user'] = [
'#markup' => !empty($row->uid) ? $row->uid : '- - -',
];
$form['table'][$row->id]['amount'] = [
'#markup' => $row->amount . ' (' . ($getCurrency[$row->currency] ?? '- - -') . ')',
];
$form['table'][$row->id]['status'] = [
'#markup' => $this->getPayStatus($row),
];
$form['table'][$row->id]['paytime'] = [
'#markup' => !empty($row->paytime) ? date('d.m.Y H:i', $row->paytime) : '- - -',
];
if ($row->status == 'new') {
$form['table'][$row->id]['paytime']['#markup'] = Url::fromRoute('monobank.pages', [
'page_type' => 'pay',
], [
'absolute' => TRUE,
'query' => ['pay_id' => $row->id],
])->toString();
}
}
$form['pager'] = [
'#type' => 'pager',
];
return $form;
}
/**
* Submit the form and redirect to the payments page with the selected status.
*
* @param array $form
* The form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state object.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$query = $_GET;
$query['status'] = $form_state->getValue('status');
$url = Url::fromRoute('monobank.payments', [], ['query' => $query]);
$form_state->setRedirectUrl($url);
}
/**
* Retrieve the payments with optional filtering and pagination.
*
* @param string $header
* The sort header.
*/
public function getPays($header) {
$query = \Drupal::database()->select('payments_monobank', 'l');
$query->fields('l');
if (!empty($_GET['status'])) {
$query->condition('l.status', $_GET['status']);
}
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(50);
return $pager->execute()->fetchAll();
}
/**
* Retrieve the payment status.
*
* @param object $row
* The payment row object.
*/
public function getPayStatus($row) {
$status = !empty($row->status) ? $row->status : '- - -';
if (!empty(self::STATUSES[$status])) {
$status = self::STATUSES[$status];
}
return $status;
}
/**
* Retrieve the options for payment status.
*/
public function getOptionsStatus() {
$query = \Drupal::database()->select('payments_monobank', 'l');
$query->fields('l', ['status', 'status']);
$options = $query->execute()->fetchAllKeyed();
foreach ($options as $key => $value) {
if (!empty(self::STATUSES[$key])) {
$options[$key] = self::STATUSES[$key];
}
}
return $options;
}
}
......@@ -48,9 +48,8 @@ class PaymentForm extends FormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $payment = NULL) {
// Payment alter
// Payment alter:
$this->basketPaymentFormAlter($form, $form_state, $payment);
// ---
return $form;
}
......@@ -68,19 +67,33 @@ class PaymentForm extends FormBase {
->fields('m', ['data'])
->condition('m.id', $payment->id)
->execute()->fetchField();
if(!empty($payData)) {
if (!empty($payData)) {
$payData = unserialize($payData);
if(!empty($payData['insert']['invoiceId'])) {
if (!empty($payData['insert']['invoiceId'])) {
return;
}
}
$config = $this->config->get('config');
$data = [
'amount' => (int) ( $payment->amount * 100 ),
'amount' => (int) ($payment->amount * 100),
'ccy' => (int) $payment->currency,
'redirectUrl' => Url::fromRoute('monobank.pages', ['page_type' => 'payment_result'], ['query' => ['id' => $payment->id], 'absolute' => TRUE])->toString(),
'webHookUrl' => Url::fromRoute('monobank.pages', ['page_type' => 'status'], ['query' => ['id' => $payment->id], 'absolute' => TRUE])->toString(),
'redirectUrl' => Url::fromRoute('monobank.pages', [
'page_type' => 'payment_result',
], [
'query' => [
'id' => $payment->id,
],
'absolute' => TRUE,
])->toString(),
'webHookUrl' => Url::fromRoute('monobank.pages', [
'page_type' => 'status',
], [
'query' => [
'id' => $payment->id,
],
'absolute' => TRUE,
])->toString(),
];
if (!empty($config['ppo']) && \Drupal::hasService('Basket')) {
......@@ -111,31 +124,31 @@ class PaymentForm extends FormBase {
}
}
// Alter
// Alter:
\Drupal::moduleHandler()->alter('monobank_payment_params', $data, $payment, $config);
// Метод give
$Token = (string) @$config['key'];
// Method give:
$token = (string) @$config['key'];
try {
$client = \Drupal::httpClient();
$response = $client->post($this::API_URL.'create', [
$response = $client->post($this::API_URL . 'create', [
'body' => json_encode($data),
'headers' => [
'Content-Type' => 'application/json',
'X-Token' => trim($Token),
'X-Token' => trim($token),
],
]);
$resData = $response->getBody()->getContents();
if(!empty($resData)) {
if (!empty($resData)) {
$resData = @json_decode($resData, TRUE);
}
}
catch ( \Exception $e) {
\Drupal::messenger()->addMessage( $e->getMessage() , 'error');
catch (\Exception $e) {
\Drupal::messenger()->addMessage($e->getMessage(), 'error');
}
if(!empty($resData['invoiceId']) && !empty($resData['pageUrl'])){
if (!empty($resData['invoiceId']) && !empty($resData['pageUrl'])) {
$raw = unserialize($payment->data);
$raw['insert'] = $resData;
$update = (object) [
......@@ -143,7 +156,7 @@ class PaymentForm extends FormBase {
'data' => serialize($raw),
];
$this->monobank->update($update);
$response = new RedirectResponse( $resData['pageUrl'] );
$response = new RedirectResponse($resData['pageUrl']);
$response->send();
exit();
}
......
......@@ -4,10 +4,9 @@ namespace Drupal\monobank\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Url;
/**
* Class SettingsForm.
* Class of SettingsForm.
*/
class SettingsForm extends FormBase {
......@@ -39,7 +38,7 @@ class SettingsForm extends FormBase {
$this->monobank = \Drupal::service('Monobank');
$this->ajax = [
'wrapper' => 'monobank_settings_form_ajax_wrap',
'callback' => '::ajaxSubmit'
'callback' => [$this, 'ajaxSubmit'],
];
$this->config = \Drupal::config('monobank.settings');
}
......@@ -55,53 +54,53 @@ class SettingsForm extends FormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$form += [
'#prefix' => '<div id="'.$this->ajax['wrapper'].'">',
'#suffix' => '</div>',
'#prefix' => '<div id="' . $this->ajax['wrapper'] . '">',
'#suffix' => '</div>',
'status_messages' => [
'#type' => 'status_messages'
]
'#type' => 'status_messages',
],
];
$form['config'] = [
'#tree' => TRUE,
'currency' => [
'#type' => 'select',
'#type' => 'select',
'#options' => self::getCurrency(),
'#title' => $this->monobank->t('Currency'),
'#title' => $this->monobank->t('Currency'),
'#default_value' => $this->config->get('config.currency'),
'#required' => TRUE
'#required' => TRUE,
],
'key' => [
'#type' => 'textfield',
'#title' => $this->monobank->t('X-Token'),
'#type' => 'textfield',
'#title' => $this->monobank->t('X-Token'),
'#default_value' => $this->config->get('config.key'),
],
'ppo' => [
'#type' => 'checkbox',
'#title' => $this->monobank->t('Order PPO'),
'#default_value'=> $this->config->get('config.ppo'),
'#type' => 'checkbox',
'#title' => $this->monobank->t('Order PPO'),
'#default_value' => $this->config->get('config.ppo'),
],
'success' => [
'#type' => 'text_format',
'#title' => $this->monobank->t('Successful payment page text'),
'#default_value' => $this->config->get('config.success.value'),
'#format' => $this->config->get('config.success.format'),
],
'success' => [
'#type' => 'text_format',
'#title' => $this->monobank->t('Successful payment page text'),
'#default_value'=> $this->config->get('config.success.value'),
'#format' => $this->config->get('config.success.format'),
]
];
$form['actions'] = [
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#name' => 'save',
'#value' => t('Save configuration'),
'#attributes' => [
'class' => ['button--primary']
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#name' => 'save',
'#value' => t('Save configuration'),
'#attributes' => [
'class' => ['button--primary'],
],
'#ajax' => $this->ajax
]
'#ajax' => $this->ajax,
],
];
return $form;
}
......@@ -126,7 +125,7 @@ class SettingsForm extends FormBase {
public function submitForm(array &$form, FormStateInterface $form_state) {}
/**
* get currency
* Get a list of currency.
*/
public static function getCurrency() {
return [
......
<?php
namespace Drupal\monobank\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class monobankPaymentsForm extends FormBase{
protected $Monobank;
const STATUSES = [
'new' => 'Новий',
'expired' => 'Термін дії закінчився',
'created' => 'Оплату створено успішно, очікується оплата',
'processing' => 'Платіж обробляється',
'success' => 'Успішна оплата',
'failure' => 'Не успішна оплата',
'reversed' => 'Оплата повернена',
];
// ---
public function __construct(){
$this->Monobank = \Drupal::service('Monobank');
}
// ---
public function getFormId(){
return 'monobank_payments';
}
public function buildForm(array $form, FormStateInterface $form_state){
$getCurrency = \Drupal\monobank\Form\SettingsForm::getCurrency();
$form['#title'] = $this->Monobank->t('Payments');
$form['filter'] = [
'#type' => 'details',
'#title' => $this->Monobank->t('Filter')
];
$form['filter']['status'] = [
'#type' => 'select',
'#title' => $this->Monobank->t('Status'),
'#options' => $this->getOptionsStatus(),
'#empty_option' => t('All'),
'#default_value'=> @$_GET['status']
];
$form['filter']['submit'] = [
'#type' => 'submit',
'#value' => $this->Monobank->t('Search')
];
$form['table'] = [
'#type' => 'table',
'#header' => [
[
'data' => 'ID',
'field' => 'l.id',
'sort' => 'desc'
],
[
'data' => $this->Monobank->t('Created'),
'field' => 'l.created'
],
[
'data' => 'NID',
'field' => 'l.nid'
],
[
'data' => 'SID',
'field' => 'l.sid'
],
[
'data' => $this->Monobank->t('User ID'),
'field' => 'l.uid'
],
[
'data' => $this->Monobank->t('Amount'),
'field' => 'l.amount'
],
[
'data' => $this->Monobank->t('Status'),
'field' => 'l.status'
],
[
'data' => $this->Monobank->t('Payment time'),
'field' => 'l.paytime'
]
]
];
foreach ($this->getPays($form['table']['#header']) as $row){
// ---
$row->data = !empty($row->data) ? unserialize($row->data) : [];
// ---
$form['table'][$row->id]['id'] = [
'#markup' => $row->id
];
$form['table'][$row->id]['created'] = [
'#markup' => date('d.m.Y H:i', $row->created)
];
$form['table'][$row->id]['nid'] = [
'#markup' => !empty($row->nid) ? $row->nid : '- - -'
];
$form['table'][$row->id]['sid'] = [
'#markup' => !empty($row->sid) ? $row->sid : '- - -'
];
$form['table'][$row->id]['user'] = [
'#markup' => !empty($row->uid) ? $row->uid : '- - -'
];
$form['table'][$row->id]['amount'] = [
'#markup' => $row->amount.' ('.($getCurrency[$row->currency] ?? '- - -').')'
];
$form['table'][$row->id]['status'] = [
'#markup' => $this->getPayStatus($row)
];
$form['table'][$row->id]['paytime'] = [
'#markup' => !empty($row->paytime) ? date('d.m.Y H:i', $row->paytime) : '- - -'
];
if($row->status == 'new'){
$form['table'][$row->id]['paytime']['#markup'] = Url::fromRoute('monobank.pages', [
'page_type' => 'pay'
], [
'absolute' => TRUE,
'query' => [ 'pay_id' => $row->id ]
])->toString();
}
}
$form['pager'] = [
'#type' => 'pager'
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state){
$query = $_GET;
$query['status'] = $form_state->getValue('status');
$url = Url::fromRoute('monobank.payments', [], [
'query' => $query
]);
$form_state->setRedirectUrl($url);
}
public function getPays($header){
$query = \Drupal::database()->select('payments_monobank', 'l');
$query->fields('l');
if(!empty($_GET['status'])){
$query->condition('l.status', $_GET['status']);
}
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(50);
return $pager->execute()->fetchAll();
}
public function getPayStatus($row){
$status = !empty($row->status) ? $row->status : '- - -';
if(!empty(self::STATUSES[$status])){
$status = self::STATUSES[$status];
}
return $status;
}
public function getOptionsStatus(){
$query = \Drupal::database()->select('payments_monobank', 'l');
$query->fields('l', ['status', 'status']);
$options = $query->execute()->fetchAllKeyed();
foreach ($options as $key => $value) {
if(!empty(self::STATUSES[$key])){
$options[$key] = self::STATUSES[$key];
}
}
return $options;
}
}
\ No newline at end of file
......@@ -6,7 +6,7 @@ use Drupal\mysql\Driver\Database\mysql\Connection;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Class Monobank.
* Class of Monobank.
*/
class Monobank {
......@@ -34,62 +34,73 @@ class Monobank {
$this->config = \Drupal::config('monobank.settings');
}
/*
* {@inheritdoc}
/**
* Translates a string to the specified language.
*
* @param string $string
* The string to be translated.
* @param array $args
* (optional) An array of arguments to replace placeholders in the string.
*/
public function t($string, $args = []){
public function t(string $string, array $args = []) {
return new TranslatableMarkup($string, $args, ['context' => 'monobank']);
}
/*
* {@inheritdoc}
/**
* Loads a payment based on the given parameters.
*
* @param array $params
* An array of parameters to filter the payment.
*/
public function load($params) {
public function load(array $params) {
$query = $this->database->select('payments_monobank', 'l');
$query->fields('l');
if(!empty($params['id'])) {
if (!empty($params['id'])) {
$query->condition('l.id', $params['id']);
}
if(!empty($params['nid'])) {
if (!empty($params['nid'])) {
$query->condition('l.nid', $params['nid']);
}
if(!empty($params['sid'])) {
if (!empty($params['sid'])) {
$query->condition('l.sid', $params['sid']);
}
if(empty($params['data'])) {
if (empty($params['data'])) {
$params['data'] = [];
}
$payment = $query->execute()->fetchObject();
// ---
if(!empty($params['create_new'])) {
if (!empty($params['create_new'])) {
$payment = FALSE;
}
if(empty($payment) && !empty($params['amount'])){
$payment = (object)[
'nid' => !empty($params['nid']) ? $params['nid'] : NULL,
'sid' => !empty($params['sid']) ? $params['sid'] : NULL,
'uid' => \Drupal::currentUser()->id(),
'created' => time(),
'paytime' => NULL,
'amount' => $params['amount'],
'currency' => !empty($params['currency']) ? $params['currency'] : \Drupal::config('monobank.settings')->get('config.currency'),
'status' => 'new',
'data' => serialize($params['data'])
if (empty($payment) && !empty($params['amount'])) {
$payment = (object) [
'nid' => !empty($params['nid']) ? $params['nid'] : NULL,
'sid' => !empty($params['sid']) ? $params['sid'] : NULL,
'uid' => \Drupal::currentUser()->id(),
'created' => time(),
'paytime' => NULL,
'amount' => $params['amount'],
'currency' => !empty($params['currency']) ? $params['currency'] : \Drupal::config('monobank.settings')->get('config.currency'),
'status' => 'new',
'data' => serialize($params['data']),
];
$payment->id = $this->database->insert('payments_monobank')
->fields((array)$payment)
->fields((array) $payment)
->execute();
}
return $payment;
}
/*
* {@inheritdoc}
/**
* Updates a payment record in the 'payments_monobank' table.
*
* @param object $payment
* The payment object to be updated.
*/
public function update($payment) {
if(!empty($payment->id)){
$updateFields = (array)$payment;
if (!empty($payment->id)) {
$updateFields = (array) $payment;
unset($updateFields['id']);
$this->database->update('payments_monobank')
->fields($updateFields)
......@@ -98,64 +109,70 @@ class Monobank {
}
}
/*
* {@inheritdoc}
/**
* Retrieves the status of a payment.
*
* @param int $pid
* (optional) The payment ID. Defaults to 0.
*/
public function getStatus($pid = 0) {
$payment = $this->load(['id' => $pid]);
if(!empty($payment)){
if (!empty($payment)) {
$raw = unserialize($payment->data);
$config = $this->config->get('config');
// Alter
// Alter:
$data = [];
\Drupal::moduleHandler()->alter('monobank_payment_params', $data, $payment, $config);
// Метод give
$Token = (string) @$config['key'];
// Method give:
$token = (string) @$config['key'];
try {
$client = \Drupal::httpClient();
$response = $client->get($this::API_URL.'status?invoiceId='.$raw['insert']['invoiceId'], [
$response = $client->get($this::API_URL . 'status?invoiceId=' . $raw['insert']['invoiceId'], [
'headers' => [
'Content-Type' => 'application/json',
'X-Token' => trim($Token),
'X-Token' => trim($token),
],
]);
$resData = $response->getBody()->getContents();
if(!empty($resData)) {
if (!empty($resData)) {
$resData = @json_decode($resData, TRUE);
}
} catch ( \Exception $e) {
\Drupal::messenger()->addMessage( $e->getMessage() , 'error');
}
catch (\Exception $e) {
\Drupal::messenger()->addMessage($e->getMessage(), 'error');
}
if(!empty($resData) && !empty($resData['status'])){
if (!empty($resData) && !empty($resData['status'])) {
$raw['status'] = $resData;
$update = (object) [
'id' => $payment->id,
'id' => $payment->id,
'status' => $resData['status'],
'data' => serialize($raw),
'data' => serialize($raw),
];
$this->update($update);
if($resData['status'] === 'success'){
if ($resData['status'] === 'success') {
$basket = \Drupal::hasService('Basket') ? \Drupal::service('Basket') : NULL;
// ---
if(!empty($payment->nid) && !empty($basket)) {
if(method_exists($basket, 'paymentFinish')) {
if (!empty($payment->nid) && !empty($basket)) {
if (method_exists($basket, 'paymentFinish')) {
$basket->paymentFinish($payment->nid);
}
}
// Alter
// Alter:
\Drupal::moduleHandler()->alter('monobank_api', $payment, $_POST);
// Trigger change payment status by order
if(!empty($payment->nid) && !empty($basket)){
$order = $basket->Orders(NULL, $payment->nid)->load();
if(!empty($order) && \Drupal::moduleHandler()->moduleExists('basket_noty')){
// Trigger change payment status by order:
if (!empty($payment->nid) && !empty($basket)) {
$order = $basket->orders(NULL, $payment->nid)->load();
if (!empty($order) && \Drupal::moduleHandler()->moduleExists('basket_noty')) {
\Drupal::service('BasketNoty')->trigger('change_monobank_status', [
'order' => $order
'order' => $order,
]);
}
}
......
......@@ -3,12 +3,13 @@
namespace Drupal\monobank\Plugin\Basket\Payment;
use Drupal\basket\Plugins\Payment\BasketPaymentInterface;
use Drupal\basket\Plugins\Payment\Annotation\BasketPayment;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\monobank\Form\PaymentForm;
use Drupal\monobank\Controller\Pages;
/**
* Class of BasketMonobank.
*
* @BasketPayment(
* id = "monobank",
* name = "Monobank",
......@@ -41,23 +42,23 @@ class BasketMonobank implements BasketPaymentInterface {
}
/**
* Alter for making adjustments when creating a payment item
* Alter for making adjustments when creating a payment item.
*/
public function settingsFormAlter(&$form, $form_state) {
$tid = $form['tid']['#value'];
$form['settings'] = [
'#type' => 'details',
'#title' => t('Settings'),
'#open' => TRUE,
'#open' => TRUE,
'#parents' => ['basket_payment_settings'],
'#tree' => TRUE,
'status' => [
'#type' => 'select',
'#type' => 'select',
'#title' => $this->monobank->t('Change order status after payment to'),
'#options' => $this->basket->Term()->getOptions('fin_status'),
'#empty_option' => $this->monobank->t('Do not change status'),
'#default_value' => $this->basket->getSettings('payment_settings', $tid.'.status')
]
'#empty_option' => $this->monobank->t('Do not change status'),
'#default_value' => $this->basket->getSettings('payment_settings', $tid . '.status'),
],
];
$form['#submit'][] = [$this, 'formSubmit'];
}
......@@ -65,9 +66,9 @@ class BasketMonobank implements BasketPaymentInterface {
/**
* Alter for making adjustments when creating a payment item (submit)
*/
public function formSubmit($form, $form_state){
public function formSubmit($form, $form_state) {
$tid = $form_state->getValue('tid');
if(!empty($tid)){
if (!empty($tid)) {
$this->basket->setSettings(
'payment_settings',
$tid,
......@@ -81,84 +82,106 @@ class BasketMonobank implements BasketPaymentInterface {
*/
public function getSettingsInfoList($tid) {
$items = [];
if(!empty($settings = $this->basket->getSettings('payment_settings', $tid))){
if (!empty($settings = $this->basket->getSettings('payment_settings', $tid))) {
$value = $this->monobank->t('Do not change status');
if(!empty($settings['status']) && !empty($term = $this->basket->Term()->load($settings['status']))){
$value = $this->basket->Translate()->t($term->name);
if (!empty($settings['status']) && !empty($term = $this->basket->term()->load($settings['status']))) {
$value = $this->basket->translate()->trans($term->name);
}
$items[] = [
'#type' => 'inline_template',
'#template' => '<b>{{ label }}: </b> {{ value }}',
'#context' => [
'label' => $this->monobank->t('Change order status after payment to'),
'value' => $value
]
'value' => $value,
],
];
}
return $items;
}
/**
* CreatePayment.
*
* Creation of payment
* return [
* 'payID' => 10,
* 'redirectUrl' => \Drupal::url('payment.routing')
* ];.
*/
public function createPayment($entity, $order) {
if(!empty($order->pay_price)){
if (!empty($order->pay_price)) {
$payment = $this->monobank->load([
'nid' => $entity->id(),
'create_new' => TRUE,
'amount' => $order->pay_price
'amount' => $order->pay_price,
]);
if(!empty($payment)){
if (!empty($payment)) {
return [
'payID' => $payment->id,
'redirectUrl' => NULL
'redirectUrl' => NULL,
];
}
}
return [
'payID' => NULL,
'redirectUrl' => NULL
'redirectUrl' => NULL,
];
}
/**
* Alter page redirects for payment
* LoadPayment.
*
* Downloading Payment Data
* return [
* 'payment' => object,
* 'isPay' => TRUE/FALSE
* ];.
*/
public function loadPayment($id) {
$payment = $this->monobank->load(['id' => $id]);
if(!empty($payment)){
if (!empty($payment)) {
return [
'payment' => $payment,
'isPay' => $payment->status != 'new' ? TRUE : FALSE
'payment' => $payment,
'isPay' => $payment->status != 'new' ? TRUE : FALSE,
];
}
}
/**
* Alter page redirects for payment
* Alter page redirects for payment.
*/
public function paymentFormAlter(&$form, $form_state, $payment) {
(new PaymentForm)->basketPaymentFormAlter($form, $form_state, $payment);
}
/**
* Alter processing pages of interaction between the payment system and the site
* BasketPaymentPages.
*
* Alter processing pages of interaction between
* the payment system and the site
* $pageType = callback/result/cancel.
*/
public function basketPaymentPages($pageType) {
return (new Pages)->pages('status');
}
/**
* Order update upon successful ordering by payment item settings
* Update order by settings.
*
* @param int $pid
* The product ID.
* @param object $orderClass
* The order class instance.
*/
public function updateOrderBySettings($pid, $orderClass) {
$order = $orderClass->load();
if(!empty($order) && !empty($settings = $this->basket->getSettings('payment_settings', $pid))){
if(!empty($settings['status'])){
if (!empty($order) && !empty($settings = $this->basket->getSettings('payment_settings', $pid))) {
if (!empty($settings['status'])) {
$order->fin_status = $settings['status'];
$orderClass->replaceOrder($order);
$orderClass->save();
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment