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

Client::download()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
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 12
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
        return $this->refresh();
47
    }
48
49
    /**
50
     * download certficates.
51
     *
52
     * @return mixed
53
     *
54
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
55
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
56
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
57
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
58
     * @throws \Psr\SimpleCache\InvalidArgumentException
59
     */
60
    private function download()
61
    {
62
        $params = [
63
            'sign_type' => 'HMAC-SHA256',
64
            'nonce_str' => uniqid('micro'),
65
        ];
66
67
        $responseType = $this->app->config->get('response_type');
68
        $this->app->config->set('response_type', 'array');
69
        $response = $this->request('risk/getcertficates', $params);
70
        $this->app->config->set('response_type', $responseType);
71
        return $this->analytical($response);
72
    }
73
74
    /**
75
     * analytical certificate.
76
     *
77
     * @param $data
78
     *
79
     * @return mixed
80
     *
81
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
82
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
83
     * @throws \Psr\SimpleCache\InvalidArgumentException
84
     */
85
    protected function analytical($data)
86
    {
87
        if ('SUCCESS' !== $data['return_code']) {
88
            throw new InvalidArgumentException(
89
                sprintf(
90
                    'Failed to download certificate. return_code_msg: "%s" .',
91
                    $data['return_code'].'('.$data['return_msg'].')'
92
                )
93
            );
94
        }
95
        if ('SUCCESS' !== $data['result_code']) {
96
            throw new InvalidArgumentException(
97
                sprintf(
98
                    'Failed to download certificate. result_err_code_des: "%s" .',
99
                    $data['result_code'].'('.$data['err_code'].'['.$data['err_code_des'].'])'
100
                )
101
            );
102
        }
103
        $certificates = \GuzzleHttp\json_decode($data['certificates'], JSON_UNESCAPED_UNICODE)['data'][0];
0 ignored issues
show
Bug introduced by
EasyWeChat\MicroMerchant...\JSON_UNESCAPED_UNICODE of type integer is incompatible with the type boolean expected by parameter $assoc of GuzzleHttp\json_decode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

103
        $certificates = \GuzzleHttp\json_decode($data['certificates'], /** @scrutinizer ignore-type */ JSON_UNESCAPED_UNICODE)['data'][0];
Loading history...
104
        $ciphertext = $this->decrypt($certificates['encrypt_certificate']);
105
        unset($certificates['encrypt_certificate']);
106
        $certificates['certificates'] = $ciphertext;
107
        $this->getCache()->set($this->microCertificates, $certificates);
108
        return $certificates;
109
    }
110
111
    /**
112
     * decrypt ciphertext.
113
     *
114
     * @param $encryptCertificate
115
     *
116
     * @return string
117
     *
118
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
119
     */
120
    protected function decrypt($encryptCertificate)
121
    {
122
        if (false === extension_loaded('sodium')) {
123
            throw new InvalidExtensionException('sodium extension is not installed,Reference link https://blog.csdn.net/u010324331/article/details/82153067');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 140 characters; contains 158 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...
124
        }
125
126
        if (false === sodium_crypto_aead_aes256gcm_is_available()) {
127
            throw new InvalidExtensionException('aes256gcm is not currently supported');
128
        }
129
130
        // sodium_crypto_aead_aes256gcm_decrypt function needs to open libsodium extension.
131
        // https://blog.csdn.net/u010324331/article/details/82153067
132
        return sodium_crypto_aead_aes256gcm_decrypt(
133
            base64_decode($encryptCertificate['ciphertext'], true),
134
            $encryptCertificate['associated_data'],
135
            $encryptCertificate['nonce'],
136
            $this->app['config']->apiv3_key
137
        );
138
    }
139
140
    /**
141
     * refresh certificate.
142
     *
143
     * @return mixed
144
     *
145
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
146
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
147
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidExtensionException
148
     * @throws \EasyWeChat\MicroMerchant\Kernel\Exceptions\InvalidSignException
149
     * @throws \Psr\SimpleCache\InvalidArgumentException
150
     */
151
    public function refresh()
152
    {
153
        return $this->download();
154
    }
155
}
156