Completed
Push — master ( 4f7c7c...fdaf8f )
by Vuong
02:10
created

PaymentGateway::requestCommands()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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;
11
12
use GatewayClients\DataInterface;
13
14
use yii\base\InvalidArgumentException;
15
use yii\base\NotSupportedException;
16
use yii\di\Instance;
17
use yii\helpers\ArrayHelper;
18
19
use yiiviet\payment\BasePaymentGateway;
20
21
use vxm\gatewayclients\RequestEvent;
22
23
/**
24
 * 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.
25
 * Hiện tại nó hổ trợ 100% các tính năng từ cổng thanh toán Bảo Kim.
26
 *
27
 * @method ResponseData purchase(array $data, $clientId = null)
28
 * @method ResponseData queryDR(array $data, $clientId = null)
29
 * @method bool|VerifiedData verifyRequestIPN($clientId = null, \yii\web\Request $request = null)
30
 * @method bool|VerifiedData verifyRequestPurchaseSuccess($clientId = null, \yii\web\Request $request = null)
31
 * @method PaymentClient getClient($id = null)
32
 * @method PaymentClient getDefaultClient()
33
 *
34
 * @property PaymentClient $client
35
 * @property PaymentClient $defaultClient
36
 * @property ResponseData $merchantData
37
 *
38
 * @author Vuong Minh <[email protected]>
39
 * @since 1.0
40
 */
41
class PaymentGateway extends BasePaymentGateway
42
{
43
    /**
44
     * Lệnh `getMerchantData` sử dụng cho việc tạo [[request()]] yêu cầu thông tin merchant.
45
     */
46
    const RC_GET_MERCHANT_DATA = 'getMerchantData';
47
48
    /**
49
     * @event RequestEvent được gọi trước khi tạo yêu câu lấy thông tin merchant.
50
     */
51
    const EVENT_BEFORE_GET_MERCHANT_DATA = 'beforeGetMerchantData';
52
53
    /**
54
     * @event RequestEvent được gọi sau khi tạo yêu câu lấy thông tin merchant.
55
     */
56
    const EVENT_AFTER_GET_MERCHANT_DATA = 'afterGetMerchantData';
57
58
    /**
59
     * Đường dẫn API của thanh toán Bảo Kim.
60
     */
61
    const PURCHASE_URL = '/payment/order/version11';
62
63
    /**
64
     * Đường dẫn API của thanh toán PRO.
65
     */
66
    const PURCHASE_PRO_URL = '/payment/rest/payment_pro_api/pay_by_card';
67
68
    /**
69
     * Đường dẫn API để lấy thông tin merchant.
70
     */
71
    const PRO_SELLER_INFO_URL = '/payment/rest/payment_pro_api/get_seller_info';
72
73
    /**
74
     * Đường dẫn API để truy vấn thông tin giao dịch.
75
     */
76
    const QUERY_DR_URL = '/payment/order/queryTransaction';
77
78
    /**
79
     * Đườ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.
80
     * 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ọ.
81
     */
82
    const VERIFY_IPN_URL = '/bpn/verify';
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ị charge.
86
     */
87
    const MUI_CHARGE = 'charge';
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ị base.
91
     */
92
    const MUI_BASE = 'base';
93
94
    /**
95
     * 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.
96
     */
97
    const MUI_IFRAME = 'iframe';
98
99
    /**
100
     * 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.
101
     */
102
    const DIRECT_TRANSACTION = 1;
103
104
    /**
105
     * 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ữ.
106
     */
107
    const SAFE_TRANSACTION = 2;
108
109
    /**
110
     * @var bool Thiết lập true nếu muốn thanh toán trực tiếp không chuyển khách đến Bảo Kim.
111
     */
112
    public $pro = false;
113
114
    /**
115
     * @see getMerchantData
116
     * @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
117
     * do dữ liệu này ít khi bị thay đổi.
118
     */
119
    public $merchantDataCache = 'cache';
120
121
    /**
122
     * @var int Thời gian cache dữ liệu của merchant lấy từ Bảo Kim.
123
     */
124
    public $merchantDataCacheDuration = 86400;
125
126
    /**
127
     * @inheritdoc
128
     */
129
    public $clientConfig = ['class' => PaymentClient::class];
130
131
    /**
132
     * @inheritdoc
133
     */
134
    public $requestDataConfig = ['class' => RequestData::class];
135
136
    /**
137
     * @inheritdoc
138
     */
139
    public $responseDataConfig = ['class' => ResponseData::class];
140
141
    /**
142
     * @inheritdoc
143
     */
144
    public $verifiedDataConfig = ['class' => VerifiedData::class];
145
146
    /**
147
     * @inheritdoc
148
     */
149 10
    public function getBaseUrl(): string
150
    {
151 10
        return $this->sandbox ? 'https://sandbox.baokim.vn' : 'https://www.baokim.vn';
152
    }
153
154
    /**
155
     * @throws \yii\base\InvalidConfigException
156
     * @inheritdoc
157
     */
158 15
    public function init()
159
    {
160 15
        if ($this->merchantDataCache) {
161 15
            $this->merchantDataCache = Instance::ensure($this->merchantDataCache, 'yii\caching\Cache');
162
        }
163
164 15
        parent::init();
165 15
    }
166
167
    /**
168
     * @inheritdoc
169
     * @since 1.0.3
170
     */
171 9
    public function requestCommands(): array
172
    {
173 9
        return [self::RC_PURCHASE, self::RC_QUERY_DR, self::RC_GET_MERCHANT_DATA];
174
    }
175
176
    /**
177
     * @inheritdoc
178
     * @throws \yii\base\InvalidConfigException
179
     */
180 15
    protected function initSandboxEnvironment()
181
    {
182 15
        $clientConfig = require(__DIR__ . '/sandbox-client.php');
183 15
        $this->setClient($clientConfig);
184 15
    }
185
186
    /**
187
     * Phương thức hổ trợ lấy thông tin merchant thông qua email business.
188
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_GET_MERCHANT_DATA]].
189
     *
190
     * @param string $emailBusiness Email muốn lấy thông tin từ Bảo Kim.
191
     * @param int|string|null $clientId PaymentClient id sử dụng để lấy thông tin.
192
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
193
     * @throws \ReflectionException|\yii\base\InvalidConfigException
194
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu của emailBusiness từ Bảo Kim phản hồi.
195
     */
196 6
    public function getMerchantData(string $emailBusiness = null, $clientId = null): DataInterface
197
    {
198
        /** @var PaymentClient $client */
199 6
        $client = $this->getClient($clientId);
200
        $cacheKey = [
201 6
            __METHOD__,
202 6
            get_class($client),
203 6
            $client->merchantId,
204 6
            $emailBusiness
205
        ];
206
207 6
        if (!$this->merchantDataCache || !($responseData = $this->merchantDataCache->get($cacheKey))) {
208 6
            $responseData = $this->request(self::RC_GET_MERCHANT_DATA, [
209 6
                'business' => $emailBusiness ?? $client->merchantEmail
210 6
            ], $clientId);
211
212 6
            if ($this->merchantDataCache) {
213 6
                $this->merchantDataCache->set($cacheKey, $responseData, $this->merchantDataCacheDuration);
214
            }
215
        }
216
217 6
        return $responseData;
218
    }
219
220
    /**
221
     * @inheritdoc
222
     */
223 9
    public function beforeRequest(RequestEvent $event)
224
    {
225 9
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
226 6
            $this->trigger(self::EVENT_BEFORE_GET_MERCHANT_DATA, $event);
227
        }
228
229 9
        parent::beforeRequest($event);
230 9
    }
231
232
    /**
233
     * @inheritdoc
234
     */
235 9
    public function afterRequest(RequestEvent $event)
236
    {
237 9
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
238 6
            $this->trigger(self::EVENT_AFTER_GET_MERCHANT_DATA, $event);
239
        }
