获取微信用户的信息(普通版)
public function getAccessToken($code) { // 获取openid $appid = WX_PUBLIC_APPID; $secret = WX_PUBLIC_APPSECRET; $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $oauth2 = json_decode(file_get_contents($oauth2Url),true); if (!isset($oauth2["access_token"])){ return null; } $access_token = $oauth2["access_token"]; // 获得 access_token(获取用户信息的access_token) 和openid $openid = $oauth2['openid']; // 获取用户信息(不包含是否关注公众号字段 - subscribe) $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"; $userInfo = json_decode(file_get_contents($get_user_info_url),true); return $userInfo; }
获取微信用户的信息(包含是否关注公众号信息)
public function getAccessToken($code)
{
// 获取openid,因为需要知道是否关注公众所以此次请求 与普通的微信登录不同
$appid = WX_PUBLIC_APPID;
$secret = WX_PUBLIC_APPSECRET;
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = json_decode(file_get_contents($oauth2Url),true);
if (!isset($oauth2["access_token"])){
return null;
}
$openid = $oauth2['openid'];
// 获取是否关注公众号所需要的access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$access = file_get_contents($url);
$access_arr = json_decode($access,true);
if (!isset($access_arr["access_token"])){
return null;
}
$new_access_token = $access_arr['access_token'];
// 获取用户信息
$get_user_subscribe_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$new_access_token."&openid=".$openid."&lang=zh_CN";
$res = file_get_contents($get_user_subscribe_url);
$userInfo = json_decode($res,true);
return $userInfo;
}