Completed
Push — master ( 1ddc55...552a80 )
by Vuong
02:04
created

PaymentGateway::verifiedRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 6
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\di\Instance;
11
use yii\helpers\ArrayHelper;
12
13
use yiiviet\payment\BasePaymentGateway;
14
use yiiviet\payment\VerifiedRequestEvent;
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 VerifiedData verifyRequestIPN($clientId = null, \yii\web\Request $request = null)
27
 * @method VerifiedData verifyRequestPurchaseSuccess($clientId = null, \yii\web\Request $request = null)
28
 *
29
 * @property PaymentClient $client
30
 * @property PaymentClient $defaultClient
31
 *
32
 * @author Vuong Minh <[email protected]>
33
 * @since 1.0
34
 */
35
class PaymentGateway extends BasePaymentGateway
36
{
37
    /**
38
     * Lệnh `purchasePro` sử dụng cho việc tạo [[request()]] yêu cầu thanh toán PRO.
39
     */
40
    const RC_PURCHASE_PRO = 'purchasePro';
41
42
    /**
43
     * Lệnh `getMerchantData` sử dụng cho việc tạo [[request()]] yêu cầu thông tin merchant.
44
     */
45
    const RC_GET_MERCHANT_DATA = 'getMerchantData';
46
47
    /**
48
     * Lệnh `verifyIPN` sử dụng cho việc tạo [[request()]] yêu cầu Bảo Kim kiểm tra dữ liệu Bảo Kim bắn sang IPN có hợp lệ hay không.
49
     * Chống giả mạo.
50
     */
51
    const RC_VERIFY_IPN = 'verifyIPN';
52
53
    /**
54
     * Lệnh `purchaseProSuccess` sử dụng cho việc yêu cấu xác thực tính hợp lệ
55
     * của dữ liệu khi khách hàng thanh toán thành công bằng phương thức PRO (cổng thanh toán redirect khách hàng về server).
56
     */
57
    const VRC_PURCHASE_PRO_SUCCESS = 'purchaseProSuccess';
58
59
    /**
60
     * @event RequestEvent được gọi trước khi tạo yêu câu thanh toán PRO.
61
     */
62
    const EVENT_BEFORE_PURCHASE_PRO = 'beforePurchasePro';
63
64
    /**
65
     * @event RequestEvent được gọi sau khi tạo yêu câu thanh toán PRO.
66
     */
67
    const EVENT_AFTER_PURCHASE_PRO = 'afterPurchasePro';
68
69
    /**
70
     * @event RequestEvent được gọi sau khi tạo yêu câu thanh toán PRO.
71
     */
72
    const EVENT_VERIFIED_REQUEST_PURCHASE_PRO_SUCCESS = 'verifiedRequestPurchaseProSuccess';
73
74
    /**
75
     * @event RequestEvent được gọi trước khi tạo yêu câu lấy thông tin merchant.
76
     */
77
    const EVENT_BEFORE_GET_MERCHANT_DATA = 'beforeGetMerchantData';
78
79
    /**
80
     * @event RequestEvent được gọi sau khi tạo yêu câu lấy thông tin merchant.
81
     */
82
    const EVENT_AFTER_GET_MERCHANT_DATA = 'afterGetMerchantData';
83
84
    /**
85
     * @event RequestEvent được gọi trước khi tạo yêu cầu cập nhật trạng thái đơn hàng từ IPN.
86
     */
87
    const EVENT_BEFORE_VERIFY_IPN = 'beforeVerifyIPN';
88
89
    /**
90
     * @event RequestEvent được gọi sau khi tạo yêu cầu cập nhật trạng thái đơn hàng từ IPN.
91
     */
92
    const EVENT_AFTER_VERIFY_IPN = 'afterVerifyIPN';
93
94
    /**
95
     * Đường dẫn API của thanh toán Bảo Kim.
96
     */
97
    const PURCHASE_URL = '/payment/order/version11';
98
99
    /**
100
     * Đường dẫn API của thanh toán PRO.
101
     */
102
    const PURCHASE_PRO_URL = '/payment/rest/payment_pro_api/pay_by_card';
103
104
    /**
105
     * Đường dẫn API để lấy thông tin merchant.
106
     */
107
    const PRO_SELLER_INFO_URL = '/payment/rest/payment_pro_api/get_seller_info';
108
109
    /**
110
     * Đường dẫn API để truy vấn thông tin giao dịch.
111
     */
112
    const QUERY_DR_URL = '/payment/order/queryTransaction';
113
114
    /**
115
     * Đườ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.
116
     * 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ọ.
117
     */
118
    const VERIFY_IPN_URL = '/bpn/verify';
119
120
    /**
121
     * 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.
122
     */
123
    const MUI_CHARGE = 'charge';
124
125
    /**
126
     * 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.
127
     */
128
    const MUI_BASE = 'base';
129
130
    /**
131
     * 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.
132
     */
133
    const MUI_IFRAME = 'iframe';
134
135
    /**
136
     * 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.
137
     */
138
    const DIRECT_TRANSACTION = 1;
139
140
    /**
141
     * 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ữ.
142
     */
143
    const SAFE_TRANSACTION = 2;
144
145
    /**
146
     * Cache component 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
147
     * do dữ liệu này ít khi bị thay đổi.
148
     *
149
     * @see getMerchantData
150
     * @var bool|string|array|\yii\caching\Cache
151
     */
152
    public $merchantDataCache = 'cache';
153
154
    /**
155
     * Cache duration quy định thời gian cache dữ liệu của merchant lấy từ Bảo Kim.
156
     *
157
     * @var int
158
     */
159
    public $merchantDataCacheDuration = 86400;
160
161
    /**
162
     * @inheritdoc
163
     */
164
    public $clientConfig = ['class' => PaymentClient::class];
165
166
    /**
167
     * @inheritdoc
168
     */
169
    public $requestDataConfig = ['class' => RequestData::class];
170
171
    /**
172
     * @inheritdoc
173
     */
174
    public $responseDataConfig = ['class' => ResponseData::class];
175
176
    /**
177
     * @inheritdoc
178
     */
179
    public $verifiedDataConfig = ['class' => VerifiedData::class];
180
181
    /**
182
     * @inheritdoc
183
     */
184 5
    public function getBaseUrl(): string
185
    {
186 5
        return $this->sandbox ? 'https://sandbox.baokim.vn' : 'https://www.baokim.vn';
187
    }
188
189
    /**
190
     * @throws \yii\base\InvalidConfigException
191
     * @inheritdoc
192
     */
193 8
    public function init()
194
    {
195 8
        if ($this->merchantDataCache) {
196 8
            $this->merchantDataCache = Instance::ensure($this->merchantDataCache, 'yii\caching\Cache');
197
        }
198
199 8
        parent::init();
200 8
    }
201
202
    /**
203
     * @inheritdoc
204
     * @throws \yii\base\InvalidConfigException
205
     */
206 8
    protected function initSandboxEnvironment()
207
    {
208 8
        $clientConfig = require(__DIR__ . '/sandbox-client.php');
209 8
        $this->setClient($clientConfig);
210 8
    }
211
212
    /**
213
     * Phương thức thanh toán pro (payment pro) hổ trợ tạo thanh toán với phương thức PRO của Bảo Kim.
214
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_PURCHASE_PRO]].
215
     *
216
     * @param array $data Dữ liệu yêu cầu khởi tạo thanh toán PRO
217
     * @param null $clientId PaymentClient id sử dụng để tạo yêu cầu thanh toán.
218
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
219
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu từ Bảo Kim phản hồi.
220
     * @throws \ReflectionException|\yii\base\InvalidConfigException|\yii\base\InvalidArgumentException
221
     */
222 1
    public function purchasePro(array $data, $clientId = null): DataInterface
223
    {
224 1
        return $this->request(self::RC_PURCHASE_PRO, $data, $clientId);
225
    }
226
227
    /**
228
     * Phương thức này là phương thức ánh xạ của [[verifyRequest()]] nó sẽ tạo lệnh [[VRC_PURCHASE_PRO_SUCCESS]]
229
     * để tạo yêu cầu xác minh tính hợp lệ của dữ liệu trả về từ máy khách đến máy chủ.
230
     *
231
     * @param string|int $clientId PaymentClient id dùng để xác thực tính hợp lệ của dữ liệu.
232
     * @param \yii\web\Request|null $request Đối tượng `request` thực hiện truy cập hệ thống.
233
     * @return bool|VerifiedData|DataInterface Sẽ trả về FALSE nếu như dữ liệu không hợp lệ ngược lại sẽ trả về thông tin đơn hàng đã được xác thực.
234
     */
235
    public function verifyRequestPurchaseProSuccess($clientId = null, \yii\web\Request $request = null)
236
    {
237
        return $this->verifyRequest(self::VRC_PURCHASE_PRO_SUCCESS, $clientId, $request);
238
    }
239
240
    /**
241
     * @inheritdoc
242
     */
243 5
    protected function getHttpClientConfig(): array
244
    {
245
        return [
246 5
            'transport' => 'yii\httpclient\CurlTransport',
247
            'requestConfig' => [
248 5
                'format' => 'json',
249
                'options' => [
250 5
                    CURLOPT_HTTPAUTH => CURLAUTH_DIGEST | CURLAUTH_BASIC,
251 5
                    CURLOPT_SSL_VERIFYHOST => false,
252 5
                    CURLOPT_SSL_VERIFYPEER => false
253
                ]
254
            ]
255
        ];
256
    }
257
258
259
    /**
260
     * Phương thức hổ trợ lấy thông tin merchant thông qua email business.
261
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_GET_MERCHANT_DATA]].
262
     *
263
     * @param string $emailBusiness Email muốn lấy thông tin từ Bảo Kim.
264
     * @param int|string|null $clientId PaymentClient id sử dụng để lấy thông tin.
265
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
266
     * @throws \ReflectionException|\yii\base\InvalidConfigException
267
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu của emailBusiness từ Bảo Kim phản hồi.
268
     */
269 1
    public function getMerchantData(string $emailBusiness = null, $clientId = null): DataInterface
270
    {
271
        /** @var PaymentClient $client */
272 1
        $client = $this->getClient($clientId);
273
        $cacheKey = [
274 1
            __METHOD__,
275 1
            get_class($client),
276 1
            $client->merchantId,
277 1
            $emailBusiness
278
        ];
279
280 1
        if (!$this->merchantDataCache || !$responseData = $this->merchantDataCache->get($cacheKey)) {
281 1
            $responseData = $this->request(self::RC_GET_MERCHANT_DATA, [
282 1
                'business' => $emailBusiness ?? $client->merchantEmail
283 1
            ], $clientId);
284
285 1
            if ($this->merchantDataCache) {
286 1
                $this->merchantDataCache->set($cacheKey, $responseData, $this->merchantDataCacheDuration);
287
            }
288
        }
289
290 1
        return $responseData;
291
    }
292
293
    /**
294
     * Phương thức tạo lệnh yêu cầu Bảo Kim kiểm tra tính hợp lệ của dữ liệu mà IPN nhận được nhầm chống giả mạo.
295
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_IPN]].
296
     *
297
     * @param \yii\web\Request $request Đối tượng request chứa thông tin mà Bảo Kim bắn sang IPN,
298
     * nó được dùng để tổng hợp dữ liệu yêu cầu Bảo Kim xác minh và cập nhật.
299
     * Nếu không thiết lập đối tượng `request` của `Yii::$app` sẽ được sử dụng.
300
     * @param null $clientId Client id sử dụng để tạo yêu cầu cập nhật.
301
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
302
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu từ Bảo Kim phản hồi.
303
     * @throws \ReflectionException|\yii\base\InvalidConfigException|\yii\base\InvalidArgumentException
304
     */
305 1
    public function verifyIPN(\yii\web\Request $request = null, $clientId = null): DataInterface
306
    {
307 1
        if ($request === null) {
308 1
            $request = Instance::ensure('request', '\yii\web\Request');
309
        }
310
311 1
        return $this->request(self::RC_VERIFY_IPN, $request->post(), $clientId);
312
    }
313
314
    /**
315
     * @inheritdoc
316
     */
317 5 View Code Duplication
    public function beforeRequest(RequestEvent $event)
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...
318
    {
319 5
        if ($event->command === self::RC_PURCHASE_PRO) {
320 1
            $this->trigger(self::EVENT_BEFORE_PURCHASE_PRO, $event);
321 4
        } elseif ($event->command === self::RC_GET_MERCHANT_DATA) {
322 1
            $this->trigger(self::EVENT_BEFORE_GET_MERCHANT_DATA, $event);
323 3
        } elseif ($event->command === self::RC_VERIFY_IPN) {
324 1
            $this->trigger(self::EVENT_BEFORE_VERIFY_IPN, $event);
325
        }
326
327 5
        parent::beforeRequest($event);
328 5
    }
329
330
    /**
331
     * @inheritdoc
332
     */
333 5 View Code Duplication
    public function afterRequest(RequestEvent $event)
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...
334
    {
335 5
        if ($event->command === self::RC_PURCHASE_PRO) {
336 1
            $this->trigger(self::EVENT_AFTER_PURCHASE_PRO, $event);
337 4
        } elseif ($event->command === self::RC_GET_MERCHANT_DATA) {
338 1
            $this->trigger(self::EVENT_AFTER_GET_MERCHANT_DATA, $event);
339 3
        } elseif ($event->command === self::RC_VERIFY_IPN) {
340 1
            $this->trigger(self::EVENT_AFTER_VERIFY_IPN, $event);
341
        }
342
343 5
        parent::afterRequest($event);
344 5
    }
345
346
    /**
347
     * @inheritdoc
348
     */
349
    public function verifiedRequest(VerifiedRequestEvent $event)
350
    {
351
        if ($event->command === self::VRC_PURCHASE_PRO_SUCCESS) {
352
            $this->trigger(self::EVENT_VERIFIED_REQUEST_PURCHASE_PRO_SUCCESS, $event);
353
        }
354
355
        parent::verifiedRequest($event);
356
    }
357
358
    /**
359
     * @inheritdoc
360
     * @throws \yii\base\InvalidConfigException
361
     */
362 5
    protected function requestInternal(\vxm\gatewayclients\RequestData $requestData, \yii\httpclient\Client $httpClient): array
363
    {
364
        /** @var PaymentClient $client */
365 5
        $client = $requestData->getClient();
366 5
        $command = $requestData->getCommand();
367 5
        $data = $requestData->get();
368 5
        $httpMethod = 'POST';
369 5
        $options = [CURLOPT_USERPWD => $client->apiUser . ':' . $client->apiPassword];
370 5
        $responseFormat = null;
371
372 5
        if (in_array($command, [self::RC_GET_MERCHANT_DATA, self::RC_QUERY_DR], true)) {
373 2
            if ($command === self::RC_GET_MERCHANT_DATA) {
374 1
                $url = self::PRO_SELLER_INFO_URL;
375
            } else {
376 1
                $url = self::QUERY_DR_URL;
377
            }
378 2
            $data[0] = $url;
379 2
            $url = $data;
380 2
            $data = null;
381 2
            $httpMethod = 'GET';
382 3
        } elseif ($command === self::RC_PURCHASE) {
383 1
            $data[0] = self::PURCHASE_URL;
384 1
            return ['redirect_url' => $httpClient->get($data)->getFullUrl()];
385 2
        } elseif ($command === self::RC_PURCHASE_PRO) {
386 1
            $url = [self::PURCHASE_PRO_URL, 'signature' => ArrayHelper::remove($data, 'signature')];
387
        } else {
388 1
            $url = self::VERIFY_IPN_URL;
389 1
            $responseFormat = 'urlencoded';
390 1
            $options = [];
391
        }
392
393 4
        return $httpClient->createRequest()
394 4
            ->setUrl($url)
395 4
            ->setMethod($httpMethod)
396 4
            ->addOptions($options)
397 4
            ->addData($data)
398 4
            ->send()
399 4
            ->setFormat($responseFormat)
400 4
            ->getData();
401
    }
402
403
    /**
404
     * @inheritdoc
405
     */
406 2
    protected function getVerifyRequestData($command, \yii\web\Request $request): array
407
    {
408
        $params = [
409 2
            'order_id', 'transaction_id', 'created_on', 'payment_type', 'transaction_status', 'total_amount', 'net_amount',
410
            'fee_amount', 'merchant_id', 'customer_name', 'customer_email', 'customer_phone', 'customer_address', 'checksum'
411
        ];
412 2
        $commandRequestMethods = [self::VRC_PURCHASE_SUCCESS => 'get', self::VRC_IPN => 'post'];
413 2
        $requestMethod = $commandRequestMethods[$command];
414 2
        $data = [];
415
416 2 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...
417 2
            if (($value = call_user_func([$request, $requestMethod], $param)) !== null) {
418 2
                $data[$param] = $value;
419
            }
420
        }
421
422 2
        return $data;
423
    }
424
}
425