本文目錄 :
php框架:Thinkphp
主題任務:微信公眾平臺開發,獲取用戶詳細信息列表。
獲取用戶詳細信息列表,有人會說直接去微信開發文檔找到對應的Api不就得了,還有什么東西可寫?
首先,微信沒有直接提供這樣的Api,所以只能將相關的接口進行組合使用。姑且做一下開發記錄。
1、 獲取access_token
微信開發文檔入口:
https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140183
我的代碼:
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'];
}
上面涉及到access_token的過期刷新方案。
因為每次從微信服務器拉取access_token時,之前用的access_token就沒用了,也不是立即沒用,會有個短暫的過渡期,但這個過渡期基本可以忽略不計。所以,總不能每次都生成新的access_token吧?所以要判斷過期時間,在過期之前就只用保存的access_token。
這里面還有一個問題,就是如果很多人同時都在操作這個公眾號的api,那么,在過期臨界點的時候會有多次拉取新access_token的現象,導致有些先拉取access_token的操作會失敗,所以,微信官方建議使用AccessToken中控服務器進行集中獲取access_token,所以現在就只有中控服務器拉取access_token,沒人跟它競爭,不會出現上述描述的場景,放一下官方建議的解決方案圖:
因為項目這里是后臺操作,一般只是管理員在操作,上述場景的情況幾乎不會出現,所以簡單場景應用簡單解決方案。
2、 獲取用戶id列表
微信開發文檔入口:
https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140840
我的代碼:
public function getFanIdList($next_openid='')
{
$access_token = $this->getAccessToken();
if (!$access_token) {
return false;
}
//調用微信提供的接口獲取數據
$url ="https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid={$next_openid}";//重頭開始拉取,一次最多拉取10000個
$return = httpRequest($url);
$list = json_decode($return, true);
if (isset($list['errcode']) && $list['errcode'] != 0) {
$this->setError("錯誤代碼:".$list['errcode']);
return false;
}
return $list;
}
獲取的數據如下:
//上邊返回的$list[]元素:
//total 關注該公眾賬號的總用戶數
//count 拉取的OPENID個數,最大值為10000
//data 列表數據,OPENID的列表
//next_openid 拉取列表的最后一個用戶的OPENID
//樣本數據:
{"total":2,"count":2,"data":{"openid":["OPENID1","OPENID2"]},"next_openid":"NEXT_OPENID"}
可以看到,這里只提供了openid,我們要用這個openid去查詢相應的粉絲詳細信息。
題外話 :
微信目前拉取上述用戶列表,一次只能拉取10000個用戶。看微信的接口約束手冊中,哦,接口約束手冊描述接口單日可用最大次數,可以看到,獲取單用戶的詳細信息的最大次數是拉取用戶列表的最大次數的10000倍,我想這里的10000倍不是巧合。
約束手冊入口:
https://mp.weixin.qq.com/wiki?action=doc&id=mp1433744592
3、 獲取單用戶詳細信息
微信開發文檔入口:
https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140839
我的代碼:
public function getFanInfo($openid, $access_token=null)
{
if (null === $access_token) {
$access_token = $this->getAccessToken();
if (!$access_token) {
return false;
}
}
//調用微信提供的接口獲取數據
$url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
$return = httpRequest($url);
$wxdata = json_decode($return, true);
if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) {
$this->setError("錯誤代碼;".$wxdata['errcode']);
return false;
}
$wxdata['sex_name'] = $this->sexName($wxdata['sex']);
return $wxdata;
}
public function sexName($sex_id)
{
if ($sex_id == 1) {
return '男';
} else if ($sex_id == 2) {
return '女';
}
return '未知';
}
上面返回的數據結構如下:
/* $wxdata[]元素:
* 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 只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現該字段。
* remark 公眾號運營者對粉絲的備注,公眾號運營者可在微信公眾平臺用戶管理界面對粉絲添加備注
* groupid 用戶所在的分組ID(兼容舊的用戶分組接口)
* tagid_list 用戶被打上的標簽ID列表
*/
4、 綜合獲取用戶詳細列表
我的代碼:
public function fans_list()
{
$wechatObj = new WechatLogic($this->wx_user);
$access_token = $wechatObj->getAccessToken();
if (!$access_token) {
return $this->error($wechatObj->getError());
}
$next_openid = '';
$p = intval(I('get.p')) ?: 1;
for ($i = 1; $i <= $p; $i++) {
$id_list = $wechatObj->getFanIdList($next_openid);
if ($id_list === false) {
return $this->error($wechatObj->getError());
}
$next_openid = $id_list['next_openid'];
}
$user_list = [];
foreach ($id_list['data']['openid'] as $openid) {
$user_list[$openid] = $wechatObj->getFanInfo($openid, $access_token);
if ($user_list[$openid] === false) {
return $this->error($wechatObj->getError());
}
$user_list[$openid]['tags'] = $wechatObj->getFanTagNames($user_list[$openid]['tagid_list']);
if ($user_list[$openid]['tags'] === false) {
return $this->error($wechatObj->getError());
}
}
$page = new Page($id_list['total'], $id_list['count']);
$show = $page->show();
$this->assign('pager',$page);
$this->assign('page',$show);
$this->assign('user_list', $user_list);
return $this->fetch();
}
上面代碼是有視圖輸出的,主要提供一種思路。
里邊涉及到的其他代碼:
涉及到獲取公眾號的用戶標簽,文檔入口:
https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140837
/**
* 獲取粉絲標簽
* @return type
*/
public function getAllFanTags()
{
$access_token = $this->getAccessToken();
if (!$access_token) {
return false;
}
//調用微信提供的接口獲取數據
$url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$access_token}";
$return = httpRequest($url);
$wxdata = json_decode($return, true);
if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) {
$this->setError("錯誤代碼;".$wxdata['errcode']);
return false;
}
//$wxdata數據樣例:{"tags":[{"id":1,"name":"每天一罐可樂星人","count":0/*此標簽下粉絲數*/}, ...]}
return $wxdata['tags'];
}
/**
* 獲取所有用戶標簽
* @return array
*/
public function getAllFanTagsMap()
{
if ($this->tags_map !== null) {
return $this->tags_map;
}
$user_tags = $this->getAllFanTags();
if ($user_tags === false) {
return false;
}
$this->tags_map = [];
foreach ($user_tags as $tag) {
$this->tags_map[$tag['id']] = $this->tags_map[$tag['name']];
}
return $this->tags_map;
}
/**
* 獲取粉絲標簽名
* @param string $tagid_list
* @param array $tags_map
* @return array
*/
public function getFanTagNames($tagid_list)
{
if ($this->tags_map === null) {
$tags_map = $this->getAllFanTagsMap();
if ($tags_map === false) {
return false;
}
$this->tags_map = $tags_map;;
}
$tag_names = [];
foreach ($tagid_list as $tag) {
$tag_names[] = $this->tags_map[$tag];
}
return $tag_names;
}
5、 代碼結構組織
setError()
和getError()
這兩個小函數記錄,上面已多次使用。WechatLogic
里邊,可以給多個業務使用。
總結:
其實只要看看官方的手冊,找到自己想要的接口,如果找不到直接的接口,就自己拼湊即可。
主要參考文檔:
微信開發入門:https://mp.weixin.qq.com/wiki?action=doc&id=mp1472017492_58YV5
微信開發文檔:https://mp.weixin.qq.com/wiki