微信公众平台开发—利用OAuth2.0获取微信用户基本信息

时间:2022-05-07 11:29:35

在借鉴前两篇获取微信用户基本信息的基础下,本人也总结整理了一些个人笔记:如何通过OAuth2.0获取微信用户信息

1、首先在某微信平台下配置OAuth2.0授权回调页面:

微信公众平台开发—利用OAuth2.0获取微信用户基本信息

2、通过appid构造url获取微信回传code值(appid可在微信平台下找到)

1)、微信不弹出授权页面url:

A、code回传到页面wxProcess2.aspx,不带参数

Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://localhost:8888/wxProcess2.aspx&response_type=code&scope=snsapi_base&state=1#wechat_redirect");

B、code回传到页面wxProcess2.aspx,带参数reurl,即wxProcess2.aspx获得code的同时,也能获取reurl的值,具体如下:

Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://localhost:8888/wxProcess2.aspx?reurl=" + reurl +"&response_type=code&scope=snsapi_base&state=1#wechat_redirect");

2)、微信弹出授权页面url:需要用户授权,才能获取code及后面需要获取的用户信息

Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://localhost:8888/wxProcess2.aspx?reurl=" + reurl + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");

说明:微信是否弹出授权页面url的区别只在一个参数scope,不弹出微信授权页面:scope=snsapi_base,弹出微信授权页面:scope=snsapi_userinfo。

微信授权页面如下:

微信公众平台开发—利用OAuth2.0获取微信用户基本信息

3、通过appid、secret、code构造url,获取微信用户的openid和access token。appid、secret可在微信平台下找到,code已在上面方法中获取并回传。具体访问url:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + Code + "&grant_type=authorization_code

4、通过openid、access token获取用户信息,具体访问url:

https://api.weixin.qq.com/sns/userinfo?access_token=" + REFRESH_TOKEN + "&openid=" + OPENID

说明:主要通过访问微信的3个url地址并回传数据,获取微信用户基本信息

====================================================================

具体代码:

1、获取微信code处理页面:wxProcess.aspx

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string reurl = "";
            //传递参数,获取用户信息后,可跳转到自己定义的页面,想怎么处理就怎么处理
            if (Request.QueryString["reurl"] != null && Request.QueryString["reurl"] != "")
            {
                reurl = Request.QueryString["reurl"].ToString();
            }
            else
            {
                reurl = "http://www.csdn.net";
            }

string code = "";

//弹出授权页面(如在不弹出授权页面基础下未获得openid,则弹出授权页面,提示用户授权)
            if (Request.QueryString["auth"] != null && Request.QueryString["auth"] != "" && Request.QueryString["auth"] == "1")
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://localhost:8888/wxProcess2.aspx?reurl=" + reurl + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
            }
            else
            {
                //不弹出授权页面
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=http://localhost:8888/wxProcess2.aspx?reurl=" + reurl + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect");            }
        }
    }

2、获取微信code值回传到自己的页面wxProcess2.aspx:

public string reurl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //获取从wxProcess.aspx传递过来的跳转地址reurl
            if (Request.QueryString["reurl"] != null && Request.QueryString["reurl"] != "")
            {
                reurl = Request.QueryString["reurl"].ToString();
            }

string code = "";
            if (Request.QueryString["code"] != null && Request.QueryString["code"] != "")
            {
                //获取微信回传的code
                code = Request.QueryString["code"].ToString();  
                OAuth_Token Model = Get_token(code);  //获取token
                OAuthUser OAuthUser_Model = Get_UserInfo(Model.access_token, Model.openid );
                if(OAuthUser_Model.openid!=null && OAuthUser_Model.openid !="")  //已获取得openid及其他信息
                {
                    //在页面上输出用户信息
                    Response.Write("用户OPENID:" + OAuthUser_Model.openid + "
用户昵称:" + OAuthUser_Model.nickname + "
性别:" + OAuthUser_Model.sex + "
所在省:" + OAuthUser_Model.province + "
所在市:" + OAuthUser_Model.city + "
所在国家:" + OAuthUser_Model.country + "
头像地址:" + OAuthUser_Model.headimgurl + "
用户特权信息:" + OAuthUser_Model.privilege);
                    //或跳转到自己的页面,想怎么处理就怎么处理
                    Response.Redirect(reurl);
                }
                else  //未获得openid,回到wxProcess.aspx,访问弹出微信授权页面
                {
                    Response.Redirect("wxProcess.aspx?auth=1");
                }
            }
        }
    }

