PaymentGateway::initSandboxEnvironment()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
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
     * @since 1.0.3.1
149
     */
150
    public $httpClientConfig = ['transport' => 'yii\httpclient\CurlTransport'];
151
152
    /**
153
     * @inheritdoc
154
     */
155 10
    public function getBaseUrl(): string
156
    {
157 10
        return $this->sandbox ? 'https://sandbox.baokim.vn' : 'https://www.baokim.vn';
158
    }
159
160
    /**
161
     * @throws \yii\base\InvalidConfigException
162
     * @inheritdoc
163
     */
164 15
    public function init()
165
    {
166 15
        if ($this->merchantDataCache) {
167 15
            $this->merchantDataCache = Instance::ensure($this->merchantDataCache, 'yii\caching\Cache');
168
        }
169
170 15
        parent::init();
171 15
    }
172
173
    /**
174
     * @inheritdoc
175
     * @since 1.0.3
176
     */
177 9
    public function requestCommands(): array
178
    {
179 9
        return [self::RC_PURCHASE, self::RC_QUERY_DR, self::RC_GET_MERCHANT_DATA];
180
    }
181
182
    /**
183
     * @inheritdoc
184
     * @throws \yii\base\InvalidConfigException
185
     */
186 15
    protected function initSandboxEnvironment()
187
    {
188 15
        $clientConfig = require(__DIR__ . '/sandbox-client.php');
189 15
        $this->setClient($clientConfig);
190 15
    }
191
192
    /**
193
     * Phương thức hổ trợ lấy thông tin merchant thông qua email business.
194
     * Đây là phương thức ánh xạ của [[request()]] sử dụng lệnh [[RC_GET_MERCHANT_DATA]].
195
     *
196
     * @param string $emailBusiness Email muốn lấy thông tin từ Bảo Kim.
197
     * @param int|string|null $clientId PaymentClient id sử dụng để lấy thông tin.
198
     * Nếu không thiết lập [[getDefaultClient()]] sẽ được gọi để xác định client.
199
     * @throws \ReflectionException|\yii\base\InvalidConfigException
200
     * @return ResponseData|DataInterface Trả về [[ResponseData]] là dữ liệu của emailBusiness từ Bảo Kim phản hồi.
201
     */
202 6
    public function getMerchantData(string $emailBusiness = null, $clientId = null): DataInterface
203
    {
204
        /** @var PaymentClient $client */
205 6
        $client = $this->getClient($clientId);
206
        $cacheKey = [
207 6
            __METHOD__,
208 6
            get_class($client),
209 6
            $client->merchantId,
210 6
            $emailBusiness
211
        ];
212
213 6
        if (!$this->merchantDataCache || !($responseData = $this->merchantDataCache->get($cacheKey))) {
214 6
            $responseData = $this->request(self::RC_GET_MERCHANT_DATA, [
215 6
                'business' => $emailBusiness ?? $client->merchantEmail
216 6
            ], $clientId);
217
218 6
            if ($this->merchantDataCache) {
219 6
                $this->merchantDataCache->set($cacheKey, $responseData, $this->merchantDataCacheDuration);
220
            }
221
        }
222
223 6
        return $responseData;
224
    }
225
226
    /**
227
     * @inheritdoc
228
     */
229 9
    public function beforeRequest(RequestEvent $event)
230
    {
231 9
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
232 6
            $this->trigger(self::EVENT_BEFORE_GET_MERCHANT_DATA, $event);
233
        }
234
235 9
        parent::beforeRequest($event);
236 9
    }
237
238
    /**
239
     * @inheritdoc
240
     */
241 9
    public function afterRequest(RequestEvent $event)
242
    {
243 9
        if ($event->command === self::RC_GET_MERCHANT_DATA) {
244 6
            $this->trigger(self::EVENT_AFTER_GET_MERCHANT_DATA, $event);
245
        }
246
247 9
        parent::afterRequest($event);
248 9
    }
