curl($url); $res = json_decode($res, true); if(isset($res['errcode'])){ trace($res, 'error'); return null; } return $res['access_token']; } /** * 请求接口 * @param $url * @param null $data * @return mixed|null */ protected function curl($url, $data=null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/json; encoding=utf-8']); if (!empty($data)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_HEADER, false); $data = curl_exec($curl); curl_close($curl); return $data; } /** * H5授权,code换accesstoken */ public function getAccessTokenByCode($appid, $secret, $code) { $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code'; $res = $this->curl($url); // 返回获取结果 return json_decode($res, true); } /** * H5跳转获取code */ public function redirectForCode($appid, $redirectUrl) { $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($redirectUrl) . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'; header('location:' . $url); exit; } }