苏飞论坛

标题: Asp.net【企业微信开发】(七)授权登录回调方法 [打印本页]

作者: 范范    时间: 2021-7-9 16:27
标题: Asp.net【企业微信开发】(七)授权登录回调方法


企业微信的的登录操作中, 不管是企业微信点击应用登录,或者是pc端的二维码扫码登录中, 都需要进行回调页面处理

在回调页面中, 我们可以根据微信回调的code, 进行登录用户信息获取, 并与数据库中存储的用户进行匹配, 从而登录成功,进入应用主页

回调页面方法如下:
[C#] 纯文本查看 复制代码
protected void Page_Load(object sender, EventArgs e)
        {
            var code = this.Request.Params["code"];
            var ret_url = this.Request.Params["ret_url"];

            LogHelper.WriteLog(code);
            if (!string.IsNullOrEmpty(code))
            {
                // 处理登录状态, 保存cookie, 并跳转到index
                //获取访问用户身份
                var url = $"https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token={AccessTokenHelper.get_suite_access_token()}&code={code}";

                HttpHelper http = new HttpHelper();
                HttpResult result = http.GetHtml(new HttpItem()
                {
                    URL = url,
                    ContentType = "application/x-www-form-urlencoded",
                    Method = "get",
                    Encoding = Encoding.UTF8
                });
               
                var html = JsonConvert.DeserializeObject<weixin_login_return_info>(result.Html);
                if (html.errcode == 0)
                {
                    // 查询用户数据,并添加cookie
                    var userbll = new sys_userBLL();
                    sys_user user_info = userbll.FindListOne($"wx_userid='{html.UserId}' and impower=1 and userflag=1 and comid=(select comid from sys_company where corpid='{html.CorpId}')");
                    if (user_info != null)
                    {
                        LoginHelper.Login(user_info.uid, "");
                        if (!string.IsNullOrEmpty(ret_url)) { Response.Redirect(ret_url); }
                        else { Response.Redirect("/PhoneCRM/Home/index.aspx"); }
                    }
                }
            }
        }
    }
}


从上面代码中可以看到, 我们根据微信回调的code, 与accessToken一起,获取用户信息,并根据返回的用户信息, 获取数据库中的用户信息, 找到用户信息后,记录cookie, 并登录成天, 跳转到对应页面

作者: xyc    时间: 2021-7-9 18:08
支持支持




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4