* Date: 2019/6/23 * Time: 11:29 AM */ namespace app\util; use think\facade\Config; use think\facade\Log; define('WX_SERVER_URL', 'https://api.weixin.qq.com'); define('CODE_2_SESSION', WX_SERVER_URL . '/sns/jscode2session'); define('WX_APP_ID', Config::get('wechat.key')); define('WX_APP_SECRET', Config::get('wechat.secret')); class WechatUtil { public function __construct() { } public function codeToSession(string $code): array { return $this->request( CODE_2_SESSION, [ 'js_code' => $code, 'grant_type' => 'authorization_code' ] ); } private function request(string $api, array $params = [], string $method = 'GET') { $params['appid'] = WX_APP_ID; $params['secret'] = WX_APP_SECRET; $method = strtolower($method); if ($method == 'get') { $api .= '?' . http_build_query($params); } $ch = null; try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); //定义是否显示状态头 1:显示 ; 0:不显示 curl_setopt($ch, CURLINFO_HEADER_OUT, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // $postHeader = array( 'Expect: ', 'User-Agent: YCF HTTP API V2', 'Content-Type: application/json;charset=UTF-8' ); curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader); if ($method != 'get') { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } switch ($method) { case 'get': break; case 'post': curl_setopt($ch, CURLOPT_POST, true); break; default: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); break; } $res = curl_exec($ch); $info = curl_getinfo($ch); Log::debug("WechatUtil res=>".print_r($res,1)); // Log::debug("WechatUtil info=>".print_r($info,1)); list($header, $res) = explode("\r\n\r\n", $res, 2); if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { throw new \Exception('Server response error' . print_r($header, 1)); } if ($res && is_string($res)) { return json_decode($res, 1); } else { throw new YCHttpException('Server response data was empty'); } return $res; } catch (\Exception $e) { throw $e; } finally { if (null != $ch) { curl_close($ch); } } return null; } }