Completed
Push — master ( bc690a...7dcdf7 )
by Dmitry
04:54
created

PayController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 6.67%

Importance

Changes 0
Metric Value
wmc 18
lcom 2
cbo 8
dl 0
loc 131
ccs 4
cts 60
cp 0.0667
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A actions() 0 13 2
A getMerchantModule() 0 4 1
A render() 0 4 1
B checkNotify() 0 59 8
A actionProxyNotification() 0 13 1
A completeTransaction() 0 22 5
1
<?php
2
/**
3
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\controllers;
12
13
use hipanel\modules\finance\models\Merchant;
14
use hiqdev\hiart\ResponseErrorException;
15
use hiqdev\yii2\merchant\actions\RequestAction;
16
use hiqdev\yii2\merchant\events\TransactionInsertEvent;
17
use hiqdev\yii2\merchant\transactions\Transaction;
18
use function is_array;
19
use Yii;
20
use yii\base\InvalidParamException;
21
use yii\helpers\Json;
22
23
/**
24
 * Class PayController.
25
 *
26
 * @property \hipanel\modules\finance\Module $module
27
 */
28
class PayController extends \hiqdev\yii2\merchant\controllers\PayController
29
{
30
    const SESSION_MERCHANT_LATEST_TRANSACTION_ID = 'MERCHANT_LATEST_TRANSACTION_ID';
31 1
32
    public function actions()
33 1
    {
34 1
        return array_merge(parent::actions(), [
35
            'request' => [
36
                'class' => RequestAction::class,
37
                'on ' . RequestAction::EVENT_AFTER_TRANSACTION_INSERT => function (TransactionInsertEvent $event) {
38
                    if ($event->transaction instanceof Transaction) {
39
                        Yii::$app->session->set(self::SESSION_MERCHANT_LATEST_TRANSACTION_ID, $event->transaction->getId());
40 1
                    }
41
                },
42
            ],
43
        ]);
44
    }
45
46
    public function getMerchantModule()
47
    {
48
        return $this->module->getMerchant();
49
    }
50
51
    public function render($view, $params = [])
52
    {
53
        return $this->getMerchantModule()->getPayController()->render($view, $params);
54
    }
55
56
    public function checkNotify(string $transactionId = null): ?Transaction
57
    {
58
        $transactionIdSources = [
59
            $transactionId,
60
            Yii::$app->request->get('transactionId'),
61
            Yii::$app->request->post('transactionId'),
62
            Yii::$app->session->get(self::SESSION_MERCHANT_LATEST_TRANSACTION_ID),
63
            Yii::$app->request->get('orderId'),
64
            Yii::$app->request->post('orderId'),
65
        ];
66
67
        foreach (array_filter($transactionIdSources) as $possibleTransactionId) {
68
            $transaction = $this->getMerchantModule()->findTransaction($possibleTransactionId);
69
            if ($transaction !== null) {
70
                break;
71
            }
72
        }
73
74
        /** @noinspection UnSafeIsSetOverArrayInspection */
75
        if (!isset($transaction)) {
76
            return null;
77
        }
78
79
        $data = array_merge([
80
            'merchant' => $transaction->getMerchant(),
81
            'username' => $transaction->getParameter('username'),
82
        ], $_REQUEST);
83
        Yii::info(http_build_query($data), 'merchant');
84
85
        if (($input = file_get_contents('php://input')) !== null) {
86
            try {
87
                $data['rawBody'] = Json::decode($input);
88
            } catch (InvalidParamException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
89
            }
90
        }
91
92
        try {
93
            return Yii::$app->get('hiart')->callWithDisabledAuth(function () use ($transaction, $data) {
94
                $result = Merchant::perform('pay-transaction', $data);
95
                $this->completeTransaction($transaction, $result);
96
97
                return $transaction;
98
            });
99
        } catch (ResponseErrorException $e) {
100
        } // Does not matter, let's try the old way then.
101
102
        try {
103
            return Yii::$app->get('hiart')->callWithDisabledAuth(function () use ($transaction, $data) {
104
                $result = Merchant::perform('pay', $data);
105
                $this->completeTransaction($transaction, $result);
106
107
                return $transaction;
108
            });
109
        } catch (ResponseErrorException $e) {
110
        } // Still no luck? Then it's not the right request.
111
112
113
        return $transaction;
114
    }
115
116
    public function actionProxyNotification()
117
    {
118
        // Currently used at least for FreeKassa integration
119
        $data = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
120
121
        $result = Yii::$app->get('hiart')->callWithDisabledAuth(function () use ($data) {
122
            return Merchant::perform('pay-transaction', $data);
123
        });
124
125
        $this->layout = false;
126
127
        return $result;
128
    }
129
130
    /**
131
     * @param Transaction $transaction
132
     * @param string|array $response
133
     * @return Transaction
134
     * @throws \yii\base\ExitException
135
     */
136
    protected function completeTransaction($transaction, $response)
137
    {
138
        if ($transaction->isCompleted() || isset($response['_error'])) {
139
            return $transaction;
140
        }
141
142
        if ($response === '"OK"') {
143
            echo $response;
144
            Yii::$app->end();
145
        }
146
147
        if (!is_array($response)) {
148
            return $transaction;
149
        }
150
151
        $transaction->complete();
152
        $transaction->addParameter('bill_id', $response['id']);
153
154
        $this->getMerchantModule()->saveTransaction($transaction);
155
156
        return $transaction;
157
    }
158
}
159