1. 程式人生 > >微信開發——同步粉絲、獲取使用者基本資訊

微信開發——同步粉絲、獲取使用者基本資訊

在關注者與公眾號產生訊息互動後,公眾號可獲得關注者的OpenID(加密後的微訊號,每個使用者對每個公眾號的OpenID是唯一的。對於不同公眾號,同一使用者的openid不同)。公眾號可通過本介面來根據OpenID獲取使用者基本資訊,包括暱稱、頭像、性別、所在城市、語言和關注時間。開發者可通過OpenID來獲取使用者基本資訊。特別需要注意的是,如果開發者擁有多個移動應用、網站應用和公眾帳號,可通過獲取使用者基本資訊中的unionid來區分使用者的唯一性,因為只要是同一個微信開放平臺帳號下的移動應用、網站應用和公眾帳號,使用者的unionid是唯一的。換句話說,同一使用者,對同一個微信開放平臺下的不同應用,unionid是相同的。

獲取使用者基本資訊,介面呼叫:https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
在前臺頁面用按鈕呼叫addFuns方法,控制器中addFuns方法如下:
        //同步粉絲
        public function addFuns(){
                $mp = $this->mp;//獲取正在使用的公眾號的ID
                include APP_PATH . 'LaneWeChat/lanewechat.php';
                $access_token = getAccess_token();
                $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token";
                $ret = Curl::callWebServer($url,'','POST');
                // print_r($ret);
                // exit;
                for ($i=0; $i < $ret['count']; $i++) { 
                        $openid = $ret['data']['openid'][$i];
                        $openids[$i]['openid'] = $openid;
                        $openids[$i]['lang'] = 'zh_CN';
                }
                // print_r($openids);
                // exit;
                $result = UserManage::getManyUserInfo($openids);
                // $result = $result['user_info_list'];
                if(isset($result['user_info_list'])){
                        $result = $result['user_info_list'];
                        foreach ($result as &$value) {
                                $value['mp_id'] = $mp['id'];
                                $value['tagid_list'] = implode(",",$value['tagid_list']);
                        }
                }


                $openid = M('mp_friends')->where("openid = '$openid'")->find(); 
                if(!isset($openid)){
                    M('mp_friends')->addAll($result);  
                }
  
                // $this->display('index');     
                $this->redirect('index');       
        }
獲取使用者基本資訊之後,需要讓資訊顯示在當前頁面,首先查詢資料庫資訊,然後讓模板顯示。程式碼如下:      

 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();
                // print_r($tag);
                // exit;
                $this->assign('tag',$tag);
                $this->assign('data',$data);
                $this->display();
        }

希望可以幫助到你們~~~嘿嘿