Passed
Push — master ( 510fa6...c11190 )
by ma
03:02
created

Base::formRequest()   A

Complexity

Conditions 3
Paths 14

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 24
rs 9.6666
cc 3
nc 14
nop 1
1
<?php
2
3
namespace tinymeng\Chinaums\Service\Common;
4
5
use Exception;
6
use tinymeng\Chinaums\Tools\Http;
7
use tinymeng\tools\FileTool;
8
9
class Base
10
{
11
    /**
12
     * @var array $config 网关
13
     */
14
    protected $config = [];
15
16
    protected $gateway;
17
    protected $gateway_type = 'default';
18
19
    /**
20
     * @var string 接口地址
21
     */
22
    protected $api;
23
    /**
24
     * @var array $body 请求参数
25
     */
26
    protected $body;
27
    /**
28
     * 必传的值
29
     * @var array
30
     */
31
    protected $require = [];
32
33
    /**
34
     * @param $config
35
     */
36
    public function __construct($config=[])
37
    {
38
        if(!empty($config)){
39
            $this->config = $config;
40
            $this->loadConfigGateway();
41
        }
42
    }
43
44
    /**
45
     * 加载多网关
46
     * @return Base
47
     */
48
    private function loadConfigGateway()
49
    {
50
        $gateway = $this->config['gateway'];// 正式环境
51
        if($this->config['sandbox'] === false){
52
            $this->gateway = isset($gateway[$this->gateway_type]) ? $gateway[$this->gateway_type] : $gateway['default'];// 沙箱环境
53
        }else{
54
            $this->gateway = $gateway['sandbox'];// 沙箱环境
55
        }
56
57
        return $this;
58
    }
59
60
    /**
61
     * @param $data
62
     * @return string
63
     * @throws Exception
64
     */
65
    private function loadData($data)
66
    {
67
        $data['mid'] = $this->config['mid'];
68
        $data['tid'] = $this->config['tid'];
69
        if ($data) {
70
            $this->body = array_merge($this->body, $data);
71
        }
72
        $this->validate();
73
        $data = $this->body;
74
        return json_encode($data);
75
    }
76
77
    /**
78
     * @param array $data
79
     * @return false|mixed|string
80
     */
81
    public function request(array $data = [])
82
    {
83
        try {
84
            $data = $this->loadData($data);
85
            $sign = $this->generateSign($data);
86
            $gateway  = $this->gateway . $this->api;
87
88
            if ('cli' == php_sapi_name()) {
89
                echo 'api:' . $gateway . PHP_EOL;
90
                echo 'request:' . $data . PHP_EOL;
91
            }
92
            $this->writeLog('api:' . $gateway);
93
            $this->writeLog('request:' . $data);
94
95
            $headers = [
96
                'Content-Type: application/json',
97
                'Content-Length: ' . strlen($data),
98
                'Authorization: ' . $sign
99
            ];
100
            $options = [
101
                CURLOPT_HTTPHEADER => $headers,
102
                CURLOPT_TIMEOUT => 60,
103
                CURLOPT_CONNECTTIMEOUT => 30
104
            ];
105
            $response = Http::post($gateway, $data, $options);
106
            $this->writeLog('response:' . $response);
107
            return $response;
108
        } catch (Exception $e) {
109
            return json_encode(['errCode' => -1, 'errMsg' => $e->getMessage(), 'responseTimestamp' => null]);
110
        }
111
    }
112
113
    /**
114
     * @param array $data
115
     * @return string
116
     * @throws Exception
117
     */
118
    public function formRequest(array $data = [])
119
    {
120
        try {
121
            $data = $this->loadData($data);
122
            $params = $this->generateSign($data,true);
123
            $gateway  = $this->gateway . $this->api;
124
125
            $data = json_encode($data);
126
            if ('cli' == php_sapi_name()) {
127
                echo 'api:' . $gateway . PHP_EOL;
128
                echo 'request:' . $data . PHP_EOL;
129
            }
130
            $this->writeLog('api:' . $gateway);
131
            $this->writeLog('request:' . $data);
132
133
            $options = [
134
                CURLOPT_TIMEOUT => 60,
135
                CURLOPT_CONNECTTIMEOUT => 30
136
            ];
137
            $response = Http::get($gateway,$params,$options);
138
            $this->writeLog('response:' . $response);
139
            return $response;
140
        } catch (Exception $e) {
141
            return json_encode(['errCode' => -1, 'errMsg' => $e->getMessage(), 'responseTimestamp' => null]);
142
        }
143
    }
144
145
    /**
146
     * @param $config
147
     * @return $this
148
     */
149
    public function setConfig($config)
150
    {
151
        $this->config = $config;
152
        $this->loadConfigGateway();
153
        return $this;
154
    }
155
156
    /**
157
     * @param $value
158
     * @return $this
159
     */
160
    public function setBody($value)
161
    {
162
        $this->body = array_merge($this->body, $value);
163
        return $this;
164
    }
165
166
    /**
167
     * @return true
168
     * @throws Exception
169
     */
170
    protected function validate()
171
    {
172
        $require = $this->require;
173
        $key = array_keys($this->body);
174
        foreach ($require as $v) {
175
            if (!in_array($v, $key)) {
176
                throw new Exception($v . ' is require!!');
177
            }
178
        }
179
        return true;
180
    }
181
182
    /**
183
     * 根绝类型生成sign
184
     * @param $body
185
     * @param bool $openForm
186
     * @return string|array
187
     */
188
    public function generateSign($body,$openForm=false)
189
    {
190
        $body = (!is_string($body)) ? json_encode($body) : $body;
191
        $appid = $this->config['appid'];
192
        $appkey = $this->config['appkey'];
193
        $timestamp = date("YmdHis", time());
194
        $nonce = md5(uniqid(microtime(true), true));
195
        $str = bin2hex(hash('sha256', $body, true));
196
        $signature = base64_encode(hash_hmac('sha256', "$appid$timestamp$nonce$str", $appkey, true));
197
        $authorization = "OPEN-BODY-SIG AppId=\"$appid\", Timestamp=\"$timestamp\", Nonce=\"$nonce\", Signature=\"$signature\"";
198
        if($openForm){
199
            return [
200
                'appId'=>$appid,
201
                'timestamp'=>$timestamp,
202
                'nonce'=>$nonce,
203
                'content'=>$body,
204
                'signature'=>$signature,
205
                'authorization'=>'OPEN-FORM-PARAM',
206
            ];
207
        }
208
        return $authorization;
209
    }
210
211
    /**
212
     * @param $name
213
     * @param $value
214
     * @return void
215
     */
216
    public function __set($name, $value)
217
    {
218
        $this->body[$name] = $value;
219
    }
220
221
    /**
222
     * @param $message
223
     * @return void
224
     */
225
    public function writeLog($message,$fileName='chinaums')
226
    {
227
        FileTool::writeLog($message,$fileName);
228
    }
229
}
230