微信公衆平臺開發—利用OAuth2.0獲取微信用戶基本信息
1、首先在某微信平臺下配置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。
微信授權頁面如下:
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 + "<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);
- OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(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<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; }
- }
- }
- /// <summary>
- /// 用戶信息類
- /// </summary>
- 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>
- public string openid
- {
- set { _openID = value; }
- get { return _openID; }
- }
- /// <summary>
- ///
- /// </summary>
- public string SearchText
- {
- set { _searchText = value; }
- get { return _searchText; }
- }
- /// <summary>
- /// 用戶暱稱
- /// </summary>
- public string nickname
- {
- set { _nickname = value; }
- get { return _nickname; }
- }
- /// <summary>
- /// 用戶的性別,值爲1時是男性,值爲2時是女性,值爲0時是未知
- /// </summary>
- public string sex
- {
- set { _sex = value; }
- get { return _sex; }
- }
- /// <summary>
- /// 用戶個人資料填寫的省份
- /// </summary>
- public string province
- {
- set { _province = value; }
- get { return _province; }
- }
- /// <summary>
- /// 普通用戶個人資料填寫的城市
- /// </summary>
- public string city
- {
- set { _city = value; }
- get { return _city; }
- }
- /// <summary>
- /// 國家,如中國爲CN
- /// </summary>
- public string country
- {
- set { _country = value; }
- get { return _country; }
- }
- /// <summary>
- /// 用戶頭像,最後一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項爲空
- /// </summary>
- public string headimgurl
- {
- set { _headimgUrl = value; }
- get { return _headimgUrl; }
- }
- /// <summary>
- /// 用戶特權信息,json 數組,如微信沃卡用戶爲(chinaunicom)其實這個格式稱不上JSON,只是個單純數組
- /// </summary>
- public string privilege
- {
- set { _privilege = value; }
- get { return _privilege; }
- }
- #endregion
- }
- /// <summary>
- /// 將Json格式數據轉化成對象
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 獲取Json的Model
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="szJson"></param>
- /// <returns></returns>
- 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);
- }
- }
- }