微信开发笔记——微信网页登录授权,获取用户信息

 
开源源码下载,请参照csdn下载:  http://download.csdn.net/detail/kingmax54212008/9453082


最近做了一个公司的微信的公众号,对微信的流程清楚了不少,这里记录下,算不上多高深的,只希望能帮助到一部分人吧。

 

闲话少说,开始:

首先大家要看下微信的API文档。

微信网页授权,获取用户的微信官方API文档地址:
http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

三次握手
微信认证流程(我自己简称三次握手):

1、用户同意授权,获取code
2、通过code换取网页授权access_token,用户openId等信息
3、通过access_token和用户的openId获取该用户的用户信息

思路:
经过研究,我这边的思路是:让所有页面都继承同一个页面,在这个页面里做微信登录授权处理,
因为第一步必须要经过微信的登录授权,不能网页后端请求,所以先要经过用户同意,通过页面网页请求组装的微信请求链接。请求该链接,
获取code后,后端模拟请求。获取用户信息。

微信三次握手的方法(代码)

public class WeiXinOAuth{    /// <summary>    /// 获取微信Code    /// </summary>    /// <param name="appId"></param>    /// <param name="appSecret"></param>    /// <param name="redirectUrl"></param>    public string GetWeiXinCode(string appId,string appSecret,string redirectUrl)    {        Random r = new Random();        //微信登录授权        //string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";        //微信OpenId授权        //string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";        //微信用户信息授权        string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";        return url;    }    /// <summary>    /// 通过code获取access_token    /// </summary>    /// <param name="appId"></param>    /// <param name="appSecret"></param>    /// <param name="code"></param>    /// <returns></returns>    public Model.WeiXinAccessTokenResult GetWeiXinAccessToken(string appId,string appSecret,string code)    {        string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+            "&code="+ code + "&grant_type=authorization_code";        string jsonStr = Tools.GetHttpRequest(url);        Model.WeiXinAccessTokenResult result = new Model.WeiXinAccessTokenResult();        if (jsonStr.Contains("errcode"))        {            Model.WeiXinErrorMsg errorResult = new Model.WeiXinErrorMsg();            errorResult=JsonHelper.ParseFromJson<Model.WeiXinErrorMsg>(jsonStr);            result.ErrorResult = errorResult;            result.Result = false;        }        else        {            Model.WeiXinAccessTokenModel model = new Model.WeiXinAccessTokenModel();            model = JsonHelper.ParseFromJson<Model.WeiXinAccessTokenModel>(jsonStr);            result.SuccessResult = model;            result.Result = true;        }        return result;    }    /// <summary>    /// 拉取用户信息    /// </summary>    /// <param name="accessToken"></param>    /// <param name="openId"></param>    /// <returns></returns>    public Model.WeiXinUserInfoResult GetWeiXinUserInfo(string accessToken,string openId)    {        string url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";        string jsonStr = Tools.GetHttpRequest(url);        Model.WeiXinUserInfoResult result = new Model.WeiXinUserInfoResult();        if(jsonStr.Contains("errcode"))        {            Model.WeiXinErrorMsg errorResult = new Model.WeiXinErrorMsg();            errorResult = JsonHelper.ParseFromJson<Model.WeiXinErrorMsg>(jsonStr);            result.ErrorMsg = errorResult;            result.Result = false;        }        else        {            Model.WeiXinUserInfo userInfo = new Model.WeiXinUserInfo();            userInfo = JsonHelper.ParseFromJson<Model.WeiXinUserInfo>(jsonStr);            result.UserInfo = userInfo;            result.Result = true;        }        return result;    }}

所需要的对应实体类

WeiXinAccessTokenResult 类:

View Code
WeiXinAccessTokenModel类:
View Code
WeiXinErrorMsg类:
View Code
WeiXinUserInfoResult类:
 
View Code
WeiXinUser 类 :
View Code
所有的页面,都会继承BasePage页面,这样方便处理,继承这个页面的其他页面就不需要考虑认证的问题了。
public partial class BasePage : System.Web.UI.Page{    public BasePage()    {        this.Page.Load += new EventHandler(Page_Load);        this.Page.Unload += new EventHandler(Page_UnLoad);    }    protected void Page_Load(object sender, EventArgs e)    {        DoWith();    }    protected void Page_UnLoad(object sender, EventArgs e)    {    }    private void DoWith()    {        //用户尚未登录        if (BLL.UserInfoManager.Instance().GetUserId() <= 0)        {            //获取appId,appSecret的配置信息            string appId = System.Configuration.ConfigurationSettings.AppSettings["appid"];            string appSecret = System.Configuration.ConfigurationSettings.AppSettings["secret"];            Core.WeiXinOAuth weixinOAuth = new WeiXinOAuth();            //微信第一次握手后得到的code 和state            string _code = Cmn.Request.Get("code");            string _state = Cmn.Request.Get("state");            if (_code == "" || _code == "authdeny")            {                if (_code == "")                {                    //发起授权(第一次微信握手)                    string _authUrl = weixinOAuth.GetWeiXinCode(appId, appSecret, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString()));                    HttpContext.Current.Response.Redirect(_authUrl, true);                }                else                { // 用户取消授权                    HttpContext.Current.Response.Redirect("~/Error.html", true);                }            }            else            {                //获取微信的Access_Token(第二次微信握手)                Core.Model.WeiXinAccessTokenResult modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, _code);                //获取微信的用户信息(第三次微信握手)                Core.Model.WeiXinUserInfoResult _userInfo = weixinOAuth.GetWeiXinUserInfo(modelResult.SuccessResult.access_token,modelResult.SuccessResult.openid);                //用户信息(判断是否已经获取到用户的微信用户信息)                if (_userInfo.Result && _userInfo.UserInfo.openid != "")                {                    //保存获取到的用户微信用户信息,并保存到数据库中                }                else                {                    GameTradingByPublic.ExceptionLog.writeFile(2, "获取用户OpenId失败");                }            }        }    }}

 

  •  
开源源码下载,请参照csdn下载:   http://download.csdn.net/detail/kingmax54212008/9453082


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值