Completed
Push — development ( 227e3a...98bb7e )
by Andrij
14:37
created

Payment_method_walletone::getAdminForm()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 19
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
c 1
b 0
f 0
nc 3
nop 2
dl 19
loc 19
rs 9.4285
1
<?php
2
3
(defined('BASEPATH')) OR exit('No direct script access allowed');
4
5
/**
6
 * Image CMS
7
 * Module Frame
8
 */
9
class Payment_method_walletone extends MY_Controller
10
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
11
12
    public $paymentMethod;
13
14
    public $moduleName = 'payment_method_walletone';
15
16
    /**
17
     * @var array list of code => number pairs
18
     */
19
    private $currencyCodes = [];
20
21
    public function __construct() {
22
        parent::__construct();
23
        $lang = new MY_Lang();
24
        $lang->load('payment_method_walletone');
25
        $config = $this->load->config('payment_method_walletone');
26
        $this->currencyCodes = $config['currency_codes'];
27
28
    }
29
30
    public function index() {
31
        lang('walletone', 'payment_method_walletone');
32
    }
33
34
    /**
35
     * Вытягивает данные способа оплаты
36
     * @param str $key
37
     * @return array
38
     */
39 View Code Duplication
    private function getPaymentSettings($key) {
40
        $ci = &get_instance();
41
        $value = $ci->db->where('name', $key)
42
            ->get('shop_settings');
43
        if ($value) {
44
            $value = $value->row()->value;
45
        } else {
46
            show_error($ci->db->_error_message());
47
        }
48
        return unserialize($value);
49
    }
50
51
    /**
52
     * Вызывается при редактировании способов оплатыв админке
53
     * @param integer $id ид метода оплаты
54
     * @param string $payName название payment_method_liqpay
55
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
56
     */
57 View Code Duplication
    public function getAdminForm($id, $payName = null) {
58
59
        if (!$this->dx_auth->is_admin()) {
60
            redirect('/');
61
            exit;
62
        }
63
64
        $nameMethod = $payName ? $payName : $this->paymentMethod->getPaymentSystemName();
65
66
        $key = $id . '_' . $nameMethod;
67
        $data = $this->getPaymentSettings($key);
68
69
        $codeTpl = \CMSFactory\assetManager::create()
70
            ->setData('data', $data)
71
            ->setData('currencyCodes', $this->currencyCodes)
72
            ->fetchTemplate('adminForm');
73
74
        return $codeTpl;
75
    }
76
77
    //Конвертация в другую валюту
78
79 View Code Duplication
    public function convert($price, $currencyId) {
80
        if ($currencyId == \Currency\Currency::create()->getMainCurrency()->getId()) {
81
            $return['price'] = $price;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
82
            $return['code'] = \Currency\Currency::create()->getMainCurrency()->getCode();
83
            return $return;
84
        } else {
85
            $return['price'] = \Currency\Currency::create()->convert($price, $currencyId);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
86
            $return['code'] = \Currency\Currency::create()->getCodeById($currencyId);
87
            return $return;
88
        }
89
    }
90
91
    //Наценка
92
93 View Code Duplication
    public function markup($price, $percent) {
94
        $price = (float) $price;
95
        $percent = (float) $percent;
96
        $factor = $percent / 100;
97
        $residue = $price * $factor;
98
        return $price + $residue;
99
    }
100
101
    /**
102
     * Формирование кнопки оплаты
103
     * @param obj $param Данные о заказе
104
     * @return str
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
105
     */
