PHP前端开发

微信网页获取用户基本信息的方法

百变鹏仔 2天前 #前端问答
文章标签 基本信息

本文主要和大家分享微信网页获取用户基本信息的方法,之前写过文章微信网页授权获取用户基本信息讲网页开发的时候,有时候需要获取用户的昵称头像等个人基本信息,获取用户的基本信息,可以通过网页授权,用户同意之后,获取到,如图所示:


但是,这样就多了一个步骤,有的用户可能看到多一个步骤,就随手点击回退,就这么失掉了一个宝贵的用户,很是遗憾,那么今天我们就使用另一种方式来获取用户信息,就是通过OpenID来获取用户基本信息。这种方式可就简单多了,在用户不知不觉的情况下,我们就拿到了他的个人信息,而且这样获取的信息比授权获取的还要多,比如这样还可以知道该用户是否关注以及关注时间

前期准备:
获取到用户的openid,这个在上一篇文章讲过了,详见:微信公众号获取用户的openid

话不多说,直接上代码:

//获取令牌public function getAccessToken(){//指定保存文件位置if(!is_dir('./access_token/')){	mkdir(iconv("GBK","UTF-8",'./access_token/'),0777,true); }$file = './access_token/token';if(file_exists($file)){	$content = file_get_contents($file);	$cont = json_decode($content);	if( (time()-filemtime($file)) expires_in){   //当前时间-文件创建时间<token return>access_token;	}}$curl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&amp;appid='.$this-&gt;appid.'&amp;secret='.$this-&gt;appsecret;$content = $this-&gt;_request($curl);file_put_contents($file,$content);$cont = json_decode($content);return $cont-&gt;access_token;}/** * 通过openid拉取用户信息 * @param  string $openid [description] * @return [type]         [description] */public function getUserInfo($openid=''){if(!$openid) return false;$access_token = $this-&gt;getAccessToken();$urlStr = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&amp;openid=%s&amp;lang=zh_CN';$url = sprintf($urlStr,$access_token,$openid);$result = json_decode($this-&gt;_request($url),true);return $result;}</token>

就可以在用户不知不觉的时候,拿到如下信息: