appid=env('WX_APPID',''); $this->appsecret=env('WX_APPSECRET',''); } /** * 创建对象 * @return WeixinServer */ static function creatServer() { if(empty(self::$server)){ self::$server = new WeixinServer(); } return self::$server; } /** * 网页授权 * @return mixed */ function authorize() { $code = request()->input('code', ''); if (empty($code)) { $redirect_url = $this->getServerUrl(); $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"; $this->redirect($url); return false; } else { $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code"; $result = $this->sendRequest($url); $result = json_decode($result, true); if (isset($result['errcode'])) { return false; } else { // $openid = $result['openid']; // $access_token = $result['access_token']; // $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$result['refresh_token']} "; // $result = $this->sendRequest($url); // $result = json_decode($result, true); // if (isset($result['access_token'])) { // $access_token = $result['access_token']; // $openid = $result['openid']; // } // $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN"; // $result = $this->sendRequest($url); // $result = json_decode($result, true); // if (isset($result['errcode'])) { // return false; // } return $result; } } } /** * 获取当前连接 * @return string */ function getServerUrl() { return urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); } function redirect($uri = '', $method = 'location', $http_response_code = 302) { if (!preg_match('#^https?://#i', $uri)) { $uri = site_url($uri); } switch ($method) { case 'refresh' : header("Refresh:0;url=" . $uri); break; default : header("Location: " . $uri, TRUE, $http_response_code); break; } exit(); } /** * @param $url * @param string $type 请求方式 * @param string $data 数据 数组格式 * @return mixed */ protected function sendRequest($url, $type = 'get', $data = '') { $ch = curl_init(); if ($type == 'get' && $data) { $url = $url . '?' . http_build_query($data); } curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $head = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'); curl_setopt($ch, CURLOPT_HTTPHEADER, $head); if ($type == 'post') { curl_setopt($ch, CURLOPT_POST, TRUE);//post请求 $data = json_encode($data, JSON_UNESCAPED_UNICODE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数 } $request = curl_exec($ch); curl_close($ch); return $request; } }