106
    public function getForm($param) {
107
        $payment_method_id = $param->getPaymentMethod();
108
        $key = $payment_method_id . '_' . $this->moduleName;
109
        $paySettings = $this->getPaymentSettings($key);
110
111
        $merchant_id = $paySettings['merchant_id'];
112
        $signatureKey = $paySettings['electronic_signature'];
113
        $description = 'OrderId: ' . $param->id . '; Key: ' . $param->getKey();
114
        $price = $param->getDeliveryPrice() ? ($param->getTotalPrice() + $param->getDeliveryPrice()) : $param->getTotalPrice();
115
116
        $code = \Currency\Currency::create()->getMainCurrency()->getCode();
117
118 View Code Duplication
        if ($paySettings['merchant_currency']) {
119
            $arrPriceCode = $this->convert($price, $paySettings['merchant_currency']);
120
            $price = $arrPriceCode['price'];
121
            $code = $arrPriceCode['code'];
122
        }
123
124
        if ($paySettings['merchant_markup']) {
125
            $price = $this->markup($price, $paySettings['merchant_markup']);
126
        }
127
128
        if (array_key_exists($code, $this->currencyCodes)) {
129
130
            $fields = [];
131
            $fields['WMI_MERCHANT_ID'] = $merchant_id;
132
            $fields['WMI_PAYMENT_AMOUNT'] = strtr($price, [',' => '.']);
133
            $fields['WMI_CURRENCY_ID'] = $this->currencyCodes[$code];
134
            $fields['WMI_DESCRIPTION'] = 'BASE64:' . base64_encode($description);
135
            $fields['WMI_SUCCESS_URL'] = site_url() . 'shop/order/view/' . $param->getKey();
136
            $fields['WMI_FAIL_URL'] = site_url() . 'shop/order/view/' . $param->getKey();
137
            $fields['WMI_PAYMENT_NO'] = $param->id;
138
139
            foreach ($fields as $key => $value) {
140
                $fields[$key] = iconv('utf-8', 'windows-1251', $value);
141
            }
142
143
            $fields['WMI_SIGNATURE'] = $this->createSignature($fields, $signatureKey);
144
145
            $codeTpl = \CMSFactory\assetManager::create()
146
                ->setData('fields', $fields)
147
                ->fetchTemplate('form');
148
149
            return $codeTpl;
150
        }
151
    }
152
153
    /**
154
     * @param array $fields
155
     * @param $key
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
156
     * @return string
157
     */
158
    private function createSignature(array $fields, $key) {
159
160
        uksort($fields, 'strcasecmp');
161
162
        $fieldValues = '';
163
164
        foreach ($fields as $value) {
165
            $fieldValues .= $value;
166
        }
167
168
        $signature = base64_encode(pack('H*', md5($fieldValues . $key)));
169
170
        return $signature;
171
    }
172
173
    /**
174
     * Метод куда система шлет статус заказа
175
     */
176
    public function callback() {
177
        if ($_POST) {
0 ignored issues
show
introduced by
The $_POST super global must not be accessed directly; use Security::getRequestData() instead
Loading history...
178
            $this->checkPaid($_POST);
0 ignored issues
show
introduced by
The $_POST super global must not be accessed directly; use Security::getRequestData() instead
Loading history...
179
        }
180
    }
181
182
    /**
183
     * Метов обработке статуса заказа
184
     * @param array $param пост от метода callback
185
     */
186
    private function checkPaid($param) {
187
        $ci = &get_instance();
188
        $order_id = $param['WMI_PAYMENT_NO'];
189
        $userOrder = $ci->db->where('id', $order_id)
190
            ->get('shop_orders');
191
        if ($userOrder) {
192
            $userOrder = $userOrder->row();
193
        } else {
194
            show_error($ci->db->_error_message());
195
        }
196
        $key = $userOrder->payment_method . '_' . $this->moduleName;
197
        $paySettings = $this->getPaymentSettings($key);
198
199
        $signatureKey = $paySettings['electronic_signature'];
200
201
        if ($this->validateData($param, $signatureKey)) {
202
            $this->successPaid($order_id, $userOrder);
203
            redirect(site_url() . 'shop/order/view/' . $userOrder->key);
204
        }
205
    }
