微信受權後獲取用戶頭像保存到服務器

最近作一個有關微信受權登陸的項目,關於受權就很少說了,我獲取到用戶基本信息,格式以下:數據庫

$user_info = '{"openid":"xx","nickname":"nice花椒.","sex":2,"language":"zh_CN","city":"杭州","province":"浙江","country":"中國","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTJPpziaqOoIpGia9ZVj9fheAwLmTiavV4rxR40NQ1zPQPyiaMY58FEISDIfpn0q5VeeXliaKyiaiabgK2ZHg\/0","privilege":[]}';

直接把headimgurl入庫保存,bug來了。json

話很少說,進入正題:微信

微信返回的是json格式curl

$user_arr = json_decode($user_info, true);

獲取用戶openid對比數據庫,判斷是否是首次受權url

$mem_info= $member->getuserinfo(array('openid'=>$user_arr['openid']));

首次受權或者頭像連接地址與上次不一樣code

if(!$mem_info || $mem_info['wximage']!=$user_info['headimg']){
    $headimgurl = saveheadimgurl($user_arr['headimgurl']);
    $headimg ? 0 : $headimg='lib/avata.jpg' ;
    if($mem_info['wximage']!=$user_info['headimg']){
        unlink($mem_info['headimg']);
    }
    //快來寫你的註冊或者修改代碼吧!
}

保存圖片接口

function saveheadimgurl($headimg){
    $header = array(
         'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',      
         'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',      
         'Accept-Encoding: gzip, deflate',
    );
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $headimg);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    $dataimg = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);  
    if ($code == 200) {     
        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($dataimg);
    }  
    $img_content=$imgBase64Code;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)){   
         $type = $result[2];
         create(DOFILESPATH."head"); 
         $new_file = DOFILESPATH."head/".md5(uniqid(rand())).".{$type}"; 
         if (file_put_contents($new_file, base64_decode(str_replace($result[1],'', $img_content))))  
         {  
             return $new_file;
         }
     }
     return false;
}

指定位置建立文件圖片

function create($dir){
    if(is_dir($dir)){
        $temp = explode('/',$dir);
        $cur_dir = '';
        for($i=0; $i<count($temp); $i++){
            $cur_dir .= $temp[$i].'/';
            if(!is_dir($cur_dir)){
                @mkdir($cur_dir,777);
            }
        }
    }
}

哈哈,我是一個專一接口的小菜鳥,多多指教!ip

相關文章
相關標籤/搜索