码迷,mamicode.com
首页 > 微信 > 详细

啊Ran讲微信开发(.net) :公众号(服务号)+自定义服务器(OAuth授权登录)

时间:2015-11-28 20:01:09      阅读:486      评论:0      收藏:0      [点我收藏+]

标签:

     上一篇我们探讨到自定义菜单key为view带有一个"url"参数的点击事件,这边我们就聊聊"微信授权登录".

1.网页授权接口

网页授权接口允许微信公众号的第三方网页获取微信个人用户的基本信息,包括昵称,头像,性别,城市,国家,注册时间等.利用微信个人用户的基本信息,可以实现体验优化,用户来源统计,账号绑定,用户身份鉴权等功能.

OAuth协议为用户资源的授权提供了一个安全的,开放而简易的标准,与以往的授权方式不同之处是OAuth的授权不会使第三方触及到用户的账户信息(如用户信息和密码),即第三方无须使用用户的用户名和密码就可以申请获得该用户资源的授权,因此OAuth是安全的.如果用户在微信客户端中访问第三方网页,则公众号可以通过微信网页授权机制来获取用户基本信息,进而实现业务逻辑.

获取用户基本信息接口是在用户和公众号产生消息交互时,才能根据用户OpenId获取用户的基本信息,而通过网页授权的方式获取用户基本信息,则无需消息交互,只要微信个人用户进入到微信公众号的网页,就会弹出请求用户授权的界面,用户授权之后,就可以获取基本信息,此过程甚至不需要用户已经关注公众号.

 

2.服务号的回调域名设置

用户在网页授权页同意授权给公众号后,微信会将授权数据传给一个回调页面,回调页面所在的域名都需要在微信公众管理后台进行登记,以确保安全可靠,所以在微信公众请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中页面配置授权回调域名.

注意:订阅号时没有此功能的,服务号才有.

技术分享

 

3.公众号的授权方式

公众号的网页授权有两种方式,一种是以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,在获取到用户的openid后,调用获取用户基本信息接口,获取用户的详细信息.此种方式是静默授权并且自动跳转到回调页面,给用户的感觉就是直接进入可想进的页面,但弊端是,如果用户并没有关注该公众号,则是无法使用"获取用户基本信息"接口的.另一种是以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息,但这种授权在当用户单击授权连接后,会跳转到一个询问用户是否同意的页面.由于这种方式已经用户同意,所以无需关注,就可以在授权后获取该用户的基本信息,并且,对于关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知.

4.网页授权access_token和access_token的区别

技术分享

 

5.授权步骤

技术分享

详细可以查看官方解释:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

 

6.代码实现

技术分享

        /// <summary>
        /// 获取微信Code
        /// </summary>
        /// <param name="appId">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 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);//发起请求

            WeiXinAccessTokenResult result = new WeiXinAccessTokenResult();
            if (jsonStr.Contains("errcode"))
            {
                WeiXinErrorMsg errorResult = new WeiXinErrorMsg();
                errorResult = JsonHelper.ParseFromJson<WeiXinErrorMsg>(jsonStr);
                result.ErrorResult = errorResult;
                result.Result = false;
            }
            else
            {
                WeiXinAccessTokenModel model = new WeiXinAccessTokenModel();
                model = JsonHelper.ParseFromJson<WeiXinAccessTokenModel>(jsonStr);//序列化
                result.SuccessResult = model;
                result.Result = true;
            }
            return result;
        }

技术分享

技术分享技术分享

        /// <summary>
        /// 刷新获取access_token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public WeiXinAccessTokenResult GetWeiXinRefreshAccessToken(string appId, string refresh_token)
        {
            string url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appId +
                "&grant_type=refresh_token&refresh_token=" + refresh_token;
            string jsonStr = Tools.GetHttpRequest(url);
            WeiXinAccessTokenResult result = new WeiXinAccessTokenResult();
            if (jsonStr.Contains("errcode"))
            {
                WeiXinErrorMsg errorResult = new WeiXinErrorMsg();
                errorResult = JsonHelper.ParseFromJson<WeiXinErrorMsg>(jsonStr);
                result.ErrorResult = errorResult;
                result.Result = false;
            }
            else
            {
                WeiXinAccessTokenModel model = new WeiXinAccessTokenModel();
                model = JsonHelper.ParseFromJson<WeiXinAccessTokenModel>(jsonStr);
                result.SuccessResult = model;
                result.Result = true;
            }
            return result;
        }

技术分享

技术分享

技术分享

注意,使用此接口是无法获取用户是否关注及关注时间.

        /// <summary>
        /// 拉取用户信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public 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);
            WeiXinUserInfoResult result = new WeiXinUserInfoResult();
            if (jsonStr.Contains("errcode"))
            {
                WeiXinErrorMsg errorResult = new WeiXinErrorMsg();
                errorResult = JsonHelper.ParseFromJson<WeiXinErrorMsg>(jsonStr);
                result.ErrorMsg = errorResult;
                result.Result = false;
            }
            else
            {
                WeiXinUserInfo userInfo = new WeiXinUserInfo();
                userInfo = JsonHelper.ParseFromJson<WeiXinUserInfo>(jsonStr);
                result.UserInfo = userInfo;
                result.Result = true;
            }
            return result;
        }

 

集成到pageBase.cs父类页面

技术分享
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()
        {
                //获取appId,appSecret的配置信息
                string appId = System.Configuration.ConfigurationSettings.AppSettings["appid"];
                string appSecret = System.Configuration.ConfigurationSettings.AppSettings["secret"];
                WeiXinOAuth weixinOAuth = new WeiXinOAuth();
                string _code = Request["code"];
                string _state = Request["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
                {
                    WeiXinAccessTokenResult modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, _code);

                    WeiXinUserInfoResult _userInfo = weixinOAuth.GetWeiXinUserInfo(modelResult.SuccessResult.access_token, modelResult.SuccessResult.openid);

                    //用户信息(判断是否已经获取到用户的微信用户信息)
                    if (_userInfo.Result && _userInfo.UserInfo.openid != "")
                    {
                        //保存获取到的用户微信用户信息,并保存到数据库中
                    }
                    else
                    {
                        //GameTradingByPublic.ExceptionLog.writeFile(2, "获取用户OpenId失败");
                    }
                }
        }
    }
View Code

 

啊Ran讲微信开发(.net) :公众号(服务号)+自定义服务器(OAuth授权登录)

标签:

原文地址:http://www.cnblogs.com/Francis-YZR/p/5002981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!