240
241 9
        parent::afterRequest($event);
242 9
    }
243
244
    /**
245
     * @inheritdoc
246
     * @throws \yii\base\InvalidConfigException|\yii\httpclient\Exception|NotSupportedException
247
     */
248 9
    protected function requestInternal(\vxm\gatewayclients\RequestData $requestData, \yii\httpclient\Client $httpClient): array
249
    {
250
        /** @var PaymentClient $client */
251 9
        $client = $requestData->getClient();
252 9
        $command = $requestData->getCommand();
253 9
        $data = $requestData->get();
254 9
        $httpMethod = 'POST';
255
256 9
        if (in_array($command, [self::RC_GET_MERCHANT_DATA, self::RC_QUERY_DR], true)) {
257 7
            if ($command === self::RC_GET_MERCHANT_DATA) {
258 6
                $url = self::PRO_SELLER_INFO_URL;
259
            } else {
260 1
                $url = self::QUERY_DR_URL;
261
            }
262 7
            $data[0] = $url;
263 7
            $url = $data;
264 7
            $data = null;
265 7
            $httpMethod = 'GET';
266
        } else {
267 2
            if ($this->pro) {
268 1
                $url = [self::PURCHASE_PRO_URL, 'signature' => ArrayHelper::remove($data, 'signature')];
269
            } else {
270 1
                $data[0] = self::PURCHASE_URL;
271 1
                return ['redirect_url' => $httpClient->get($data)->getFullUrl()];
272
            }
273
        }
274
275
        return $httpClient
276 8
            ->createRequest()
277 8
            ->setUrl($url)
278 8
            ->setMethod($httpMethod)
279 8
            ->setFormat('json')
280 8
            ->addData($data)
281 8
            ->addHeaders(['Authorization' => 'Basic ' . base64_encode($client->apiUser . ':' . $client->apiPassword)])
282 8
            ->send()
283 8
            ->data;
284
    }
285
286
    /**
287
     * @inheritdoc
288
     */
289 2
    public function verifyRequest($command, \yii\web\Request $request = null, $clientId = null)
290
    {
291 2
        if ($command === self::VRC_IPN) {
292
293 1 View Code Duplication
            if ($request === null) {
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...
294 1
                if (Yii::$app instanceof \yii\web\Application) {
295 1
                    $request = Yii::$app->getRequest();
296
                } else {
297
                    throw new InvalidArgumentException('Request instance arg must be set to verify return request is valid or not!');
298
                }
299
            }
300
301 1
            $content = $this->getHttpClient()->post(self::VERIFY_IPN_URL, $request->post())->send()->getContent();
302
303 1
            if (strpos($content, 'VERIFIED') === false) {
304 1
                return false;
305
            }
306
        }
307
308 1
        return parent::verifyRequest($command, $request, $clientId);
309
    }
310
311
    /**
312
     * @inheritdoc
313
     */
314 1
    protected function getVerifyRequestData($command, \yii\web\Request $request): array
315
    {
316
        $params = [
317 1
            'order_id', 'transaction_id', 'created_on', 'payment_type', 'transaction_status', 'total_amount', 'net_amount',
318
            'fee_amount', 'merchant_id', 'customer_name', 'customer_email', 'customer_phone', 'customer_address', 'checksum',
319
            'payer_name', 'payer_email', 'payer_phone_no', 'shipping_address', 'verify_sign', 'resend', 'customer_location',
320
            'merchant_address', 'merchant_email', 'merchant_location', 'merchant_name', 'merchant_phone'
321
        ];
322 1
        $commandRequestMethods = [self::VRC_PURCHASE_SUCCESS => 'get', self::VRC_IPN => 'post'];
323 1
        $requestMethod = $commandRequestMethods[$command];
324 1
        $data = [];
325
326 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...
327 1
            if (($value = call_user_func([$request, $requestMethod], $param)) !== null) {
328 1
                $data[$param] = $value;
329
            }
330
        }
331
332 1
        return $data;
333
    }
334
335
}
336