天天看點

微信公衆平台開發—利用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");  

                //不彈出授權頁面  

                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)  

            //擷取從wxProcess.aspx傳遞過來的跳轉位址reurl  

            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 + "<br>使用者昵稱:" + OAuthUser_Model.nickname + "<br>性别:" + OAuthUser_Model.sex + "<br>所在省:" + OAuthUser_Model.province + "<br>所在市:" + OAuthUser_Model.city + "<br>所在國家:" + OAuthUser_Model.country + "<br>頭像位址:" + OAuthUser_Model.headimgurl + "<br>使用者特權資訊:" + 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<OAuth_Token>(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);  

    //根據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<OAuthUser>(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;  

    /// <summary>  

    /// token類  

    /// </summary>  

    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 字段屬性  

        /// <summary>  

        /// 使用者的唯一辨別  

        /// </summary>  

            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; }  

    /// 将Json格式資料轉化成對象  

    public class JsonHelper  

        /// <summary>    

        /// 生成Json格式    

        /// </summary>    

        /// <typeparam name="T"></typeparam>    

        /// <param name="obj"></param>    

        /// <returns></returns>    

        public static string GetJson<T>(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    

        /// <param name="szJson"></param>    

        public static T ParseFromJson<T>(string szJson)  

            T obj = Activator.CreateInstance<T>();  

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))  

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());  

                return (T)serializer.ReadObject(ms);  

 輸出微信使用者資訊: