微信公眾號開發(二) -- 獲取使用者資訊 修改粉絲標籤
阿新 • • 發佈:2018-11-25
獲取code值
$appid=’’ // 微信支付申請對應的公眾號的APPID
$urlCode=’’ // 處理code頁面 不能包含? 是微信可訪問頁面
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=http://".$urlCode."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
header('location:'.$url);
通過code獲取openid 查詢使用者資訊
$appid=’’ // 微信支付申請對應的公眾號appid $secret=’’ // 微信支付申請對應的公眾號的APP Key //第一步:取全域性access_token $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret; $token = getJson($url); //第二步:取得openid $oauth2Url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$_GET['code']."&grant_type=authorization_code"; $oauth2 = getJson($oauth2Url); //第三步:根據全域性access_token和openid查詢使用者資訊 $access_token = $token["access_token"]; $openid = $oauth2['openid']; $get_user_info_url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"; $userinfo = getJson($get_user_info_url); Var_dump($userinfo); function getJson($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); return json_decode($output, true); } function http_curl($url,$type='get',$res='json',$arr=''){ //1.例項化curl $ch = curl_init(); //2.設定curl引數 curl_setopt($ch,CURLOPT_URL,$url);//要訪問的url地址 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);//對認證證書的來源檢查 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//從證書中檢查SSL加密演算法是否存在 if($type=='post'){ curl_setopt($ch, CURLOPT_POST, 1);//傳送一個常規的POST請求 curl_setopt($ch, CURLOPT_POSTFIELDS,$arr);//post提交的資料包 } curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//獲取的資訊以檔案流的形式返回 //3.採集 $output = curl_exec($ch);//執行操作 if($res=='json'){ if(curl_errno($ch)){ return curl_error($ch); }else{ return json_decode($output,true); } } //4.關閉 curl_close($ch); }
獲取資訊格式
array(16) {
[“subscribe”]=>
int(1)
[“openid”]=>
string(28) “oEuSRwmEaaw6ozzYlJPYIyOtg1co”
[“nickname”]=>
string(6) “微信名”
[“sex”]=>
int(2)
[“language”]=>
string(5) “zh_CN”
[“city”]=>
string(6) “市”
[“province”]=>
string(6) “省”
[“country”]=>
string(6) “中國”
[“headimgurl”]=>
string(137) ") “ http://thirdwx.qlogo.cn/mmopen/vJ90HLKGHicnoc4SyxqLzxqiamWrwJpGOAbpDAicxqib3kXENNZmscYqMUO5orWHYuxpDhZMMoibnZrPD1pvHFBd9OicAOuXTgfJWZ/132”
"
[“subscribe_time”]=>
int(1541230987)
[“remark”]=>
string(0) “”
[“groupid”]=>
int(0)
[“tagid_list”]=>
array(0) {
}
[“subscribe_scene”]=>
string(16) “ADD_SCENE_SEARCH”
[“qr_scene”]=>
int(0)
[“qr_scene_str”]=>
string(0) “”
}
修改粉絲標籤
$url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$access_token;
$posts = array(
"openid" => $openid,
"to_groupid" => $label,
);
$post = json_encode($posts);
$change = http_curl($url,'post','json',$post);