小程序模板網(wǎng)

微信開發(fā)之獲取用戶詳細(xì)列表

發(fā)布時間:2017-12-16 15:19 所屬欄目:小程序開發(fā)教程

本文目錄 :

  1. 獲取access_token
  2. 獲取用戶id列表
  3. 獲取單用戶詳細(xì)信息
  4. 綜合獲取用戶詳細(xì)列表
  5. 代碼結(jié)構(gòu)組織

php框架:Thinkphp
主題任務(wù):微信公眾平臺開發(fā),獲取用戶詳細(xì)信息列表。

獲取用戶詳細(xì)信息列表,有人會說直接去微信開發(fā)文檔找到對應(yīng)的Api不就得了,還有什么東西可寫?
首先,微信沒有直接提供這樣的Api,所以只能將相關(guān)的接口進(jìn)行組合使用。姑且做一下開發(fā)記錄。


1、 獲取access_token

微信開發(fā)文檔入口:

https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140183

我的代碼:

public function getAccessToken()
{
    $wechat = $this->wx_user; //$this->wx_user:已從數(shù)據(jù)庫中取出所需公眾號信息
    if (empty($wechat)) {
        $this->setError("公眾號不存在!");
        return false;
    }

    //判斷是否過了緩存期
    $expire_time = $wechat['web_expires'];
    if($expire_time > time()){
       return $wechat['web_access_token'];
    }

    //調(diào)用微信提供的接口獲取數(shù)據(jù)
    $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;
    }

    //設(shè)置過期時間,保存進(jìn)數(shù)據(jù)庫,下次判斷數(shù)據(jù)庫中的時間是否過期,如上面代碼所示
    $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的過期刷新方案。
因為每次從微信服務(wù)器拉取access_token時,之前用的access_token就沒用了,也不是立即沒用,會有個短暫的過渡期,但這個過渡期基本可以忽略不計。所以,總不能每次都生成新的access_token吧?所以要判斷過期時間,在過期之前就只用保存的access_token。

這里面還有一個問題,就是如果很多人同時都在操作這個公眾號的api,那么,在過期臨界點的時候會有多次拉取新access_token的現(xiàn)象,導(dǎo)致有些先拉取access_token的操作會失敗,所以,微信官方建議使用AccessToken中控服務(wù)器進(jìn)行集中獲取access_token,所以現(xiàn)在就只有中控服務(wù)器拉取access_token,沒人跟它競爭,不會出現(xiàn)上述描述的場景,放一下官方建議的解決方案圖:

因為項目這里是后臺操作,一般只是管理員在操作,上述場景的情況幾乎不會出現(xiàn),所以簡單場景應(yīng)用簡單解決方案。


2、 獲取用戶id列表

微信開發(fā)文檔入口:

https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140840

我的代碼:

public function getFanIdList($next_openid='')
{
    $access_token = $this->getAccessToken();
    if (!$access_token) {
        return false;
    }

    //調(diào)用微信提供的接口獲取數(shù)據(jù)
    $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;
}

獲取的數(shù)據(jù)如下:

//上邊返回的$list[]元素:
//total 關(guān)注該公眾賬號的總用戶數(shù)
//count 拉取的OPENID個數(shù),最大值為10000
//data  列表數(shù)據(jù),OPENID的列表
//next_openid   拉取列表的最后一個用戶的OPENID
//樣本數(shù)據(jù):
{"total":2,"count":2,"data":{"openid":["OPENID1","OPENID2"]},"next_openid":"NEXT_OPENID"}

可以看到,這里只提供了openid,我們要用這個openid去查詢相應(yīng)的粉絲詳細(xì)信息。
題外話 :
微信目前拉取上述用戶列表,一次只能拉取10000個用戶??次⑿诺慕涌诩s束手冊中,哦,接口約束手冊描述接口單日可用最大次數(shù),可以看到,獲取單用戶的詳細(xì)信息的最大次數(shù)是拉取用戶列表的最大次數(shù)的10000倍,我想這里的10000倍不是巧合。

約束手冊入口:

https://mp.weixin.qq.com/wiki?action=doc&id=mp1433744592


3、 獲取單用戶詳細(xì)信息

微信開發(fā)文檔入口:

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;
        }
    }

    //調(diào)用微信提供的接口獲取數(shù)據(jù)
    $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 '未知';
}

上面返回的數(shù)據(jù)結(jié)構(gòu)如下:

/* $wxdata[]元素:
 * subscribe    用戶是否訂閱該公眾號標(biāo)識,值為0時,代表此用戶沒有關(guān)注該公眾號,拉取不到其余信息。
 * openid   用戶的標(biāo)識,對當(dāng)前公眾號唯一
 * nickname 用戶的昵稱
 * sex  用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知
 * city 用戶所在城市
 * country  用戶所在國家
 * province 用戶所在省份
 * language 用戶的語言,簡體中文為zh_CN
 * headimgurl   用戶頭像,最后一個數(shù)值代表正方形頭像大?。ㄓ?、46、64、96、132數(shù)值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空。若用戶更換頭像,原有頭像URL將失效。
 * subscribe_time   用戶關(guān)注時間,為時間戳。如果用戶曾多次關(guān)注,則取最后關(guān)注時間
 * unionid  只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現(xiàn)該字段。
 * remark   公眾號運營者對粉絲的備注,公眾號運營者可在微信公眾平臺用戶管理界面對粉絲添加備注
 * groupid  用戶所在的分組ID(兼容舊的用戶分組接口)
 * tagid_list   用戶被打上的標(biāo)簽ID列表
 */


4、 綜合獲取用戶詳細(xì)列表

我的代碼:

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();
}

上面代碼是有視圖輸出的,主要提供一種思路。

里邊涉及到的其他代碼:
涉及到獲取公眾號的用戶標(biāo)簽,文檔入口:

https://mp.weixin.qq.com/wiki?action=doc&id=mp1421140837

/**
 * 獲取粉絲標(biāo)簽
 * @return type
 */
public function getAllFanTags()
{
    $access_token = $this->getAccessToken();
    if (!$access_token) {
        return false;
    }

    //調(diào)用微信提供的接口獲取數(shù)據(jù)
    $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數(shù)據(jù)樣例:{"tags":[{"id":1,"name":"每天一罐可樂星人","count":0/*此標(biāo)簽下粉絲數(shù)*/}, ...]}
    return $wxdata['tags'];
}

/**
 * 獲取所有用戶標(biāo)簽
 * @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;
}

/**
 * 獲取粉絲標(biāo)簽名
 * @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、 代碼結(jié)構(gòu)組織

  1. 因為調(diào)用官方接口如果出錯,會有錯誤碼和錯誤信息,可幫助定位問題,為了不浪費這個信息,做了setError()getError()這兩個小函數(shù)記錄,上面已多次使用。
  2. 除了最后的綜合使用的業(yè)務(wù)函數(shù)之外,其他都是微信的常規(guī)操作,都放在一個微信的常規(guī)操作類WechatLogic里邊,可以給多個業(yè)務(wù)使用。


總結(jié)
其實只要看看官方的手冊,找到自己想要的接口,如果找不到直接的接口,就自己拼湊即可。


主要參考文檔

微信開發(fā)入門:https://mp.weixin.qq.com/wiki?action=doc&id=mp1472017492_58YV5
微信開發(fā)文檔:https://mp.weixin.qq.com/wiki


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.u-renovate.com/wxmini/doc/course/18194.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點擊咨詢
QQ在線咨詢
AI智能客服 ×