公众号通过接口查询所有粉丝的openid信息列表。
一 . 查询用户列表:
1. 获取access_token。
2. 获取open_id。
2. 查询用户列表。(get方式访问)
class UsersService extends Service
{
private $appid = ''; //自己appid
private $appsecret = ''; //自己appsecret
private $access_token; //token
private $open_id;
public $error;
//$begin 代表从哪个用户开始,类似于order by
public function userList($begin = '')
{
if(empty($this->access_token)){
$this->getToken();
}
$begin = empty($begin) ? '' : 'OPENID'.$begin;
$url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$this->access_token.'&next_openid='.$begin;
$result = $this->requestUrl($url);
$result = json_decode($result);
$data = $result->data->openid;
foreach($data as $k => $v){
$info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->access_token.'&openid='.$v.'&lang=zh_CN';
$data_info = $this->requestUrl($info_url);
$user_info[] = json_decode($data_info);
}
return $user_info;
}
/*
* 获取普通通用token
*/
public function getToken()
{
if (empty($_SESSION['accessToken'])) {
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->appsecret;
$result = json_decode($this->requestUrl($url), true);
if (empty($result['access_token'])) {
$this->error = $result['errorMsg'];
return false;
}
$_SESSION['accessToken'] = $result['access_token'];
}
$this->access_token = $_SESSION['accessToken'];
}
/**
* curl 请求
*/
private function requestUrl($url, $data = '')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //禁止 cURL 验证对等证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 为SSL不检查名称
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
二 . 控制器边调用方法查询:
/**
* 微信获取用户列表
* @writer dan
* @date 2022-07-14
*/
public function actionUserList()
{
$begin = 0;
$users = $this->users()->userList($begin);
if(empty($users)){
return '暂无人关注';
}
return $users;
}