您的位置:首页 > 移动开发 > 微信开发

微信通过网页获取用户头像与昵称等信息

2015-02-26 17:59 691 查看
define("APPID", "xxxx");
define("APPSECRET", "xxx");

$code = $_GET['code'];
if(!$code){
echo '<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5d7a4bb756e53b28&redirect_uri=http://www.xxx.com/index.php?m=oauth2&a=init&response_type=code&scope=snsapi_base&state=1#wechat_redirect" target="_blank">点击登陆</a>';
}else{

//使用code获取OpenID
$openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
$openid_data = file_get_contents($openid_url);
$arr_openid = (Array)json_decode($openid_data);
$openid = $arr_openid['openid'];

//获取全局Access Token
/*
$access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
$access_token_data = file_get_contents($access_token_url);
$arr_access_token = (Array)json_decode($access_token_data);
$ACCESS_TOKEN = $arr_access_token['access_token'];
*/

$mem = new Memcache;
$mem->connect('localhost', 11211) or die ("Could not connect");
$ACCESS_TOKEN = $mem->get('access_token');
if (empty($ACCESS_TOKEN)){
$access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
$access_token_data = file_get_contents($access_token_url);
$arr_access_token = (Array)json_decode($access_token_data);
$ACCESS_TOKEN = $arr_access_token['access_token'];
$mem->set('access_token', $ACCESS_TOKEN, 0, 7200);
}

//使用全局ACCESS_TOKEN获取OpenID的详细信息
$userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$ACCESS_TOKEN."&openid=".$openid."&lang=zh_CN";
$userinfo_data = file_get_contents($userinfo_url);
$arr_userinfo = (Array)json_decode($userinfo_data);

/*

参数				说明
subscribe		 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
openid			 用户的标识,对当前公众号唯一
nickname		 用户的昵称
sex				 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
city			 用户所在城市
country			 用户所在国家
province		 用户所在省份
language		 用户的语言,简体中文为zh_CN
headimgurl		 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
subscribe_time	 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
unionid			 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)

*/

//获取全部信息:$openid, $nickname, $sex, $city, $province, $country, $headimgurl
$subscribe = $arr_userinfo['subscribe'];
$nickname = $arr_userinfo['nickname'];
$sex = $arr_userinfo['sex'];
$city = $arr_userinfo['city'];
$province = $arr_userinfo['province'];
$country = $arr_userinfo['country'];
$headimgurl = $arr_userinfo['headimgurl'];

echo "ACCESS TOKEN:".$ACCESS_TOKEN;
echo "<br>";
echo "openid:".$openid;
echo "<br>";
echo "nickname:".$nickname;
echo "<br>";
echo "city:".$province.$city;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: