Completed
Pull Request — master (#1556)
by wannanbigpig
04:17
created

Client::download()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 13
ccs 0
cts 8
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace EasyWeChat\MicroMerchant\Certficates;
13
14
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
15
use EasyWeChat\Kernel\Traits\InteractsWithCache;
16
use EasyWeChat\MicroMerchant\Kernel\BaseClient;
17
use EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException;
18
19
/**
20
 * Class Client.
21
 *
22
 * @author   liuml  <[email protected]>
23
 * @DateTime 2019-05-30  14:19
24
 */
25
class Client extends BaseClient
26
{
27
    use InteractsWithCache;
28
29
    /**
30
     * get certficates.
31
     *
32
     * @return mixed
33
     *
34
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
35
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
36
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
37
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
38
     * @throws \Psr\SimpleCache\InvalidArgumentException
39
     */
40 1
    public function get()
41
    {
42 1
        $certificates = $this->getCache()->get($this->microCertificates);
43 1
        if ($certificates && strtotime($certificates['expire_time']) > time()) {
44 1
            return $certificates;
45
        }
46
47
        return $this->refresh();
48
    }
49
50
    /**
51
     * download certficates.
52
     *
53
     * @return mixed
54
     *
55
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
56
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
57
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
58
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
59
     * @throws \Psr\SimpleCache\InvalidArgumentException
60
     */
61
    private function download()
62
    {
63
        $params = [
64
            'sign_type' => 'HMAC-SHA256',
65
            'nonce_str' => uniqid('micro'),
66
        ];
67
68
        $responseType = $this->app->config->get('response_type');
69
        $this->app->config->set('response_type', 'array');
70
        $response = $this->request('risk/getcertficates', $params);
71
        $this->app->config->set('response_type', $responseType);
72
73
        return $this->analyze($response);
74
    }
75
76
    /**
77
     * analytical certificate.
78
     *
79
     * @param $data
80
     *
81
     * @return mixed
82
     *
83
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
84
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
85
     * @throws \Psr\SimpleCache\InvalidArgumentException
86
     */
87
    protected function analyze($data)
88
    {
89
        if ('SUCCESS' !== $data['return_code']) {
90
            throw new InvalidArgumentException(
91
                sprintf(
92
                    'Failed to download certificate. return_code_msg: "%s" .',
93
                    $data['return_code'].'('.$data['return_msg'].')'
94
                )
95
            );
96
        }
97
        if ('SUCCESS' !== $data['result_code']) {
98
            throw new InvalidArgumentException(
99
                sprintf(
100
                    'Failed to download certificate. result_err_code_des: "%s" .',
101
                    $data['result_code'].'('.$data['err_code'].'['.$data['err_code_des'].'])'
102
                )
103
            );
104
        }
105
        $certificates = \GuzzleHttp\json_decode($data['certificates'], true)['data'][0];
106
        $ciphertext = $this->decrypt($certificates['encrypt_certificate']);
107
        unset($certificates['encrypt_certificate']);
108
        $certificates['certificates'] = $ciphertext;
109
        $this->getCache()->set($this->microCertificates, $certificates);
110
111
        return $certificates;
112
    }
113
114
    /**
115
     * decrypt ciphertext.
116
     *
117
     * @param $encryptCertificate
118
     *
119
     * @return string
120
     *
121
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
122
     */
123
    protected function decrypt($encryptCertificate)
124
    {
125
        if (false === extension_loaded('sodium')) {
126
            throw new InvalidExtensionException('sodium extension is not installed,Reference link https://php.net/manual/zh/book.sodium.php');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 140 characters; contains 142 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
127
        }
128
129
        if (false === sodium_crypto_aead_aes256gcm_is_available()) {
130
            throw new InvalidExtensionException('aes256gcm is not currently supported');
131
        }
132
133
        // sodium_crypto_aead_aes256gcm_decrypt function needs to open libsodium extension.
134
        // https://www.php.net/manual/zh/function.sodium-crypto-aead-aes256gcm-decrypt.php
135
        return sodium_crypto_aead_aes256gcm_decrypt(
136
            base64_decode($encryptCertificate['ciphertext'], true),
137
            $encryptCertificate['associated_data'],
138
            $encryptCertificate['nonce'],
139
            $this->app['config']->apiv3_key
140
        );
141
    }
142
143
    /**
144
     * refresh certificate.
145
     *
146
     * @return mixed
147
     *
148
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
149
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
150
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
151
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
152
     * @throws \Psr\SimpleCache\InvalidArgumentException
153
     */
154
    public function refresh()
155
    {
156
        return $this->download();
157
    }
158
}
159