コード例 #1
0
        public ActionResult MpCallback(string callbackUrl, string code, string state)
        {
            if (code == null)
            {
                return(Content("验证失败!"));
            }

            if (state != "Azure")
            {
                return(Content("请从合法途径进入!"));
            }

            OAuthUserInfo userInfo = null;
            string        openId   = null;

            try
            {
                userInfo = _oAuthService.GetOAuthResult(SiteConfig.AppId, SiteConfig.AppSecret, code);

                openId = userInfo.openid;
            }
            catch (Exception ex)
            {
                LogUtility.OAuthLogger.InfoFormat("公众号OAuth异常,code:{0},原因:{1}", code, ex.Message);

                return(RenderError("公众号OAuth授权异常,原因{0}".With(ex.Message)));
            }

            //处理Account
            var accountService = ObjectFactory.GetInstance <IAccountService>();
            var account        =
                accountService.GetObject(z => z.WeixinOpenId == openId);

            if (account == null)
            {
                int shopId = 0;

                int.TryParse(HttpContext.Request.QueryString["shopId"], out shopId);

                try
                {
                    account = accountService.CreateAccountByUserInfo(userInfo, shopId);
                }
                catch (Exception ex)
                {
                    return(RenderError(ex.Message));
                }
            }
            else if (userInfo != null && account.NickName.IsNullOrEmpty() && account.PicUrl.IsNullOrEmpty())
            {
                accountService.UpdateAccountByUserInfo(userInfo, account);
            }

            Session["OpenId"] = userInfo.openid;
            //记录登录信息
            account.LastLoginTime = account.ThisLoginTime;
            account.LastLoginIP   = account.ThisLoginIP;
            account.ThisLoginTime = DateTime.Now;
            account.ThisLoginIP   = Request.UserHostName;
            accountService.SaveObject(account); //保存Account信息,同时会清除FullAccount信息,顺便保证“强制退出”等参数失效。

            return(Redirect(callbackUrl));
        }