Inheritance: Senparc.Weixin.Entities.WxJsonResult
        public static async Task<bool> SaveOAuthUserTokenAsync(OAuthAccessTokenResult result)
        {
            double now = CommonHelper.GetUnixTimeNow();

            UserInfoRedis u = new UserInfoRedis();
            u.Openid = result.openid;
            u.Unionid = result.unionid;
            u.AccessToken = result.access_token;
            u.ExpireIn = (now + result.expires_in).ToString();
            u.RefreshToken = result.refresh_token;
            return await RedisManager.SaveObjectAsync(u);
        }
Beispiel #2
0
        /// <summary>
        /// OAuthScope.snsapi_userinfo方式回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="returnUrl">用户最初尝试进入的页面</param>
        /// <returns></returns>
        public ActionResult UserInfoCallback(string code, string state, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            if (state != HttpContext.Session.GetString("State"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下,
                //建议用完之后就清空,将其一次性使用
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return(Content("验证失败!请从正规途径进入!"));
            }

            OAuthAccessTokenResult result = null;

            //通过,用code换取access_token
            try
            {
                result = OAuthApi.GetAccessToken(appId, appSecret, code);
            }
            catch (Exception ex)
            {
                return(Content(ex.Message));
            }
            if (result.errcode != ReturnCode.请求成功)
            {
                return(Content("错误:" + result.errmsg));
            }
            //下面2个数据也可以自己封装成一个类,储存在数据库中(建议结合缓存)
            //如果可以确保安全,可以将access_token存入用户的cookie中,每一个人的access_token是不一样的
            HttpContext.Session.SetString("OAuthAccessTokenStartTime", SystemTime.Now.ToString());
            HttpContext.Session.SetString("OAuthAccessToken", result.ToJson());

            //因为第一步选择的是OAuthScope.snsapi_userinfo,这里可以进一步获取用户详细信息
            try
            {
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return(Redirect(returnUrl));
                }

                OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
                return(View(userInfo));
            }
            catch (ErrorJsonResultException ex)
            {
                return(Content(ex.Message));
            }
        }