• 微信 获取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,订阅号不能。

  • 相关阅读:
    轻量级数据持久层Seaking.PL简介--Query对象
    轻量级数据持久层Seaking.PL简介及建议征集
    Google秘密搜索入口
    异常,究竟抛向何处?
    [转]深入讲解ASP+ 验证
    .Net卸载程序的制作
    性能测试:Reflection VS CodeDom
    小心文件夹名称中的特殊字符
    [转]用Web标准进行开发
    使用ASP.Net Forms模式实现WebService身份验证
  • 原文地址:https://www.cnblogs.com/tingfengqieyu/p/5462312.html
Copyright © 2020-2023  润新知