这是一个实用且通用的功能,说通俗点就是用微信帐号登录第三方网站,经用户确认后,允许网站获取用户基本资料。
技术资料参见微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN
1、实现这一功能需要先设置授权回调页面域名,如下图:
2、主要代码(只获取用户信息,登录网站部分略)
<?php if(isset($_GET['code'])){ $code = $_GET['code']; $userInfo = getUserInfo($code); echo $userInfo; } else{ echo "Error!"; } function getUserInfo($code){ $appid = "wx04d2578db7e1b736"; $appsecret = "43b9557d223737d01ababb39a4b4b14d"; $accessToken = ""; //根据code获取token $tokenURL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code"; $tokenJson = https_request($tokenURL); $tokenArray = json_decode($tokenJson,true); $accssToken = $tokenArray['access_token']; $openid = $tokenArray['openid']; //拉取用户信息 $userInfoURL = "https://api.weixin.qq.com/sns/userinfo?access_token=$accssToken&openid=$openid"; $userInfoJson = https_request($userInfoURL); $userInfoArray = json_decode($userInfoJson,true); return $userInfoJson; } function https_request($url){ //return $url; $curl = curl_init(); curl_setopt($curl,CURLOPT_URL,$url); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false); curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); $data = curl_exec($curl); if(curl_errno($curl)){ return 'ERROR'.curl_error($curl); } curl_close($curl); return $data; } ?>
3,最后按以下格式访问,获得用户信息
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx04d2578db7e1b736&redirect_uri=http://essays.duapp.com/getUserInfo.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
返回信息大致如下(未经处理)
{
"openid": "owThxwlQQV8WQynaTZmMI6yi29-s",
"nickname": "自由行走",
"sex": 1,
"language": "zh_CN",
"city": "Kunming",
"province": "Yunnan",
"country": "CN",
"headimgurl": "http://wx.qlogo.cn/mmopen/eGrUpN8dpomatpwS0VrRIh6n9deJACV9S9F8vqxjmxicd0Gt5QLl0BNC4zeKSoS24umarmibP7rzf1obOJibVvG9d8icK7cjibTiaE/0",
"privilege": [ ]
}