Passed
Push — master ( c11190...b979a3 )
by ma
03:25
created

Base::writeLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace tinymeng\Chinaums\Service\Common;
4
5
use Exception;
6
use tinymeng\Chinaums\Tools\Http;
7
8
/**
9
 * Base
10
 * @method static \tinymeng\Chinaums\Service\Common\Base request(array $params) 创建请求
11
 */
12
class Base
13
{
14
    /**
15
     * @var array $config 网关
16
     */
17
    protected $config = [];
18
19
    protected $gateway;
20
    protected $gateway_type = 'default';
21
22
    /**
23
     * @var string 接口地址
24
     */
25
    protected $api;
26
    /**
27
     * @var array $body 请求参数
28
     */
29
    protected $body;
30
    /**
31
     * 代码传输过来的请求参数
32
     * @var
33
     */
34
    protected $params;
35
    /**
36
     * 必传的值
37
     * @var array
38
     */
39
    protected $require = [];
40
41
    /**
42
     * @param $config
43
     * @param $params
44
     */
45
    public function __construct($config=[],$params=[])
46
    {
47
        if(!empty($config)){
48
            $this->config = $config;
49
            $this->loadConfigGateway();
50
        }
51
        $this->params = $params;
52
    }
53
54
    /**
55
     * 加载多网关
56
     * @return Base
57
     */
58
    private function loadConfigGateway()
59
    {
60
        $gateway = $this->config['gateway'];// 正式环境
61
        if($this->config['sandbox'] === false){
62
            $this->gateway = isset($gateway[$this->gateway_type]) ? $gateway[$this->gateway_type] : $gateway['default'];// 沙箱环境
63
        }else{
64
            $this->gateway = $gateway['sandbox'];// 沙箱环境
65
        }
66
67
        return $this;
68
    }
69
70
    /**
71
     * @return false|string
72
     * @throws Exception
73
     */
74
    private function loadData()
75
    {
76
        $data = $this->params;
77
        $data['mid'] = $this->config['mid'];
78
        $data['tid'] = $this->config['tid'];
79
        if ($data) {
80
            $this->body = array_merge($this->body, $data);
81
        }
82
        $this->validate();
83
        $data = $this->body;
84
        $data = json_encode($data);
85
        return $data;
86
    }
87
88
    /**
89
     * @return false|mixed|string
90
     */
91
    public function request($params = [])
92
    {
93
        if(!empty($params)){
94
            $this->params = $params;
95
        }
96
97
        try {
98
            $data = $this->loadData();
99
            $sign = $this->generateSign($data);
100
            $gateway  = $this->gateway . $this->api;
101
102
            if ('cli' == php_sapi_name()) {
103
                echo 'api:' . $gateway . PHP_EOL;
104
                echo 'request:' . $data . PHP_EOL;
105
            }
106
            $headers = [
107
                'Content-Type: application/json',
108
                'Content-Length: ' . strlen($data),
109
                'Authorization: ' . $sign
110
            ];
111
            $options = [
112
                CURLOPT_HTTPHEADER => $headers,
113
                CURLOPT_TIMEOUT => 60,
114
                CURLOPT_CONNECTTIMEOUT => 30
115
            ];
116
            $response = Http::post($gateway, $data, $options);
0 ignored issues
show
Bug introduced by
$data of type string is incompatible with the type array expected by parameter $params of tinymeng\Chinaums\Tools\Http::post(). ( Ignorable by Annotation )

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

116
            $response = Http::post($gateway, /** @scrutinizer ignore-type */ $data, $options);
Loading history...
117
            return $response;
118
        } catch (Exception $e) {
119
            return json_encode(['errCode' => -1, 'errMsg' => $e->getMessage(), 'responseTimestamp' => null]);
120
        }
121
    }
122
123
    /**
124
     * @return string
125
     */
126
    public function formRequest()
127
    {
128
        try {
129
            $data = $this->loadData();
130
            $params = $this->generateSign($data,true);
131
            $gateway  = $this->gateway . $this->api;
132
133
            $data = json_encode($data);
134
            if ('cli' == php_sapi_name()) {
135
                echo 'api:' . $gateway . PHP_EOL;
136
                echo 'request:' . $data . PHP_EOL;
137
            }
138
139
            $options = [
140
                CURLOPT_TIMEOUT => 60,
141
                CURLOPT_CONNECTTIMEOUT => 30
142
            ];
143
            $response = Http::get($gateway,$params,$options);
0 ignored issues
show
Bug introduced by
$params of type string is incompatible with the type array expected by parameter $params of tinymeng\Chinaums\Tools\Http::get(). ( Ignorable by Annotation )

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

143
            $response = Http::get($gateway,/** @scrutinizer ignore-type */ $params,$options);
Loading history...
144
            return $response;
145
        } catch (Exception $e) {
146
            return json_encode(['errCode' => -1, 'errMsg' => $e->getMessage(), 'responseTimestamp' => null]);
147
        }
148
    }
149
150
    /**
151
     * @param $config
152
     * @return $this
153
     */
154
    public function setConfig($config)
155
    {
156
        $this->config = $config;
157
        $this->loadConfigGateway();
158
        return $this;
159
    }
160
161
    /**
162
     * @param $value
163
     * @return $this
164
     */
165
    public function setBody($value)
166
    {
167
        $this->body = array_merge($this->body, $value);
168
        return $this;
169
    }
170
171
    /**
172
     * @return true
173
     * @throws Exception
174
     */
175
    protected function validate()
176
    {
177
        $require = $this->require;
178
        $key = array_keys($this->body);
179
        foreach ($require as $v) {
180
            if (!in_array($v, $key)) {
181
                throw new Exception($v . ' is require!!');
182
            }
183
        }
184
        return true;
185
    }
186
    /**
187
     * 根绝类型生成sign
188
     * @param $params
189
     * @param string $signType
190
     * @return string
191
     */
192
    public function generateSign($body,$openForm=false)
193
    {
194
        $body = (!is_string($body)) ? json_encode($body) : $body;
195
        $appid = $this->config['appid'];
196
        $appkey = $this->config['appkey'];
197
        $timestamp = date("YmdHis", time());
198
        $nonce = md5(uniqid(microtime(true), true));
199
        $str = bin2hex(hash('sha256', $body, true));
200
        $signature = base64_encode(hash_hmac('sha256', "$appid$timestamp$nonce$str", $appkey, true));
201
        $authorization = "OPEN-BODY-SIG AppId=\"$appid\", Timestamp=\"$timestamp\", Nonce=\"$nonce\", Signature=\"$signature\"";
202
        if($openForm){
203
            $params = [
204
                'appId'=>$appid,
205
                'timestamp'=>$timestamp,
206
                'nonce'=>$nonce,
207
                'content'=>$body,
208
                'signature'=>$signature,
209
                'authorization'=>'OPEN-FORM-PARAM',
210
            ];
211
            return $params;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $params returns the type array<string,mixed|string> which is incompatible with the documented return type string.
Loading history...
212
        }
213
        return $authorization;
214
    }
215
216
    /**
217
     * @param $name
218
     * @param $value
219
     * @return void
220
     */
221
    public function __set($name, $value)
222
    {
223
        $this->body[$name] = $value;
224
    }
225
}
226