調用獲取用戶增減數據接口

/**
 * 數組轉json 轉義中文
 */
public function arrToJson($arr) {
    $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
    $json = str_replace("\\/", "/",  $json);
    return $json;
}
// 微信配置信息
protected $app_id = '微信appid';
protected $app_secret = '微信appsecret';
/**
  * 調用獲取用戶增減數據接口
*/
   public function postFluctuate(){
      $access_token = $this->get_access_token();//獲取token,可以存入數據庫如果過期在重新獲取
      $data = $this->arrToJson($_POST);//數組轉json 轉義中文
      $url = 'https://api.weixin.qq.com/datacube/getusersummary?access_token='.$access_token;
      $list = json_decode($this->post_data($url,$data),true);//現在調取接口的時間是7天時間差不能過大
      $listun = $this->assoc_unique($list['list'],$key='ref_date');//查出的關注用戶人數是分開的,去重相加
      foreach ($listun as &$v){
         $v['new_user'] = 0;
         $v['cancel_user'] = 0;
      }
      foreach ($listun as $k=>&$v){
         foreach ($list['list'] as $key=>$value){
            if($v['ref_date'] == $value['ref_date']){
               $v['new_user'] = $v['new_user']+$value['new_user'];
               $v['cancel_user'] = $v['cancel_user']+$value['cancel_user'];
            };
         }
      }
      foreach ($listun as &$v){
         $v['user_growth'] = $v['new_user']-$v['cancel_user'];
      }
      $listun['list'] = $listun;
      return $listun;
   }
/*
*數組根據某個鍵去重
*/
   public function assoc_unique($arr, $key) {
      $tmp_arr = array();
      foreach ($arr as $k => $v) {
         if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr數組中存在,若存在返回true
            unset($arr[$k]);
         } else {
            $tmp_arr[] = $v[$key];
         }
      }
      sort($arr); //sort函數對數組進行排序
      return $arr;

   }

   /**
    * 微信獲取access_token
    */
   private function get_access_token() {
      $result = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret);
      $result = json_decode($result,true);
//    return $result;
      return $result['access_token'];
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章