本文目录 :
- 获取access_token
- 获取用户id列表
- 获取单用户详细信息
- 综合获取用户详细列表
- 代码结构组织
php框架:Thinkphp
主题任务:微信公众平台开发,获取用户详细信息列表。
获取用户详细信息列表,有人会说直接去微信开发文档找到对应的Api不就得了,还有什么东西可写?
首先,微信没有直接提供这样的Api,所以只能将相关的接口进行组合使用。姑且做一下开发记录。
1、 获取access_token
微信开发文档入口:
我的代码:
public function getAccessToken()
{
$wechat = $this->wx_user; //$this->wx_user:已从数据库中取出所需公众号信息
if (empty($wechat)) {
$this->setError("公众号不存在!");
return false;
}
//判断是否过了缓存期
$expire_time = $wechat['web_expires'];
if($expire_time > time()){
return $wechat['web_access_token'];
}
//调用微信提供的接口获取数据
$appid = $wechat['appid'];
$appsecret = $wechat['appsecret'];
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$return = httpRequest($url,'GET');
if (empty($return)) {
$this->setError("请求失败,获取access_token失败");
return false;
}
$return = json_decode($return, true);
if (isset($return['errcode']) && $return['errcode'] != 0) {
$this->setError("get_access_token 错误代码;".$return['errcode']);
return false;
}
//设置过期时间,保存进数据库,下次判断数据库中的时间是否过期,如上面代码所示
$web_expires = time() + 7000; // 提前200秒过期
M('wx_user')->where(array('id'=>$wechat['id']))->save(array('web_access_token'=>$return['access_token'],'web_expires'=>$web_expires));
return $return['access_token'];
}