微信 获取openid

function get_code(){
    if (!session("wx_info")){
        $code = $_GET["code"];
        if(empty($code)){
                $url = str_replace ( "&" ,  "%26" ,  $_SERVER["REQUEST_URI"] );
                header("location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C(‘WX_APPID‘)."&redirect_uri=http://".$_SERVER[‘HTTP_HOST‘].$url."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
        exit;    
        }else{
            $userinfo = getUserInfo($code);
            session("wx_info",$userinfo);
            
        }
    }
    if (!session("wx_info")){
        echo ‘微信获取信息失败! ‘;
        exit;
    }
}

    //微信接口
    function getUserInfo($code) {
        $appid = C(‘WX_APPID‘);
        $appsecret = C(‘WX_APPSECRET‘);
        $access_token = "";
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array[‘access_token‘];
        $openid = $access_token_array[‘openid‘];
        session("open_id",$openid);
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo_json = https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json, true);
        return $userinfo_array;
    }
    function https_request($url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $data = curl_exec($curl);
            if (curl_errno($curl)) {return ‘ERROR ‘.curl_error($curl);}
            curl_close($curl);
            return $data;
     }
    

首先获取code,有了code之后使用函数getUserInfo()来获取用户信息,包括openid,用户昵称,头像等。

好像只有公众号才能获取openid,订阅号不能。

微信 获取openid

上一篇:MVC微信浏览器图片上传(img转Base64)


下一篇:微信公众平台