微信中同步粉丝

       在关注者与公众号产生消息交互后,公众号可获得关注者的OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)。公众号可通过本接口来根据OpenID获取用户基本信息。

一,获取用户基本信息:开发者可通过OpenID来获取

http请求方式: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

二,批量获取用户基本信息

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN

在同步粉丝之前,需查看正在使用的公众号。代码如下:

private $mp;

    public function _initialize(){
      $mp=getCurrentMp();
      if(empty($mp)){
        $this->error('无使用的公众号',U('mp/index'));
        exit;
       }else{
        $this->mp=$mp;
       }
    }

同步粉丝时,需获取粉丝的所有信息,包括昵称,头像等,代码如下:

 public function sycFans(){
    	$mp=$this->mp;

    	include APP_PATH.'LaneWeChat/lanewechat.php';
    	$ret=UserManage::getFansList();//取出所有信息
    	// print_r($ret);
     //  exit;
    	$openids=$ret['data']['openid'];//取得openid
      // print_r($openids);
      $arr=array();
      foreach ($openids as $value) {
        $row=array();
        $row['openid']=$value;
        // print_r($row['openid']);
        // exit;
        $row['lang']="zh_CN";
        $arr[]=$row;
      }
      // print_r($arr);
      $ret=UserManage::getManyUserInfo($arr);
      // print_r($ret);
      // $data=$ret['user_info_list'];
      // print_r($data);
      if(isset($ret['user_info_list'])){
        $data=$ret['user_info_list'];
        // print_r($data);
        $fans=M('mp_friends');
        $fans->where("mp_id={$mp['id']}")->delete();
        foreach ($data as &$value) {
          $value['mp_id']=$mp['id'];
          
          // $value['mp_id']=$mp['id'];
          $value['tagid_list']=implode(',',$value['tagid_list']);
        }
        
        $fans->addAll($data);

      }
      $this->success('同步完成',U('index'));

   }

首先使用UserManage来取出所有信息,然后再取得openid,因为时二维数组,所以需要遍历数组,并获取标签,最后同步完成。

当获取的所有信息中头像不显示时,可编写如下代码:

//显示图片
    public function showMpImg($url){
      header('content-type:image/jpeg');
      echo file_get_contents($url);
    }
显示之后,可根据标签分组并显示,代码如下:
 public function index($tagid=''){
       $mp=$this->mp;
       $where['mp_id']=$mp['id'];
       if(!empty($tagid)){
        $where['tagid_list']=array('like',"%{$tagid}%");
       }

       $data=M('mp_friends')->where($where)->field('id,headimgurl,nickname,subscribe_time,openid,tagid_list')->order()->select();
       $tag=M('tags')->where($where)->select();

       $this->assign('tag',$tag);
       $this->assign('friendList',$data);
       $this->display();
    }

同步完成,显示出来,根据标签也可完成显示。


猜你喜欢

转载自blog.csdn.net/f__theone/article/details/80098174