Completed
Push — master ( eccc2c...9c0ef3 )
by Vuong
01:43
created

PaymentGateway::requestInternal()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 38
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 4.0009

Importance

Changes 0
Metric Value
dl 0
loc 38
ccs 25
cts 26
cp 0.9615
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 29
nc 4
nop 2
crap 4.0009
1
<?php
2
/**
3
 * @link https://github.com/yiiviet/yii2-payment
4
 * @copyright Copyright (c) 2017 Yii Viet
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace yiiviet\payment\baokim;
9
10
use yii\base\NotSupportedException;
11
use yii\di\Instance;
12
use yii\helpers\ArrayHelper;
13
14
use yiiviet\payment\BasePaymentGateway;
15
16
use vxm\gatewayclients\RequestEvent;
17
use vxm\gatewayclients\DataInterface;
18
19
20
/**
21
 * Lớp PaymentGateway thực thi các phương thức trừu tượng dùng hổ trợ kết nối đến Bảo Kim.
22
 * Hiện tại nó hổ trợ 100% các tính năng từ cổng thanh toán Bảo Kim.
23
 *
24
 * @method ResponseData purchase(array $data, $clientId = null)
25
 * @method ResponseData queryDR(array $data, $clientId = null)
26
 * @method bool|VerifiedData verifyRequestPurchaseSuccess($clientId = null, \yii\web\Request $request = null)
27
 * @method PaymentClient getClient($id = null)
28
 * @method PaymentClient getDefaultClient()
29
 *
30
 * @property PaymentClient $client
31
 * @property PaymentClient $defaultClient
32
 *
33
 * @author Vuong Minh <[email protected]>
34
 * @since 1.0
35
 */
36
class PaymentGateway extends BasePaymentGateway
37
{
38
    /**
39
     * Lệnh `getMerchantData` sử dụng cho việc tạo [[request()]] yêu cầu thông tin merchant.
40
     */
41
    const RC_GET_MERCHANT_DATA = 'getMerchantData';
42
43
    /**
44
     * @event RequestEvent được gọi trước khi tạo yêu câu lấy thông tin merchant.
45
     */
46
    const EVENT_BEFORE_GET_MERCHANT_DATA = 'beforeGetMerchantData';
47
48
    /**
49
     * @event RequestEvent được gọi sau khi tạo yêu câu lấy thông tin merchant.
50
     */
51
    const EVENT_AFTER_GET_MERCHANT_DATA = 'afterGetMerchantData';
52
53
    /**
54
     * Đường dẫn API của thanh toán Bảo Kim.
55
     */
56
    const PURCHASE_URL = '/payment/order/version11';
57
58
    /**
59
     * Đường dẫn API của thanh toán PRO.
60
     */
61
    const PURCHASE_PRO_URL = '/payment/rest/payment_pro_api/pay_by_card';
62
63
    /**
64
     * Đường dẫn API để lấy thông tin merchant.
65
     */
66
    const PRO_SELLER_INFO_URL = '/payment/rest/payment_pro_api/get_seller_info';
67
68
    /**
69
     * Đường dẫn API để truy vấn thông tin giao dịch.
70
     */
71
    const QUERY_DR_URL = '/payment/order/queryTransaction';
72
73
    /**
74
     * Đường dẫn API IPN của Bảo Kim để cập nhật và xác minh dữ liệu từ IPN request từ Bảo Kim bắn sang.
75
     * Nói cách khác là sẽ có 2 IPN, 1 cái nằm trên server của bạn và 1 cái là của Bảo Kim để cập nhật đơn hàng của họ.
76
     */
77
    const VERIFY_IPN_URL = '/bpn/verify';
78
79
    /**
80
     * MUI thuộc tính trong mảng data khi tạo thanh toán PRO, cho phép chỉ định giao diện hiển thị charge.
81
     */
82
    const MUI_CHARGE = 'charge';
83
84
    /**
85
     * MUI thuộc tính trong mảng data khi tạo thanh toán PRO, cho phép chỉ định giao diện hiển thị base.
86
     */
87
    const MUI_BASE = 'base';
88
89
    /**
90
     * MUI thuộc tính trong mảng data khi tạo thanh toán PRO, cho phép chỉ định giao diện hiển thị iframe.
91
     */
92
    const MUI_IFRAME = 'iframe';
93
94
    /**
95
     * Transaction mode direct là thuộc tính khi tạo thanh toán Bảo Kim và PRO, cho phép chỉ định giao dịch trực tiếp.
96
     */
97
    const DIRECT_TRANSACTION = 1;
98
99
    /**
100
     * Transaction mode safe là thuộc tính khi tạo thanh toán Bảo Kim và PRO, cho phép chỉ định giao dịch tạm giữ.
101
     */
102
    const SAFE_TRANSACTION = 2;
103
104
    /**
105
     * @var bool Set it TRUE if you want use gateway with pro mode. Currently only method `purchase` is depend on it.
106
     */
107
    public $pro = false;
108
109
    /**
110
     * @see getMerchantData
111
     * @var bool|string|array|\yii\caching\Cache Hổ trợ cho việc cache lại dữ liệu merchant lấy từ Bảo Kim nhầm tối ưu hóa hệ thống
112
     * do dữ liệu này ít khi bị thay đổi.
113
     */
114
    public $merchantDataCache = 'cache';
115
116
    /**
117
     * @var int Thời gian cache dữ liệu của merchant lấy từ Bảo Kim.
118
     */
119
    public $merchantDataCacheDuration = 86400;
120
121
    /**
122
     * @inheritdoc
123
     */
124
    public $clientConfig = ['class' => PaymentClient::class];
125
126
    /**
127
     * @inheritdoc
128
     */
129
    public $requestDataConfig = ['class' => RequestData::class];
130
131
    /**
132
     * @inheritdoc
133
     */
134
    public $responseDataConfig = ['class' => ResponseData::class];
135
136
    /**
137
     * @inheritdoc
138
     */
139
    public $verifiedDataConfig = ['class' => VerifiedData::class];
140
141
    /**
142
     * @inheritdoc
143
     */
144 5
    public function getBaseUrl(): string
145
    {
146 5
        return $this->sandbox ? 'https://sandbox.baokim.vn' : 'https://www.baokim.vn';
147
    }
148
149
    /**
150
     * @throws \yii\base\InvalidConfigException
151
     * @inheritdoc
152
     */
153 7
    public function init()
154
    {
155 7
        if ($this->merchantDataCache) {
156 7
            $this->merchantDataCache = Instance::ensure($this->merchantDataCache, 'yii\caching\Cache');
157
        }
158
159 7
        parent::init();
160 7
    }
161
162
    /**
163
     * @inheritdoc
164
     * @throws \yii\base\InvalidConfigException
165
     */
166 7
    protected function initSandboxEnvironment()
167
    {
168 7
        $clientConfig = require(__DIR__ . '/sandbox-client.php');
169 7
        $this->setClient($clientConfig);
170 7
    }
171
172
    /**
173
     * @inheritdoc
174
     */
175 5 View Code Duplication
    protected function getHttpClientConfig(): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
    {
177
        return [
178 5
            'transport' => 'yii\httpclient\CurlTransport',
179
            'requestConfig' => [
180 5
                'format' => 'json',
181
                'options' => [
182 5
                    CURLOPT_SSL_VERIFYHOST => false,
183 5
                    CURLOPT_SSL_VERIFYPEER => false
184
                ]
185
            ]
186
        ];
187
    }
188
189
    /**
190
     * Phương thức hổ trợ lấy thông tin merchant thông qua email business.
191
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_GET_MERCHANT_DATA]].
192
     *
193
     * @param string $emailBusiness Email muốn lấy thông tin từ Bảo Kim.
194
     * @param int|string|null $clientId PaymentClient id sử dụng để lấy thông tin.
195
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
196
     * @throws \ReflectionException|\yii\base\InvalidConfigException
197
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu của emailBusiness từ Bảo Kim phản hồi.
198
     */
199 1
    public function getMerchantData(string $emailBusiness = null, $clientId = null): DataInterface
200
    {
201
        /** @var PaymentClient $client */
202 1
        $client = $this->getClient($clientId);
203
        $cacheKey = [
204 1
            __METHOD__,
205 1
            get_class($client),
206 1
            $client->merchantId,
207 1
            $emailBusiness
208
        ];
209
210 1
        if (!$this->merchantDataCache || !($responseData = $this->merchantDataCache->get($cacheKey))) {
211 1
            $responseData = $this->request(self::RC_GET_MERCHANT_DATA, [
212 1
                'business' => $emailBusiness ?? $client->merchantEmail
213 1
            ], $clientId);
214
215 1
            if ($this->merchantDataCache) {
216 1
                $this->merchantDataCache->set($cacheKey, $responseData, $this->merchantDataCacheDuration);
217
            }
218
        }
219
220 1
        return $responseData;
221
    }
222
223
    /**
224
     * @inheritdoc
225
     */
226 4
    public function beforeRequest(RequestEvent $event)
227
    {
228 4
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
229 1
            $this->trigger(self::EVENT_BEFORE_GET_MERCHANT_DATA, $event);
230
        }
231
232 4
        parent::beforeRequest($event);
233 4
    }
