接着上次的理论,我们这次来研究用代码实现“网页授权获取用户基本信息”,首先我们需要一个链接指向微信的授权页面,在微信开发平台中已经说了,这个链接必须在微信客户端中打开,那么我们就干脆使用文本消息来完成吧,也就是说当我们发送“授权”两个字的时候,微信给我们一个链接,我们点击这个链接然后进入“授权页面”。首先改造一下我们OnLoad函数:
[csharp] view plaincopy
- if (wx.MsgType == "text" && wx.Content == "你好")
- {
- res = sendTextMessage(wx, "你好,欢迎使用北京永杰友信科技有限公司公共微信平台!");
- }
- else if (wx.MsgType == "text" && wx.Content == "授权")
- {
- string MyAppid = "wx043225275885dafd";
- string RedirectUri = "http://wx.4ugood.net/OAuthRedirectUri.aspx";
- 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" ;
- string Str = "<a href=‘" + URL + "‘>授权页面</a>";
- res = sendTextMessage(wx, Str);
- }
- else if (wx.MsgType == "voice")
- {
- res = sendTextMessage(wx, wx.Recognition);
- }
- else if (wx.MsgType == "location")
- {
- res = sendTextMessage(wx, "您发送的位置是:" + wx.Label + ";纬度是:" + wx.Location_X + ";经度是:" + wx.Location_Y + ";缩放比例为:" + wx.Scale);
- }
- else
- {
- res = sendTextMessage(wx, "你好,未能识别消息!");
- }
其中,MyAppid不用说了,RedirectUri 是我们跳转后的网页,等会儿就会看到代码,URL是微信给出的格式,我们直接使用就OK了。这样就会反馈一个链接,点击就可以进入授权的页面了。
下面我们来看看RedirectUri参数的OAuthRedirectUri.aspx页面的源码吧,因为是讲解的例子,以说明问题为主,我就简化了其中也布局,OAuthRedirectUri.aspx.cs的内容如下:
首先我们用到了两个类:OAuth_Token和OAuthUser
[csharp] view plaincopy
- 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 { get; set; }
- public string expires_in { get; set; }
- public string refresh_token { get; set; }
- public string openid { get; set; }
- public string scope { get; set; }
- }
- 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
- }
然后是OAuthRedirectUri.aspx.cs的全部内容:
[csharp] view plaincopy
- public partial class OAuthRedirectUri : System.Web.UI.Page
- {
- string Appid = "wx043225275885dafd";
- string appsecret = "cb4425b24ab79ef875029cf0bf326ae9";
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- if (!string.IsNullOrEmpty(Request.QueryString["code"]))
- {
- string Code = Request.QueryString["code"].ToString();
- //获得Token
- OAuth_Token Model = Get_token(Code);
- //Response.Write(Model.access_token);
- OAuthUser OAuthUser_Model = Get_UserInfo(Model.access_token, Model.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);
- }
- }
- }
- //获得Token
- protected OAuth_Token Get_token(string Code)
- {
- string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + appsecret + "&code=" + Code + "&grant_type=authorization_code");
- OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str);
- return Oauth_Token_Model;
- }
- //刷新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;
- }
- //获得用户信息
- protected OAuthUser Get_UserInfo(string REFRESH_TOKEN, string OPENID)
- {
- // Response.Write("获得用户信息REFRESH_TOKEN:" + REFRESH_TOKEN + "||OPENID:" + 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;
- }
- 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"))
- {
- //可能发生错误
- }
- //Response.Write(returnText);
- return returnText;
- }
- }
其中用到的JsonHelper类在 《微信公共服务平台开发(.Net 的实现)5-------解决access_token过期的问题》 也提到过,不再粘贴了。这样我们就实现了授权到拉取用户信息的功能了。
时间: 2024-10-07 01:10:59