微信第三方掃碼登陸
阿新 • • 發佈:2019-01-24
API程式碼:
//-------配置 $AppID = C('WX_APPID'); $AppSecret = C('WX_APPSECRET'); $callback = C('WX_CALLBACK');//'http://www.wftc.co//'; //回撥地址 //微信登入 session_start(); //-------生成唯一隨機串防CSRF攻擊 $state = md5(uniqid(rand(), TRUE)); $_SESSION["wx_state"] = $state; //存到SESSION $callback = urlencode($callback); $wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=".$AppID."&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect"; header("Location: $wxurl");
callback程式碼:
if($_GET['state']!=$_SESSION["wx_state"]){ exit("5001"); } $AppID = C('WX_APPID'); $AppSecret = C('WX_APPSECRET'); $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code'; $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); $arr=json_decode($json,1); //得到 access_token 與 openid //print_r($arr); // exit; $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN'; //exit($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); $arr=json_decode($json,1); //得到 使用者資料 print_r($arr);