234
235
    /**
236
     * @inheritdoc
237
     */
238 3
    public function afterRequest(RequestEvent $event)
239
    {
240 3
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
241 1
            $this->trigger(self::EVENT_AFTER_GET_MERCHANT_DATA, $event);
242
        }
243
244 3
        parent::afterRequest($event);
245 3
    }
246
247
    /**
248
     * @inheritdoc
249
     * @throws \yii\base\InvalidConfigException
250
     */
251 4
    protected function requestInternal(\vxm\gatewayclients\RequestData $requestData, \yii\httpclient\Client $httpClient): array
252
    {
253
        /** @var PaymentClient $client */
254 4
        $client = $requestData->getClient();
255 4
        $command = $requestData->getCommand();
256 4
        $data = $requestData->get();
257 3
        $httpMethod = 'POST';
258
259 3
        if (in_array($command, [self::RC_GET_MERCHANT_DATA, self::RC_QUERY_DR], true)) {
260 2
            if ($command === self::RC_GET_MERCHANT_DATA) {
261 1
                $url = self::PRO_SELLER_INFO_URL;
262
            } else {
263 1
                $url = self::QUERY_DR_URL;
264
            }
265 2
            $data[0] = $url;
266 2
            $url = $data;
267 2
            $data = null;
268 2
            $httpMethod = 'GET';
269
        } else {
270 1
            if ($this->pro) {
271
                $url = [self::PURCHASE_PRO_URL, 'signature' => ArrayHelper::remove($data, 'signature')];
272
            } else {
273 1
                $data[0] = self::PURCHASE_URL;
274 1
                return ['redirect_url' => $httpClient->get($data)->getFullUrl()];
275
            }
276
        }
277
278 2
        return $httpClient->createRequest()
279 2
            ->setUrl($url)
280 2
            ->setMethod($httpMethod)
281 2
            ->addOptions([
282 2
                CURLOPT_HTTPAUTH => CURLAUTH_DIGEST | CURLAUTH_BASIC,
283 2
                CURLOPT_USERPWD => $client->apiUser . ':' . $client->apiPassword
284
            ])
285 2
            ->addData($data)
286 2
            ->send()
287 2
            ->getData();
288
    }
289
290
    /**
291
     * @inheritdoc
292
     * @return bool|VerifiedData|DataInterface
293
     */
294 1
    public function verifyRequestIPN($clientId = null, \yii\web\Request $request = null)
295
    {
296 1
        if ($request === null) {
297 1
            $request = Instance::ensure('request', '\yii\web\Request');
298
        }
299
300 1
        $content = $this->getHttpClient()->post(self::VERIFY_IPN_URL, $request->post())->send()->getContent();
301
302 1
        if (strpos($content, 'VERIFIED') !== false) {
303
            return parent::verifyRequestIPN($clientId, $request);
304
        } else {
305 1
            return false;
306
        }
307
    }
308
309
    /**
310
     * @inheritdoc
311
     */
312 1
    protected function getVerifyRequestData($command, \yii\web\Request $request): array
313
    {
314
        $params = [
315 1
            'order_id', 'transaction_id', 'created_on', 'payment_type', 'transaction_status', 'total_amount', 'net_amount',
316
            'fee_amount', 'merchant_id', 'customer_name', 'customer_email', 'customer_phone', 'customer_address', 'checksum',
317
            'payer_name', 'payer_email', 'payer_phone_no', 'shipping_address', 'verify_sign', 'resend'
318
        ];
319 1
        $commandRequestMethods = [self::VRC_PURCHASE_SUCCESS => 'get', self::VRC_IPN => 'post'];
320 1
        $requestMethod = $commandRequestMethods[$command];
321 1
        $data = [];
322
323 1 View Code Duplication
        foreach ($params as $param) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
324 1
            if (($value = call_user_func([$request, $requestMethod], $param)) !== null) {
325 1
                $data[$param] = $value;
326
            }
327
        }
328
329 1
        return $data;
330
    }
331
332
}
333