微信自定義菜單打開本地連接,並提示用戶授權登錄獲取信息,將微信用戶與本地用戶關系打通
網頁端判斷是否是微信瀏覽器瀏覽
<script> if(isWeixin()) { // alert('是微信瀏覽器'); window.location.href = "{:url(\"/bindphone/getcode\")}"; } function isWeixin () { var ua = window.navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_'){ return true; } else{ return false; } } </script>
如果是微信客戶端瀏覽網頁則跳轉到getcode方法中,進行提示用戶授權操作,來獲取用戶openid 等信息
public function getcode() { $state = md5(uniqid(rand(), TRUE)); $hdurl = urlencode("http://****.cn/bindphone/callback"); $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $hdurl . "&response_type=code&scope=snsapi_userinfo&state=" . $state . "#wechat_redirect"; $this->redirect($url); //此方法為跳轉到頁面方法,不是curl方法獲取數據用 die; }
上面拿到微信的code碼,用戶同意授權后,會跳轉到紅色 回調路徑中去,
微信官方提示:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
下圖為scope等於snsapi_userinfo時的授權頁面:
用戶同意授權后
如果用戶同意授權,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE。
code說明 : code作為換取access_token的票據,每次用戶授權帶上的code將不一樣,code只能使用一次,5分鍾未被使用自動過期。
這樣在callback方法中獲取code碼,然后在獲取accetoken 即可
public function callback() { $param = request()->param(); $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->AppSecret . '&code=' . $param['code'] . '&grant_type=authorization_code'; $arr = $this->http_curl($url); $openids = $arr['openid']; 這里就可以拿到用戶openid 與accestoken等信息 Cache::set($openids, $openids, 86400); //得到openid 后查詢數據庫看看是否有該紀錄,如果有,直接登錄,存好uid到session,如果沒有,走綁定手機號步驟,進行完善或者注冊 $useinfo = Db::name('nqi_sys_user')->where('openid', $openids)->find(); if (!empty($useinfo)) { $this->sees($useinfo['sys_user_id'],$useinfo['user_name']);//這里是登錄操作,無關 $this->redirect("/news.html?searchmodels=能源&filter=filter-ny&pageindex=2&pagesize=12"); } //得到 access_token 與 openid $urls = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $arr['access_token'] . '&openid=' .$openids . '&lang=zh_CN'; $wechatInfos = $this->http_curl($urls); 這里得到用戶資料 //得到 用戶資料,將openid unionid傳給頁面,跳轉去走注冊或者綁定流程頁面 $this->redirect("/bindphone.html?openid=".$wechatInfos['openid']."&nickname=".$wechatInfos['nickname']); }
public function http_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json = curl_exec($ch);
curl_close($ch);
return json_decode($json, 1);
}
經過上面步驟就可以拿到用戶個人信息,頭像用戶名,openid等信息,想要拿到unionid需要到開放平台去授權公眾平台才行