249
250
    /**
251
     * @inheritdoc
252
     * @throws \yii\base\InvalidConfigException|\yii\httpclient\Exception|NotSupportedException
253
     */
254 9
    protected function requestInternal(\vxm\gatewayclients\RequestData $requestData, \yii\httpclient\Client $httpClient): array
255
    {
256
        /** @var PaymentClient $client */
257 9
        $client = $requestData->getClient();
258 9
        $command = $requestData->getCommand();
259 9
        $data = $requestData->get();
260 9
        $httpMethod = 'POST';
261
262 9
        if (in_array($command, [self::RC_GET_MERCHANT_DATA, self::RC_QUERY_DR], true)) {
263 7
            if ($command === self::RC_GET_MERCHANT_DATA) {
264 6
                $url = self::PRO_SELLER_INFO_URL;
265
            } else {
266 1
                $url = self::QUERY_DR_URL;
267
            }
268 7
            $data[0] = $url;
269 7
            $url = $data;
270 7
            $data = null;
271 7
            $httpMethod = 'GET';
272
        } else {
273 2
            if ($this->pro) {
274 1
                $url = [self::PURCHASE_PRO_URL, 'signature' => ArrayHelper::remove($data, 'signature')];
275
            } else {
276 1
                $data[0] = self::PURCHASE_URL;
277 1
                return ['redirect_url' => $httpClient->get($data)->getFullUrl()];
278
            }
279
        }
280
281
        return $httpClient
282 8
            ->createRequest()
283 8
            ->setUrl($url)
284 8
            ->setMethod($httpMethod)
285 8
            ->setFormat('json')
286 8
            ->addData($data)
287 8
            ->addOptions([
288 8
                CURLOPT_HTTPAUTH => CURLAUTH_DIGEST | CURLAUTH_BASIC,
289 8
                CURLOPT_USERPWD => $client->apiUser . ':' . $client->apiPassword
290
            ])
291 8
            ->send()
292 8
            ->getData();
293
    }
294
295
    /**
296
     * @inheritdoc
297
     */
298 2
    public function verifyRequest($command, \yii\web\Request $request = null, $clientId = null)
299
    {
300 2
        if ($command === self::VRC_IPN) {
301
302 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...
303 1
                if (Yii::$app instanceof \yii\web\Application) {
304 1
                    $request = Yii::$app->getRequest();
305
                } else {
306
                    throw new InvalidArgumentException('Request instance arg must be set to verify return request is valid or not!');
307
                }
308
            }
309
310 1
            $content = $this->getHttpClient()->post(self::VERIFY_IPN_URL, $request->post())->send()->getContent();
311
312 1
            if (strpos($content, 'VERIFIED') === false) {
313 1
                return false;
314
            }
315
        }
316
317 1
        return parent::verifyRequest($command, $request, $clientId);
318
    }
319
320
    /**
321
     * @inheritdoc
322
     */
323 1
    protected function getVerifyRequestData($command, \yii\web\Request $request): array
324
    {
325
        $params = [
326 1
            'order_id', 'transaction_id', 'created_on', 'payment_type', 'transaction_status', 'total_amount', 'net_amount',
327
            'fee_amount', 'merchant_id', 'customer_name', 'customer_email', 'customer_phone', 'customer_address', 'checksum',
328
            'payer_name', 'payer_email', 'payer_phone_no', 'shipping_address', 'verify_sign', 'resend', 'customer_location',
329
            'merchant_address', 'merchant_email', 'merchant_location', 'merchant_name', 'merchant_phone'
330
        ];
331 1
        $commandRequestMethods = [self::VRC_PURCHASE_SUCCESS => 'get', self::VRC_IPN => 'post'];
332 1
        $requestMethod = $commandRequestMethods[$command];
333 1
        $data = [];
334
335 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...
336 1
            if (($value = call_user_func([$request, $requestMethod], $param)) !== null) {
337 1
                $data[$param] = $value;
338
            }
339
        }
340
341 1
        return $data;
342
    }
343
344
}
345