-
Notifications
You must be signed in to change notification settings - Fork 1
/
payme-hook.php
525 lines (423 loc) · 13.9 KB
/
payme-hook.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('BILLING_MODULE', 1);
include './payme/AbstractPayme.php';
include './payme/DbTransactionProvider.php';
class Payme extends AbstractPayme
{
/**
* List fields
*
* @var array $accounts
*/
protected $accounts = ["order"];
/**
* Table of transactions
*
* @var string $tableName
*/
protected $tableName = "payme_uz";
/**
* Min summ
*
* @var int $minSum
*/
protected $minSum = 1000;
/**
* Max summ
*
* @var int $maxSum
*/
protected $maxSum = 100000;
/**
* Transaction timeout
*
* @var int $timeout
*/
protected $timeout = 6000 * 1000;
/**
* @var bool $canCancelSuccessTransaction
*/
protected $canCancelSuccessTransaction = false;
/**
* User primaryKey
*
* @var string $userKey
*/
protected $userKey = "order";
private $config = [
'merchant' => 'merchant-id',
'login' => 'Paycom',
'key' => 'merchant-key',
'test_key' => 'merchant-key',
];
/**
* Pdo object
* @var PDO
*/
private $pdo;
/**
* Wallet constructor.
* @param string $request JSON request
*/
public function __construct($request)
{
file_put_contents('./log.txt', $request);
$host = 'db-host';
$db = 'db-name';
$user = 'db-user';
$pass = 'db-password';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
parent::__construct($request, new DbTransactionProvider($this->tableName, $pdo));
$this->pdo = $pdo;
}
/**
* @return bool
*/
public function auth()
{
$headers = getallheaders();
if (!$headers ||
!isset($headers['Authorization']) ||
!preg_match('/^\s*Basic\s+(\S+)\s*$/i', $headers['Authorization'], $matches) ||
base64_decode($matches[1]) != $this->config['login'] . ":" . $this->config['key']
) {
return false;
}
return true;
}
/**
* Transaksiya otkazib bolish imkoniyatini tekshiradi
*
* @return array
*/
protected function checkPerformTransaction()
{
// check auth
if (!$this->auth()) {
return $this->response->error(PaymeResponse::AUTH_ERROR);
}
// Check account fields
if (!$this->request->hasAccounts($this->accounts) || !$this->request->hasParam(["amount"])) {
return $this->response->error(PaymeResponse::JSON_RPC_ERROR);
}
// Get vars
$accounts = $this->request->getParam('account');
$amount = $this->getAmount($this->request->getParam("amount"));
// check order
// Ushbu proverka sestemaga bogliq zakaz yoki polzvatel pul qabul qila oladimi yoki yuq ?
$invoice = $this->getInvoice($accounts['order']);
if (!$invoice) {
return $this->response->error(PaymeResponse::USER_NOT_FOUND);
}
// Check amount
if (!$this->isValidAmount($invoice['invoice_pay'], $amount)) {
return $this->response->error(PaymeResponse::WRONG_AMOUNT);
}
// Success
return $this->response->successCheckPerformTransaction();
}
/**
* Transaksiya yaratadi
*
* @return array
*/
protected function createTransaction()
{
// check auth
if (!$this->auth()) {
return $this->response->error(PaymeResponse::AUTH_ERROR);
}
// Check account fields
if (!$this->request->hasAccounts($this->accounts) || !$this->request->hasParam(["amount", "time", "id"])) {
return $this->response->error(PaymeResponse::JSON_RPC_ERROR);
}
$accounts = $this->request->getParam('account');
$amount = $this->getAmount($this->request->getParam("amount"));
$transId = $this->request->getParam("id");
$time = $this->request->getParam("time");
// get transaction
$trans = $this->provider->getByTransId($transId);
if ($trans) {
// check state
if ($trans['state'] != 1) {
return $this->response->error(PaymeResponse::CANT_PERFORM_TRANS);
}
// check timeout
if (!$this->checkTimeout($trans['create_time'])) {
$this->provider->update($transId, [
"state" => -1,
"reason" => 4
]);
return $this->response->error(PaymeResponse::CANT_PERFORM_TRANS, [
"uz" => "Vaqt tugashi o'tdi",
"ru" => "Тайм-аут прошел",
"en" => "Timeout passed"
]);
}
return $this->response->successCreateTransaction(
$trans['create_time'],
$trans['id'],
$trans['state']
);
}
// check perform transaction
// check order
$invoice = $this->getInvoice($accounts[$this->userKey]);
if (!$invoice) {
return $this->response->error(PaymeResponse::USER_NOT_FOUND);
}
// Check amount
if (!$this->isValidAmount($invoice['invoice_pay'], $amount)) {
return $this->response->error(PaymeResponse::WRONG_AMOUNT);
}
// check order status
$trans = $this->provider->getByOwnerId($accounts[$this->userKey]);
if ($trans && $trans['state'] == 1) {
return $this->response->error(PaymeResponse::PENDING_PAYMENT);
}
// Add new transaction
try {
$this->provider->insert([
'transaction' => $transId,
'payme_time' => $time,
'amount' => $amount,
'state' => 1,
'create_time' => $this->microtime(),
'owner_id' => $accounts[$this->userKey],
]);
$trans = $this->provider->getByTransId($transId);
return $this->response->successCreateTransaction($trans['create_time'], $trans['id'], $trans['state']);
} catch (\Exception $e) {
return $this->response->error(PaymeResponse::SYSTEM_ERROR);
}
}
/**
* Transaksiyani utqazish va foydalanuvchi hisobiga pul otqazish
*
* @return array
*/
protected function performTransaction()
{
// check auth
if (!$this->auth()) {
return $this->response->error(PaymeResponse::AUTH_ERROR);
}
// Check fields
if (!$this->request->hasParam(["id"])) {
return $this->response->error(PaymeResponse::JSON_RPC_ERROR);
}
// Search by id
$transId = $this->request->getParam('id');
$trans = $this->provider->getByTransId($transId);
if (!$trans) {
return $this->response->error(PaymeResponse::TRANS_NOT_FOUND);
}
if ($trans['state'] != 1) {
if ($trans['state'] == 2) {
return $this->response->successPerformTransaction($trans['state'], $trans['perform_time'], $trans['id']);
} else {
return $this->response->error(PaymeResponse::CANT_PERFORM_TRANS);
}
}
// Check timeout
if (!$this->checkTimeout($trans['create_time'])) {
$this->provider->update($transId, [
"state" => -1,
"reason" => 4
]);
return $this->response->error(PaymeResponse::CANT_PERFORM_TRANS, [
"uz" => "Vaqt tugashi o'tdi",
"ru" => "Тайм-аут прошел",
"en" => "Timeout passed"
]);
}
try {
$this->fillUpBalance($trans['owner_id'], $trans['amount']);
$performTime = $this->microtime();
$this->provider->update($transId, [
"state" => 2,
"perform_time" => $performTime
]);
return $this->response->successPerformTransaction(2, $performTime, $trans['id']);
} catch (\Exception $e) {
return $this->response->error(PaymeResponse::CANT_PERFORM_TRANS);
}
}
/**
* Transaksiyani statusini tekshiradi
*
* @return array
*/
protected function checkTransaction()
{
// check auth
if (!$this->auth()) {
return $this->response->error(PaymeResponse::AUTH_ERROR);
}
// Check fields
if (!$this->request->hasParam(["id"])) {
return $this->response->error(PaymeResponse::JSON_RPC_ERROR);
}
$transId = $this->request->getParam("id");
$trans = $this->provider->getByTransId($transId);
if ($trans) {
return $this->response->successCheckTransaction(
$trans['create_time'],
$trans['perform_time'],
$trans['cancel_time'],
$trans['id'],
$trans['state'],
$trans['reason']
);
} else {
return $this->response->error(PaymeResponse::TRANS_NOT_FOUND);
}
}
/**
* Transaksiyani qaytarish va foydalanuvchi hisobidan yechib olish
*
* @return array
*/
protected function cancelTransaction()
{
// check auth
if (!$this->auth()) {
return $this->response->error(PaymeResponse::AUTH_ERROR);
}
// Check fields
if (!$this->request->hasParam(["id", "reason"])) {
return $this->response->error(PaymeResponse::JSON_RPC_ERROR);
}
$transId = $this->request->getParam("id");
$reason = $this->request->getParam("reason");
$trans = $this->provider->getByTransId($transId);
if (!$trans) {
$this->response->error(PaymeResponse::TRANS_NOT_FOUND);
}
if ($trans['state'] == 1) {
$cancelTime = $this->microtime();
$this->provider->update($transId, [
"state" => -1,
"cancel_time" => $cancelTime,
"reason" => $reason
]);
return $this->response->successCancelTransaction(-1, $cancelTime, $trans['id']);
}
if ($trans['state'] != 2) {
return $this->response->successCancelTransaction($trans['state'], $trans['cancel_time'], $trans['id']);
}
try {
$this->withdrawBalance($trans['owner_id'], $trans['amount']);
$cancelTime = $this->microtime();
$this->provider->update($transId, [
"state" => -2,
"cancel_time" => $cancelTime,
"reason" => $reason
]);
return $this->response->successCancelTransaction(-2, $cancelTime, $trans['id']);
} catch (\Exception $e) {
return $this->response->error(PaymeResponse::CANT_CANCEL_TRANSACTION);
}
}
/**
* Hozircha bu metod hech narsa qilmaydi, lekin keyin albatta qilaman
*/
public function getStatement()
{
// TODO: Implement GetStatement() method.
}
/**
* Bu metod parolni uzgartirish uchun kk
*/
protected function changePassword()
{
// TODO: Implement ChangePassword() method.
}
// helpers
/**
* Foydalanuvchi hisobiga pul otqazish
*
* @param $owner_id
* @param $amount
* @throws \Exception
*/
private function fillUpBalance($owner_id, $amount)
{
// buyurtmani olamiz
$invoice = $this->getInvoice($owner_id);
if (!$invoice) {
throw new \Exception("Can't find order");
}
// buyurtmani tolandi db belgilash
$this->pdo->query("UPDATE `dle_billing_invoice` SET `invoice_date_pay` = '".time()."' WHERE invoice_id = {$owner_id}");
$this->pdo->query("UPDATE `dle_users` SET `user_balance` = (user_balance + '{$amount}') WHERE name = '{$invoice['invoice_user_name']}'");
}
/**
* Foydalanuvchi hisobidan pul yechish
*
* @param $owner_id
* @param $amount
* @throws \Exception
*/
private function withdrawBalance($owner_id, $amount)
{
// buyurtmani olamiz
$invoice = $this->getInvoice($owner_id);
if (!$invoice) {
throw new \Exception("Can't find order");
}
// buyurtmani tolandi db belgilash
$this->pdo->query("UPDATE `dle_billing_invoice` SET `invoice_date_pay` = '0' WHERE invoice_id = {$owner_id}");
$this->pdo->query("UPDATE `dle_users` SET `user_balance` = (user_balance - '{$amount}') WHERE name = '{$invoice['invoice_user_name']}'");
}
/**
* Transaksiyani tekshiradi timeoutga qarab
*
* @param $created_time
* @return bool
*/
private function checkTimeout($created_time)
{
return $this->microtime() <= ($created_time + $this->timeout);
}
/**
* Oddiy helper prosta akkount yoki zakazni olish uchun
*
* @param $id
* @return null|array
*/
private function getInvoice($id) {
return $this->pdo->query("SELECT * FROM dle_billing_invoice WHERE invoice_id = '{$id}' ")
->fetch();
}
/**
* @param $clientAmount
* @param $paymeAmount
* @return bool
*/
private function isValidAmount($clientAmount, $paymeAmount) {
return $clientAmount == $paymeAmount;
}
/**
* @param $amount
* @return float|int
*/
private function getAmount($amount) {
return $amount / 100;
}
}
$data = file_get_contents("php://input");
if ($data) {
$response = (new Payme($data))->response();
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($response);
}