TP6获取已关注用户列表(公众号粉丝统计)
根据微信官方文档(文档地址:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html)描述:access_token:调用接口凭证是必填
所以第一步:获取access_token
/**
* 此AccessToken 与 getUserAccessToken不一样
* 获得AccessToken
* @return mixed
*/
private function getAccessToken()
{
$appid = '**********'; //公众号appid
$secret = '**********'; //公众号开发秘钥
// 获取 access token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$accessToken = file_get_contents($url);
$accessToken = json_decode($accessToken);
// 获得access_token
$access = $accessToken->access_token;
return $access;
}
第二步:根据拿到的access_token获得关注此公众号用户openID
/**
* 获得获得关注此公众号用户openID
* 微信官方文档加上next_openid值会报40003错误,还未找到解决方法
*/
public function getUserOpenid($access_token)
{
//根据调用接口凭证去获取用户列表:openID 注 微信官方文档加上next_openid值会报40003错误,还未找到解决方法
$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid=";
$openidAll = file_get_contents($url);
$openidAll = json_decode($openidAll, true);
//获得openID
$data = $openidAll['data']['openid'];
return $data;
}
注意:微信官方文档加上next_openid值会报40003错误,还未找到解决方法
还可以根据用户openID获取用户基本信息(UnionID机制)(文档地址:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId)
/**
* 公众号---根据用户的openID获取用户信息
* @param $accessToken
* @param $openId
* @return mixed
*/
public function useOpenidGetUserInfo($accessToken, $openId)
{
if (!empty($accessToken) && !empty($openId)) {
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
$userInfo = file_get_contents($url);
return json_decode($userInfo, true);
} else {
return false;
}
}
到此就完成了,可以用于公众号粉丝统计