#region 属性
    public string appid = "wx6669e231bffa123f";  //公众微信平台下可以找到
    public string appsecret = "9d693f7a81236c123464281115p78445";  //公众微信平台下可以找到
    #endregion

//根据appid,secret,code获取微信openid、access token信息
    protected OAuth_Token Get_token(string Code)
    {
        //获取微信回传的openid、access token
        string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + Code + "&grant_type=authorization_code");
        //微信回传的数据为Json格式,将Json格式转化成对象
        OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson(Str);
        return Oauth_Token_Model;
    }

//刷新Token(好像这个刷新Token没有实际作用)
    protected OAuth_Token refresh_token(string REFRESH_TOKEN)
    {
        string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + REFRESH_TOKEN);
        OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson(Str);
        return Oauth_Token_Model;
    }

//根据openid,access token获得用户信息
    protected OAuthUser Get_UserInfo(string REFRESH_TOKEN, string OPENID)
    {
        string Str = GetJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + REFRESH_TOKEN + "&openid=" + OPENID);
        OAuthUser OAuthUser_Model = JsonHelper.ParseFromJson(Str);
        return OAuthUser_Model;
    }

//访问微信url并返回微信信息
    protected string GetJson(string url)
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultCredentials;
        wc.Encoding = Encoding.UTF8;
        string returnText = wc.DownloadString(url);

if (returnText.Contains("errcode"))
        {
            //可能发生错误
        }
        return returnText;
    }

///
    /// token类
    ///
    public class OAuth_Token
    {
        public OAuth_Token()
        {

//
            //TODO: 在此处添加构造函数逻辑
            //
        }
        //access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
        //expires_in access_token接口调用凭证超时时间,单位(秒)
        //refresh_token 用户刷新access_token
        //openid 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
        //scope 用户授权的作用域,使用逗号(,)分隔
        public string _access_token;
        public string _expires_in;
        public string _refresh_token;
        public string _openid;
        public string _scope;
        public string access_token
        {
            set { _access_token = value; }
            get { return _access_token; }
        }
        public string expires_in
        {
            set { _expires_in = value; }
            get { return _expires_in; }
        }

public string refresh_token
        {
            set { _refresh_token = value; }
            get { return _refresh_token; }
        }
        public string openid
        {
            set { _openid = value; }
            get { return _openid; }
        }
        public string scope
        {
            set { _scope = value; }
            get { return _scope; }
        }

}

///
    /// 用户信息类
    ///
    public class OAuthUser
    {
        public OAuthUser()
        { }
        #region 数据库字段
        private string _openID;
        private string _searchText;
        private string _nickname;
        private string _sex;
        private string _province;
        private string _city;
        private string _country;
        private string _headimgUrl;
        private string _privilege;
        #endregion

#region 字段属性
        ///
        /// 用户的唯一标识
        ///
        public string openid
        {
            set { _openID = value; }
            get { return _openID; }
        }
        ///
        ///
        ///
        public string SearchText
        {
            set { _searchText = value; }
            get { return _searchText; }
        }
        ///
        /// 用户昵称
        ///
        public string nickname
        {
            set { _nickname = value; }
            get { return _nickname; }
        }
        ///
        /// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
        ///
        public string sex
        {
            set { _sex = value; }
            get { return _sex; }
        }
        ///
        /// 用户个人资料填写的省份
        ///
        public string province
        {
            set { _province = value; }
            get { return _province; }
        }
        ///
        /// 普通用户个人资料填写的城市
        ///
        public string city
        {
            set { _city = value; }
            get { return _city; }
        }
        ///
        /// 国家,如中国为CN
        ///
        public string country
        {
            set { _country = value; }
            get { return _country; }
        }
        ///
        /// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
        ///
        public string headimgurl
        {
            set { _headimgUrl = value; }
            get { return _headimgUrl; }
        }
        ///
        /// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)其实这个格式称不上JSON,只是个单纯数组
        ///
        public string privilege
        {
            set { _privilege = value; }
            get { return _privilege; }
        }
        #endregion
    }

///
    /// 将Json格式数据转化成对象
    ///
    public class JsonHelper
    {
        ///  
        /// 生成Json格式 
        ///  
        ///  
        ///  
        ///  
        public static string GetJson(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
            }
        }
        ///  
        /// 获取Json的Model 
        ///  
        ///  
        ///  
        ///  
        public static T ParseFromJson(string szJson)
        {
            T obj = Activator.CreateInstance();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
    }

输出微信用户信息: