config = $config; } /** * 发送curl请求 * @param string $url 要请求的URL * @param string $method 请求方法[get|post] * @param string|array $post_data 请求数据,模拟表单提交时为Array,提交JSON数据时为String * @param string $data_type 数据类型[form|file|json|xml] */ private function curlRequest($url, $method, $post_data='', $data_type='form') { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 为项目内调用设置专用的UA curl_setopt($ch, CURLOPT_USERAGENT, 'Intract cURL'); // 设置为不自动输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 不输出头部 curl_setopt($ch, CURLOPT_HEADER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 不从证书中检查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 根据$data_type,选择不同的HTTP Header $data_type = strtolower($data_type); switch($data_type) { case 'form': $header = 'application/x-www-form-urlencoded'; break; case 'file': $header = 'multipart/form-data'; break; case 'json': $header = 'application/json'; break; case 'xml': $header = 'text/xml'; break; default: // 默认为form $header = 'application/x-www-form-urlencoded'; } $header = array( 'Content-type: ' . $header, 'Content-length: ' . strlen($post_data) ); // 根据不同的提交方式,设置头部和数据 $method = strtolower($method); switch($method) { case 'get': break; case 'post': // 设置头部 curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // 设置POST提交 curl_setopt($ch, CURLOPT_POST, true); // 设置POST数据 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); break; default: ; } // 执行请求 $response = curl_exec($ch); // 返回数据 $res = array( 'status' => 0, 'err_msg' => '', 'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), 'data' => null ); if($response === false) { $res['err_msg'] = curl_error($ch); } else { $res['status'] = 1; $res['data'] = $response; } // 关闭连接 curl_close($ch); return $res; } /** * 发送报文 * @param string $url 接口URL * @param string $data 加密后的数据 * @param string $sign 交易报文签名 * @return bool|string 成功时返回JSON字符串 */ public function send(string $url, string $data, string $sign) { // 组装通用参数 $post_data = array( 'data' => $data, 'orgid' => $this->config['org_num'], 'signtype' => $this->config['signtype'], 'sign' => $sign ); $post_data = json_encode($post_data); echo "【请求报文】
{$post_data}

"; // 发送请求 $send_res = $this->curlRequest($url, 'post', $post_data, 'json'); if($send_res['status'] !== 1) { $this->err_msg = $send_res['err_msg'] . '(HTTP Code: ' . $send_res['http_code'] . ')'; return false; } return $send_res['data']; } } ?>