这篇文章主要介绍了PHP微信开发之同步粉丝 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
首先获取到当前公众号的id//获取正在使用的公众号
function getCurrentMp(){
$mp=M('mp')->where('is_use=1')->find();
return $mp;
}
初始化private $mp;
public function _initialize(){
$mp=getCurrentMp();
if(empty($mp)){
$this->error('无使用的公众号',U('mp/index'));
exit;
}else{
$this->mp=$mp;
}
}
获取access_token的方法function getAccess_token(){
$mp=M('mp')->where('is_use=1')->find();
if(empty($mp)) return false;
$id=$mp['id'];//正在使用的公众号的主键
if(empty($mp['access_token']) || $mp['expire_time']
$appid=$mp['appid'];
$appsecret=$mp['appsecret'];
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
include APP_PATH.'LaneWeChat/lanewechat.php';
$arr= \LaneWeChat\Core\Curl::callWebServer($url,'','GET');
//将获取到的access_token存入数据库
if(isset($arr['access_token'])){
$data['access_token']=$arr['access_token'];
$data['expire_time']=$arr['expires_in'] + time()-200;
M('mp')->where("id=$id")->save($data);
return $arr['access_token'];
}else{
return false;
}
}else{
return $mp['access_token'];
}
}
调用封装好的框架public static function getFansList($next_openid=''){
//获取ACCESS_TOKEN
$accessToken = getAccess_token();
if(empty($next_openid)){
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$accessToken;
}else{
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$accessToken.'&next_openid='.$next_openid;
}
return Curl::callWebServer($queryUrl, '', 'GET');
}//批量获取基本信息
public function getManyUserInfo($openids){
$accessToken = getAccess_token();
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.$accessToken;
$json=json_encode(array('user_list'=>$openids));
return Curl::callWebServer($queryUrl, $json, 'POST');
}
做好准备工作后,开始同步public function downFans(){
$mp=$this->mp;
$mp_id = $mp['id'];
include APP_PATH.'LaneWeChat/lanewechat.php';
$ret=UserManage::getFansList();
// print_r($ret);
$openids=$ret['data']['openid'];
// print_r($openids);
$arr=array();
foreach ($openids as $value) {
$row=array();
$row['openid']=$value;
$row['lang']="zh_CN";
$arr[]=$row;
}
// print_r($arr);
// exit;
$ret=UserManage::getManyUserInfo($arr);
// print_r($ret);
// exit;
if(isset($ret['user_info_list'])){
$data=$ret['user_info_list'];
// print_r($data);
// exit;
$mp=$this->mp;
// $data['mp_id']= $mp_id;
$fan=M('mp_friends');
$fan->where("mp_id={$mp['id']}")->delete();
foreach ($data as &$value) {
$value['mp_id']=$mp['id'];
$value['tagid_list']=implode(',', $value['tagid_list']);
}
$fan->addAll($data);
}
$this->success('同步完成',U('index'));
}
相关推荐: