微信公眾平臺接口可以根據openid獲取用戶詳細信息,方法如下:
引導用戶去授權頁面。
用戶同意授權後,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE
code是去到授權頁面後,用戶同意授權後返回來的。PHP代碼如下:
//通過code換取token
$code = $_GET['code'];
$url = "/sns/oauth2/access_token?appid=appid&secret=SECRET&code=$code&grant_type=authorization_code";
$json = file_get_contents($url);
$arr = json_decode($json,true);
$token = $arr['access_token'];
$openid = $arr['openid'];
//拿到token後就可以獲取用戶基本信息了
$url = "/sns/userinfo?access_token=$token&openid=$openid ";
$json = file_get_contents($url);//獲取微信用戶基本信息
$arr = json_decode($json,true);
$name = $arr['nickname'];//昵稱
$imgURL = $arr['headimgurl'];//頭像地址
$sex = $arr['sex'];//性別
$province = $arr['province'];//用戶個人資料填寫的省份
$city= $arr['city'];//普通用戶個人資料填寫的城市
$country= $arr['country'];//國家,如中國為CN