微信公共服务平台开发(.Net 的实现)13-------网页授权(下 :C#代码的实现 )

接着上次的理论,我们这次来研究用代码实现“网页授权获取用户基本信息”,首先我们需要一个链接指向微信的授权页面,在微信开发平台中已经说了,这个链接必须在微信客户端中打开,那么我们就干脆使用文本消息来完成吧,也就是说当我们发送“授权”两个字的时候,微信给我们一个链接,我们点击这个链接然后进入“授权页面”。首先改造一下我们OnLoad函数:

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. if (wx.MsgType == "text" && wx.Content == "你好")  
  2.              {  
  3.                   
  4.                  res = sendTextMessage(wx, "你好,欢迎使用北京永杰友信科技有限公司公共微信平台!");  
  5.              }  
  6.              else if (wx.MsgType == "text" && wx.Content == "授权")  
  7.              {  
  8.                  string MyAppid = "wx043225275885dafd";  
  9.                  string RedirectUri = "http://wx.4ugood.net/OAuthRedirectUri.aspx";  
  10.                  string URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + MyAppid + "&redirect_uri=" + RedirectUri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect" ;     
  11.                  string Str = "<a href='" + URL + "'>授权页面</a>";  
  12.                  res = sendTextMessage(wx, Str);  
  13.              }  
  14.              else if (wx.MsgType == "voice")  
  15.              {  
  16.                  res = sendTextMessage(wx, wx.Recognition);  
  17.              }  
  18.              else if (wx.MsgType == "location")  
  19.              {  
  20.                  res = sendTextMessage(wx, "您发送的位置是:" + wx.Label + ";纬度是:" + wx.Location_X + ";经度是:" + wx.Location_Y + ";缩放比例为:" + wx.Scale);  
  21.              }  
  22.              else  
  23.              {  
  24.                  res = sendTextMessage(wx, "你好,未能识别消息!");  
  25.              }  


其中,MyAppid不用说了,RedirectUri 是我们跳转后的网页,等会儿就会看到代码,URL是微信给出的格式,我们直接使用就OK了。这样就会反馈一个链接,点击就可以进入授权的页面了。
下面我们来看看RedirectUri参数的OAuthRedirectUri.aspx页面的源码吧,因为是讲解的例子,以说明问题为主,我就简化了其中也布局,OAuthRedirectUri.aspx.cs的内容如下:
首先我们用到了两个类:OAuth_Token和OAuthUser

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class OAuth_Token  
  2. {  
  3.     public OAuth_Token()  
  4.     {  
  5.   
  6.         //  
  7.         //TODO: 在此处添加构造函数逻辑  
  8.         //  
  9.     }  
  10.     //access_token  网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同  
  11.     //expires_in    access_token接口调用凭证超时时间,单位(秒)  
  12.     //refresh_token 用户刷新access_token  
  13.     //openid    用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID  
  14.     //scope 用户授权的作用域,使用逗号(,)分隔  
  15.     public string access_token { get; set; }  
  16.     public string expires_in { get; set; }  
  17.     public string refresh_token { get; set; }  
  18.     public string openid { get; set; }  
  19.     public string scope { get; set; }  
  20.   
  21. }  
  22.   
  23.   
  24. public class OAuthUser  
  25. {  
  26.     public OAuthUser()  
  27.     { }  
  28.     #region 数据库字段  
  29.     private string _openID;  
  30.     private string _searchText;  
  31.     private string _nickname;  
  32.     private string _sex;  
  33.     private string _province;  
  34.     private string _city;  
  35.     private string _country;  
  36.     private string _headimgUrl;  
  37.     private string _privilege;  
  38.     #endregion  
  39.  
  40.     #region 字段属性  
  41.     /// <summary>  
  42.     /// 用户的唯一标识  
  43.     /// </summary>  
  44.     public string openid  
  45.     {  
  46.         set { _openID = value; }  
  47.         get { return _openID; }  
  48.     }  
  49.     /// <summary>  
  50.     ///   
  51.     /// </summary>  
  52.     public string SearchText  
  53.     {  
  54.         set { _searchText = value; }  
  55.         get { return _searchText; }  
  56.     }  
  57.     /// <summary>  
  58.     /// 用户昵称   
  59.     /// </summary>  
  60.     public string nickname  
  61.     {  
  62.         set { _nickname = value; }  
  63.         get { return _nickname; }  
  64.     }  
  65.     /// <summary>  
  66.     /// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知   
  67.     /// </summary>  
  68.     public string sex  
  69.     {  
  70.         set { _sex = value; }  
  71.         get { return _sex; }  
  72.     }  
  73.     /// <summary>  
  74.     /// 用户个人资料填写的省份  
  75.     /// </summary>  
  76.     public string province  
  77.     {  
  78.         set { _province = value; }  
  79.         get { return _province; }  
  80.     }  
  81.     /// <summary>  
  82.     /// 普通用户个人资料填写的城市   
  83.     /// </summary>  
  84.     public string city  
  85.     {  
  86.         set { _city = value; }  
  87.         get { return _city; }  
  88.     }  
  89.     /// <summary>  
  90.     /// 国家,如中国为CN   
  91.     /// </summary>  
  92.     public string country  
  93.     {  
  94.         set { _country = value; }  
  95.         get { return _country; }  
  96.     }  
  97.     /// <summary>  
  98.     /// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空  
  99.     /// </summary>  
  100.     public string headimgurl  
  101.     {  
  102.         set { _headimgUrl = value; }  
  103.         get { return _headimgUrl; }  
  104.     }  
  105.     /// <summary>  
  106.     /// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)其实这个格式称不上JSON,只是个单纯数组  
  107.     /// </summary>  
  108.     public string privilege  
  109.     {  
  110.         set { _privilege = value; }  
  111.         get { return _privilege; }  
  112.     }  
  113.     #endregion  
  114. }  

然后是OAuthRedirectUri.aspx.cs的全部内容:

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public partial class OAuthRedirectUri : System.Web.UI.Page  
  2. {  
  3.   
  4.     string Appid = "wx043225275885dafd";  
  5.     string appsecret = "cb4425b24ab79ef875029cf0bf326ae9";  
  6.     protected void Page_Load(object sender, EventArgs e)  
  7.     {  
  8.         if (!IsPostBack)  
  9.         {  
  10.             if (!string.IsNullOrEmpty(Request.QueryString["code"]))  
  11.             {  
  12.                 string Code = Request.QueryString["code"].ToString();  
  13.                 //获得Token  
  14.                 OAuth_Token Model = Get_token(Code);  
  15.                 //Response.Write(Model.access_token);  
  16.                 OAuthUser OAuthUser_Model = Get_UserInfo(Model.access_token, Model.openid);  
  17.                 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);  
  18.                   
  19.             }  
  20.         }  
  21.     }  
  22.   
  23.     //获得Token  
  24.     protected OAuth_Token Get_token(string Code)  
  25.     {  
  26.         string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + appsecret + "&code=" + Code + "&grant_type=authorization_code");  
  27.         OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str);  
  28.         return Oauth_Token_Model;  
  29.     }  
  30.     //刷新Token  
  31.     protected OAuth_Token refresh_token(string REFRESH_TOKEN)  
  32.     {  
  33.         string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Appid + "&grant_type=refresh_token&refresh_token=" + REFRESH_TOKEN);  
  34.         OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str);  
  35.         return Oauth_Token_Model;  
  36.     }  
  37.     //获得用户信息  
  38.     protected OAuthUser Get_UserInfo(string REFRESH_TOKEN, string OPENID)  
  39.     {  
  40.        // Response.Write("获得用户信息REFRESH_TOKEN:" + REFRESH_TOKEN + "||OPENID:" + OPENID);  
  41.         string Str = GetJson("https://api.weixin.qq.com/sns/userinfo?access_token=" + REFRESH_TOKEN + "&openid=" + OPENID);  
  42.         OAuthUser OAuthUser_Model = JsonHelper.ParseFromJson<OAuthUser>(Str);  
  43.         return OAuthUser_Model;  
  44.     }  
  45.     protected string GetJson(string url)  
  46.     {  
  47.         WebClient wc = new WebClient();  
  48.         wc.Credentials = CredentialCache.DefaultCredentials;  
  49.         wc.Encoding = Encoding.UTF8;  
  50.         string returnText = wc.DownloadString(url);  
  51.   
  52.         if (returnText.Contains("errcode"))  
  53.         {  
  54.             //可能发生错误  
  55.         }  
  56.         //Response.Write(returnText);  
  57.         return returnText;  
  58.     }  
  59. }  


其中用到的JsonHelper类在 《微信公共服务平台开发(.Net 的实现)5-------解决access_token过期的问题》  也提到过,不再粘贴了。这样我们就实现了授权到拉取用户信息的功能了。

原文地址:https://www.cnblogs.com/Alex80/p/4259200.html