示例#1
0
        /// <summary>
        /// code换取openid和网页授权acctoken
        /// </summary>
        /// <returns></returns>
        private WxOauthModel GetOpenidByCode()
        {
            WxOauthModel res = new WxOauthModel();

            try
            {
                //第一步code换取accesstoken、openid
                string code = HttpContext.Current.Request.QueryString["code"]?.ToString();
                LogHelper.WriteLog("code:" + code);
                //获取网页授权accesstoken
                string   url      = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WchartApiConst.appid + "&secret=" + WchartApiConst.appsecret + "&code=" + code + "&grant_type=authorization_code";
                HttpItem httpItem = new HttpItem();
                httpItem.URL    = url;
                httpItem.Method = "GET";
                HttpHelper helper     = new HttpHelper();
                HttpResult httpResult = helper.GetHtml(httpItem);
                var        reshtml    = httpResult.Html;
                LogHelper.WriteLog("html1:" + reshtml);
                res = JsonConvert.DeserializeObject <WxOauthModel>(reshtml);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "GetOpenid");
            }
            return(res);
        }
示例#2
0
        public JsonResponse CodeLogin()
        {
            try
            {
                string       state     = HttpContext.Current.Request.QueryString["state"]?.ToString() ?? "";
                WxOauthModel info      = GetOpenidByCode();
                string       infomodel = System.Web.HttpContext.Current.Cache.Get(info.openid)?.ToString() ?? "";
                if (!string.IsNullOrEmpty(infomodel))
                {
                    WxUserBaseInfoModel baseinfo = JsonConvert.DeserializeObject <WxUserBaseInfoModel>(infomodel.ToString());
                    System.Web.HttpContext.Current.Cache.Insert(state, baseinfo.openid, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
                    //客服消息提示扫码成功
                    return(FastResponse("扫码授权成功"));
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "codelogin");
            }

            return(FastResponse("扫码授权失败"));
        }