206
207
    private function validateData($data, $signatureKey) {
208
209
        $fields = [];
210
        foreach ($data as $name => $value) {
211
            if ($name !== 'WMI_SIGNATURE') { $fields[$name] = $value;
0 ignored issues
show
introduced by
Expected "if (...) {\n"; found "if (...) { "
Loading history...
introduced by
There should be no white space after an opening "{"
Loading history...
212
            }
213
        }
214
215
        if ($data['WMI_SIGNATURE'] == $this->createSignature($fields, $signatureKey)) {
216
            if (strtoupper($data['WMI_ORDER_STATE']) == 'ACCEPTED') {
217
218
                $this->printAnswer('Ok', 'Заказ #' . $data['WMI_PAYMENT_NO'] . ' оплачен!');
219
                return true;
220
221
            } else {
222
                $this->printAnswer('Retry', 'Неверное состояние ' . $data['WMI_ORDER_STATE']);
223
            }
224
        } else {
225
            $this->printAnswer('Retry', 'Неверная подпись ' . $data['WMI_SIGNATURE']);
226
        }
227
        return false;
228
229
    }
230
231
    private function printAnswer($result, $description) {
232
        print 'WMI_RESULT=' . strtoupper($result) . '&';
233
        print 'WMI_DESCRIPTION=' . urlencode($description);
234
    }
235
236
    /**
237
     * Save settings
238
     *
239
     * @return bool|string
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use boolean.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
240
     */
241 View Code Duplication
    public function saveSettings(SPaymentMethods $paymentMethod) {
242
        $saveKey = $paymentMethod->getId() . '_' . $this->moduleName;
243
244
        \ShopCore::app()->SSettings->set($saveKey, serialize($_POST['payment_method_walletone']));
245
246
        return true;
247
    }
248
249
    /**
250
     * Переводит статус заказа в оплачено, и прибавляет пользователю
251
     * оплеченную сумму к акаунту
252
     * @param integer $order_id ид заказа который обрабатывается
253
     * @param obj $userOrder данные заказа
254
     */
255 View Code Duplication
    public function successPaid($order_id, $userOrder) {
256
        $ci = &get_instance();
257
        $amount = $ci->db->select('amout')
258
            ->get_where('users', ['id' => $userOrder->user_id]);
259
260
        if ($amount) {
261
            $amount = $amount->row()->amout;
262
        } else {
263
            show_error($ci->db->_error_message());
264
        }
265
266
        $amount += $userOrder->total_price;
267
268
        $result = $ci->db->where('id', $order_id)
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
269
            ->update('shop_orders', ['paid' => '1', 'date_updated' => time()]);
270
        if ($ci->db->_error_message()) {
271
            show_error($ci->db->_error_message());
272
        }
273
        \CMSFactory\Events::create()->registerEvent(['system' => __CLASS__, 'order_id' => $order_id], 'PaimentSystem:successPaid');
274
        \CMSFactory\Events::runFactory();
275
276
        $result = $ci->db
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
277
            ->where('id', $userOrder->user_id)
278
            ->limit(1)
279
            ->update(
280
                'users',
281
                [
282
                 'amout' => str_replace(',', '.', $amount),
283
                ]
284
            );
285
        if ($ci->db->_error_message()) {
286
            show_error($ci->db->_error_message());
287
        }
288
    }
289
290
    public function autoload() {
291
292
    }
293
294 View Code Duplication
    public function _install() {
295
        $ci = &get_instance();
296
297
        $result = $ci->db->where('name', $this->moduleName)
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
298
            ->update('components', ['enabled' => '1']);
299
        if ($ci->db->_error_message()) {
300
            show_error($ci->db->_error_message());
301
        }
302
    }
303
304 View Code Duplication
    public function _deinstall() {
305
        $ci = &get_instance();
306
307
        $result = $ci->db->where('payment_system_name', $this->moduleName)
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
308
            ->update(
309
                'shop_payment_methods',
310
                [
311
                 'active'              => '0',
312
                 'payment_system_name' => '0',
313
                ]
314
            );
315
        if ($ci->db->_error_message()) {
316
            show_error($ci->db->_error_message());
317
        }
318
319
        $result = $ci->db->like('name', $this->moduleName)
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
320
            ->delete('shop_settings');
321
        if ($ci->db->_error_message()) {
322
            show_error($ci->db->_error_message());
323
        }
324
    }
325
326
}
327
328
/* End of file sample_module.php */