微信开放平台第三方登录(二)

来源:互联网 发布:中国保险网络大学网站 编辑:程序博客网 时间:2024/05/01 18:55

微信第三方登录

微信第三方登录其实我很简单 写好之后 授权 授权以后 在输入网址 网页就是一个我二维码了,用微信扫一扫 就可以看到 登录


直接上代码

   第一步: 根据开发者文档首先判断code是不是有值,如果没有值说明需要调用接口获取code 代码如下

         var code = Request.QueryString["Code"];
            if (string.IsNullOrEmpty(code))
            {
              Response.Redirect("https://open.weixin.qq.com/connect/qrconnect?appid=" + appid + "&redirect_uri=" + Utils.UrlEncode(shouquanyu) + "&response_type=code&  scope=snsapi_login&state=awen#wechat_redirect");
          }

介绍一下appid就是开放平台里面给的 ,shouquanyu 是请求之后携带参数需要跳转的页面,需要注意的是这个URL 字符串需要编码

Utils类 封装的

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

//第一步:通过code来获取Access Token以及openid

   Dictionary<string, object> dic1 = Weixin_helper.get_access_token(code, state);

Weixin_helper类中get_access_token方法如下:

       private static string componentAppId = WebConfigurationManager.AppSettings["devlopID"];
        private static string componentAppSecret = WebConfigurationManager.AppSettings["devlogPsw"];
        public static readonly string Token = WebConfigurationManager.AppSettings["Token"];//与微信公众账号后台的Token设置保持一致,区分大小写。
        public static readonly string EncodingAESKey = WebConfigurationManager.AppSettings["AccessToken"];//与微信公众账号后台的EncodingAESKey设置保持一致,区分大小写。
       // public string AccessToken = ""; //获取的通行证
       
       /// <summary>
        /// 取得临时的Access Token(默认过期时间为2小时)
        /// </summary>
        /// <param name='code'>临时Authorization Code</param>
        /// <param name='state'>防止CSRF攻击,成功授权后回调时会原样带回</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> get_access_token(string code, string state)
        {
            //AccessData acc = new AccessData();
            //acc.Write("code:" + code + ",componentAppId:" + componentAppId + ",componentAppSecret:" + componentAppSecret);
            //获得配置信息  
            string send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + componentAppId+ "&secret=" + componentAppSecret+ "&code="+ code +"&grant_type=authorization_code";
            //发送并接受返回值
            string result = Functions.webRequestGet(send_url);
            //acc.Write("进入获取get_access_token,result:" + result);
            if (result.Contains("errmsg"))
            {
                return null;
            }
            try
            {
                Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                return dic;
            }
            catch
            {
                return null;
            }
        }


这样就可以得到 一个Dictionary<string, object> 里面的值就是微信号的信息

    if (dic1 == null || !dic1.ContainsKey("access_token"))
                {
                    // return Content('错误代码:,无法获取Access Token,请检查App Key是否正确!');
                }
                if (dic1 == null || !dic1.ContainsKey("openid"))
                {
                    if (dic1.ContainsKey("errmsg"))
                    {
                        //return Content('errcode:' + dic1['errcode'] + ',errmsg:' + dic1['errmsg']);
                    }
                    else
                    {
                        // return Content('出错啦,无法获取用户授权Openid!');
                    }
                }
                access_token = dic1["access_token"].ToString();//获取access_token
                expires_in = dic1["expires_in"].ToString();//获取过期时间
                refresh_token = dic1["refresh_token"].ToString();//获取用于重新刷新access_token的凭证
                openid = dic1["openid"].ToString();//用户唯一标示openid



            //#endregion
            ////第二步:通过Access Token以及openid来获取用户的基本信息
            Dictionary<string, object> dic2 = Weixin_helper.get_user_info(access_token, openid);

       Weixin_helper类的get_user_info方法


      /// <summary>
        /// 获取登录用户自己的基本资料
        /// </summary>
        /// <param name='access_token'>临时的Access Token</param>
        /// <param name='open_id'>用户openid</param>
        /// <returns>Dictionary</returns>
        public static Dictionary<string, object> get_user_info(string access_token, string open_id)
        {
            //获得配置信息
            
            //发送并接受返回值   
            string send_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+open_id;
            //发送并接受返回值
            string result = Functions.webRequestGet(send_url);
            if (result.Contains("errmsg"))
            {
                return null;
            }
            //反序列化JSON
            Dictionary<string, object> dic = JsonToDictionary(result);
            return dic;
        }

            ////第三步:跳转到指定页面
            return Content(WeChatResultJson());



0 0
原创粉丝点击