コード例 #1
0
        /// <summary>
        /// 【异步方法】刷新AuthorizerToken
        /// </summary>
        /// <param name="componentAccessToken"></param>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public static async Task <RefreshAuthorizerTokenResult> RefreshAuthorizerTokenAsync(string componentAccessToken, string componentAppId, string authorizerAppid,
                                                                                            string refreshToken)
        {
            var refreshResult = await ComponentApi.ApiAuthorizerTokenAsync(componentAccessToken, componentAppId, authorizerAppid,
                                                                           refreshToken).ConfigureAwait(false);

            //更新到存储
            ComponentContainer.AuthorizerTokenRefreshedFunc(componentAppId, authorizerAppid, refreshResult);
            return(refreshResult);
        }
コード例 #2
0
        /// <summary>
        /// 刷新AuthorizerToken
        /// </summary>
        /// <param name="componentAccessToken"></param>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public static RefreshAuthorizerTokenResult RefreshAuthorizerToken(string componentAccessToken, string componentAppId, string authorizerAppid,
                                                                          string refreshToken)
        {
            var refreshResult = ComponentApi.ApiAuthorizerToken(componentAccessToken, componentAppId, authorizerAppid,
                                                                refreshToken);

            //更新到存储
            ComponentContainer.AuthorizerTokenRefreshedFunc(componentAppId, authorizerAppid, refreshResult);
            return(refreshResult);
        }
コード例 #3
0
        /// <summary>
        /// 发起授权页的体验URL
        /// </summary>
        /// <returns></returns>
        public ActionResult OAuth()
        {
            //获取预授权码
            var preAuthCode = ComponentContainer.TryGetPreAuthCode(component_AppId, component_Secret, true);

            var callbackUrl = "http://sdk.weixin.senparc.com/OpenOAuth/OpenOAuthCallback";//成功回调地址
            var url         = ComponentApi.GetComponentLoginPageUrl(component_AppId, preAuthCode, callbackUrl);

            return(Redirect(url));
        }
コード例 #4
0
        public override string OnComponentVerifyTicketRequest(RequestMessageComponentVerifyTicket requestMessage)
        {
            ComponentTokenService cts = new ComponentTokenService();
            var componentToken        = cts.GetToken();

            componentToken.ComponentVerifyTicketCreateOn = DateTime.Now;
            componentToken.ComponentVerifyTicket         = requestMessage.ComponentVerifyTicket;
            cts.SaveVerifyToken(componentToken);


            var expiredTime =
                componentToken.ComponentAccessTokenCreateOn.AddSeconds(componentToken.ComponentAccessTokenExpiresIn);

            if (ExpiresIn(expiredTime, 1200))
            { //Refresh the token before 1200 seconds when it expired
                try
                {
                    var updatedToken = ComponentApi.GetComponentAccessToken(ConfigurationManager.AppSettings["AppId"],
                                                                            ConfigurationManager.AppSettings["AppSecret"],
                                                                            componentToken.ComponentVerifyTicket);
                    componentToken.ComponentAccessTokenCreateOn  = DateTime.Now;
                    componentToken.ComponentAccessTokenExpiresIn = updatedToken.expires_in;
                    componentToken.ComponentAccessToken          = updatedToken.component_access_token;
                    cts.SaveAccessToken(componentToken);
                    Log("update access token to " + JsonConvert.SerializeObject(componentToken));
                }
                catch (Exception e)
                {
                    Log(e.ToString(), true);
                }
            }

            expiredTime = componentToken.PreAuthCodeCreateOn.AddSeconds(componentToken.PreAuthCodeExpiresIn);
            if (ExpiresIn(expiredTime, 1200))
            {
                try
                {
                    var updatedCode = ComponentApi.GetPreAuthCode(ConfigurationManager.AppSettings["AppId"],
                                                                  componentToken.ComponentAccessToken);
                    componentToken.PreAuthCodeExpiresIn = updatedCode.expires_in;
                    componentToken.PreAuthCode          = updatedCode.pre_auth_code;
                    componentToken.PreAuthCodeCreateOn  = DateTime.Now;
                    cts.SavePreAuthCode(componentToken);
                    Log("update preauth to " + JsonConvert.SerializeObject(componentToken));
                }
                catch (Exception e2)
                {
                    Log(e2.ToString(), true);
                }
            }



            return(base.OnComponentVerifyTicketRequest(requestMessage));
        }
コード例 #5
0
        public StatusIoClient(StatusIoConfiguration configuration)
        {
            Configuration = configuration;
            network       = new StatusIoNetwork(configuration);

            components  = new ComponentApi(this);
            incidents   = new IncidentApi(this);
            maintenance = new MaintenanceApi(this);
            metrics     = new MetricApi(this);
            status      = new StatusApi(this);
            subscribers = new SubscriberApi(this);
        }
コード例 #6
0
        public void UpdateAccessData()
        {
            var ad    = ComponentKeys.GetInstance().AccessData;
            var atRlt = ComponentApi.GetComponentAccessToken(_wxConfig.AppId, _wxConfig.AppSecret,
                                                             ComponentKeys.GetInstance().VerifyData.Ticket);

            ad.AccessCode = atRlt.component_access_token;
            ad.ExpiresIn  = atRlt.expires_in;
            ad.RefreshOn  = DateTime.Now;

            //store to db
            basicToken.AccessToken          = ad.AccessCode;
            basicToken.AccessTokenRefreshOn = ad.RefreshOn;
            basicToken.AccessTokenExpiresIn = ad.ExpiresIn;
        }
コード例 #7
0
        public void UpdatePreAuthCode()
        {
            var pac    = ComponentKeys.GetInstance().PreAuthData;
            var pacRlt =
                ComponentApi.GetPreAuthCode(_wxConfig.AppId, ComponentKeys.GetInstance().AccessData.AccessCode);

            pac.PreAuthCode = pacRlt.pre_auth_code;
            pac.ExpiresIn   = pacRlt.expires_in;
            pac.RefreshOn   = DateTime.Now;

            //store to db
            basicToken.PreAuthCode          = pac.PreAuthCode;
            basicToken.PreAuthCodeRefreshOn = pac.RefreshOn;
            basicToken.PreAuthCodeExpiresIn = pac.ExpiresIn;
        }
コード例 #8
0
ファイル: Job.cs プロジェクト: simcu/wechat-gateway
        public void Run(string appId, PerformContext context = null)
        {
            context.WriteLine("开始刷新AccessToken【{0}】...", appId);
            var resp = ComponentApi.RefreshAccessToken(_componentAccessToken, _componentAppId, appId, _redis.StringGet(CacheKey.UserRefreshTokenPrefix + appId));

            if (resp.ErrCode == 0)
            {
                _redis.StringSet(CacheKey.UserAccessTokenPrefix + appId, resp.AuthorizerAccessToken, new TimeSpan(0, 0, resp.ExpiresIn));
                _redis.StringSet(CacheKey.UserRefreshTokenPrefix + appId, resp.AuthorizerRefreshToken);
                context.WriteLine("刷新AccessToken【{0}】成功...", appId);
            }
            else
            {
                context.WriteLine("刷新AccessToken【{0}】失败:{1}...", appId, resp.ErrMsg);
                throw new ServiceException(resp.ErrCode, resp.ErrMsg);
            }
        }
コード例 #9
0
        public override Task <GetAppIdResponse> GetAppId(GetAppIdRequest request, ServerCallContext context)
        {
            var resp = new GetAppIdResponse();
            var data = ComponentApi.GetAuthInfo(_componentAccessToken, _componentAppId, request.Code);

            if (data.ErrCode == 0)
            {
                resp.AppId = data.AuthorizationInfo.AuthorizerAppId;
            }
            else
            {
                resp.Error = new Error
                {
                    ErrCode = data.ErrCode,
                    ErrMsg  = data.ErrMsg
                };
            }
            return(Task.FromResult(resp));
        }
コード例 #10
0
        public override Task <GetInfoResponse> GetInfo(GetInfoRequest request, ServerCallContext context)
        {
            var resp = new GetInfoResponse();

            var data = ComponentApi.GetAuthorizerInfo(_componentAccessToken, _componentAppId, request.AppId);

            if (data.ErrCode == 0)
            {
                _redis.StringSet(CacheKey.UserRefreshTokenPrefix + data.AuthorizationInfo.AuthorizerAppId, data.AuthorizationInfo.AuthorizerRefreshToken);
                if (data.AuthorizerInfo.MiniProgramInfo != null)
                {
                    _redis.StringSet(CacheKey.UserIsWxAppPrefix + data.AuthorizationInfo.AuthorizerAppId, 1);
                    resp.Type = "WxApp";
                }
                else
                {
                    _redis.KeyDelete(CacheKey.UserIsWxAppPrefix + data.AuthorizationInfo.AuthorizerAppId);
                    resp.Type = "WxWeb";
                }
                resp.HeadImg         = data.AuthorizerInfo.HeadImg;
                resp.NickName        = data.AuthorizerInfo.NickName;
                resp.PrincipalName   = data.AuthorizerInfo.PrincipalName;
                resp.UserName        = data.AuthorizerInfo.UserName;
                resp.Alias           = data.AuthorizerInfo.Alias;
                resp.AppId           = data.AuthorizationInfo.AuthorizerAppId;
                resp.QrcodeUrl       = data.AuthorizerInfo.QrcodeUrl;
                resp.ServiceTypeInfo = data.AuthorizerInfo.ServiceTypeInfo.Id;
                resp.VerifyTypeInfo  = data.AuthorizerInfo.VerifyTypeInfo.Id;
                foreach (var item in data.AuthorizationInfo.FuncInfos)
                {
                    resp.Permissions.Add(item.Category.Id);
                }
            }
            else
            {
                resp.Error = new Error
                {
                    ErrMsg  = data.ErrMsg,
                    ErrCode = data.ErrCode
                };
            }
            return(Task.FromResult(resp));
        }
コード例 #11
0
        public IActionResult Refresh()
        {
            int timeSpanToUpdate = 300; //提前5分钟进行update
            var almostExpireList = db.AuthorizerTokens.Where(c => c.RefreshOn.AddSeconds(c.ExpiredIn - timeSpanToUpdate) > DateTime.Now);

            foreach (var token in almostExpireList)
            {
                var refreshToken = ComponentApi.ApiAuthorizerToken(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId,
                                                                   token.AuthorizerAppId, token.AuthorizerRefreshToken);
                token.RefreshOn              = DateTime.Now;
                token.AuthorizerAccessToken  = refreshToken.authorizer_access_token;
                token.AuthorizerRefreshToken = refreshToken.authorizer_refresh_token;
                token.ExpiredIn              = refreshToken.expires_in;
            }

            db.SaveChanges();

            return(Content("Refresh Success"));
        }
コード例 #12
0
        /// <summary>
        /// 【异步方法】获取可用Ticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static async Task <JsApiTicketResult> GetJsApiTicketResultAsync(string componentAppId, string authorizerAppid, bool getNewTicket = false)
        {
            TryRegister(componentAppId, authorizerAppid);

            var accessTicketBag = TryGetItem(authorizerAppid);

            using (Cache.BeginCacheLock(LockResourceName + ".GetJsApiTicketResult", authorizerAppid))//同步锁
            {
                if (getNewTicket || accessTicketBag.JsApiTicketExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    var authorizerAccessToken = await TryGetAuthorizerAccessTokenAsync(componentAppId, authorizerAppid);

                    accessTicketBag.JsApiTicketResult = await ComponentApi.GetJsApiTicketAsync(authorizerAccessToken);

                    accessTicketBag.JsApiTicketExpireTime = ApiUtility.GetExpireTime(accessTicketBag.JsApiTicketResult.expires_in);
                }
            }
            return(accessTicketBag.JsApiTicketResult);
        }
コード例 #13
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static JsApiTicketResult GetJsApiTicketResult(string componentAppId, string authorizerAppid, bool getNewTicket = false)
        {
            TryRegister(componentAppId, authorizerAppid);

            var accessTicketBag = ItemCollection[authorizerAppid];

            lock (accessTicketBag.Lock)
            {
                if (getNewTicket || accessTicketBag.JsApiTicketExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    var authorizerAccessToken = TryGetAuthorizerAccessToken(componentAppId, authorizerAppid);

                    accessTicketBag.JsApiTicketResult = ComponentApi.GetJsApiTicket(authorizerAccessToken);

                    accessTicketBag.JsApiTicketExpireTime = DateTime.Now.AddSeconds(accessTicketBag.JsApiTicketResult.expires_in);
                }
            }
            return(accessTicketBag.JsApiTicketResult);
        }
コード例 #14
0
ファイル: TokenController.cs プロジェクト: kevinleptin/Libra
        private void RefreshMpAccessCode()
        {
            var    cts            = new ComponentTokenService();
            var    componentToken = cts.GetToken();
            string componentAppId = ConfigurationManager.AppSettings["AppId"];
            var    mpTokenList    = _context.MpTokens.ToList();

            foreach (var mpToken in mpTokenList)
            {
                if (DateTime.Now.AddSeconds(600) >= mpToken.RefreshOn.AddSeconds(mpToken.ExpiredIn))
                {
                    var refreshRlt = ComponentApi.ApiAuthorizerToken(componentToken.ComponentAccessToken, componentAppId,
                                                                     mpToken.MpAppId, mpToken.MpRefreshToken);
                    mpToken.ExpiredIn      = refreshRlt.expires_in;
                    mpToken.MpAccessToken  = refreshRlt.authorizer_access_token;
                    mpToken.MpRefreshToken = refreshRlt.authorizer_refresh_token;
                    mpToken.RefreshOn      = DateTime.Now;
                    _context.SaveChanges();
                }
            }
        }
コード例 #15
0
 public ComponentToken ForceRefresh()
 {
     using (ApplicationDbContext _context = new ApplicationDbContext())
     {
         var componentToken = _context.ComponentTokens.OrderByDescending(c => c.Id).First();
         try
         {
             var updatedToken = ComponentApi.GetComponentAccessToken(ConfigurationManager.AppSettings["AppId"],
                                                                     ConfigurationManager.AppSettings["AppSecret"],
                                                                     componentToken.ComponentVerifyTicket);
             componentToken.ComponentAccessTokenCreateOn  = DateTime.Now;
             componentToken.ComponentAccessTokenExpiresIn = updatedToken.expires_in;
             componentToken.ComponentAccessToken          = updatedToken.component_access_token;
             _context.SaveChanges();
         }
         catch (Exception e)
         {
             Log(e.ToString());
         }
         return(componentToken);
     }
 }
コード例 #16
0
        /// <summary>
        /// 【异步方法】获取QueryAuthResult(此方法每次都会发出请求,不缓存)
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizationCode"></param>
        /// <param name="updateToAuthorizerContanier">是否将Authorization更新到AuthorizerContanier</param>
        /// <param name="getNewToken"></param>
        /// <returns></returns>
        /// <exception cref="WeixinOpenException"></exception>
        public static async Task<QueryAuthResult> GetQueryAuthResultAsync(string componentAppId, string authorizationCode, bool updateToAuthorizerContanier = true, bool getNewToken = false)
        {
            if (!CheckRegistered(componentAppId))
            {
                throw new WeixinOpenException(UN_REGISTER_ALERT);
            }

            var componentBag = TryGetItem(componentAppId);
            using (Cache.BeginCacheLock(LockResourceName + ".GetQueryAuthResult", componentAppId))//同步锁
            {
                var accessToken = TryGetComponentAccessToken(componentAppId, componentBag.ComponentAppSecret, null, getNewToken);
                var queryAuthResult = await ComponentApi.QueryAuthAsync(accessToken, componentAppId, authorizationCode);

                if (updateToAuthorizerContanier)
                {
                    //更新到AuthorizerContainer
                    AuthorizerContainer.TryUpdateAuthorizationInfo(componentAppId, queryAuthResult.authorization_info.authorizer_appid, queryAuthResult.authorization_info);
                }

                return queryAuthResult;
            }
        }
コード例 #17
0
ファイル: InsideMsgHandler.cs プロジェクト: kevinleptin/Libra
        public override string OnAuthorizedRequest(RequestMessageAuthorized requestMessage)
        {
            // create new entity
            AppAuthInfo appInfo = new AppAuthInfo();

            appInfo.AuthorizerAppId = requestMessage.AuthorizerAppid; // db table key
            appInfo.AppId           = requestMessage.AppId;           // 第三方平台的 appid
            appInfo.Authorized      = true;
            appInfo.Code            = requestMessage.AuthorizationCode;
            appInfo.ExpiredTime     = requestMessage.AuthorizationCodeExpiredTime;
            appInfo.CreateOn        = DateTime.Now;
            appInfo.LastUpdateOn    = DateTime.Now;

            //,
            var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, requestMessage.AuthorizerAppid);
            var authorizerInfo       = authorizerInfoResult.authorizer_info;
            var authorizerInfoEntity = new JinZhou.Models.DbEntities.AuthorizerInfo()
            {
                UserName      = authorizerInfo.user_name,
                NickName      = authorizerInfo.nick_name,
                HeadImg       = authorizerInfo.head_img,
                ServiceType   = (int)authorizerInfo.service_type_info.id,
                VerifyType    = (int)authorizerInfo.verify_type_info.id,
                PrincipalName = authorizerInfo.principal_name,
                BizStore      = authorizerInfo.business_info.open_store,
                BizPay        = authorizerInfo.business_info.open_pay,
                BizCard       = authorizerInfo.business_info.open_card,
                BizScan       = authorizerInfo.business_info.open_scan,
                BizShake      = authorizerInfo.business_info.open_shake,
                Alias         = authorizerInfo.alias,
                QrcodeUrl     = authorizerInfo.qrcode_url
            };

            appInfo.Authorizer = authorizerInfoEntity;

            db.AppAuths.Add(appInfo);
            db.SaveChanges();
            return(base.OnAuthorizedRequest(requestMessage));
        }
コード例 #18
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static JsApiTicketResult GetJsApiTicketResult(string componentAppId, string authorizerAppid, bool getNewTicket = false)
        {
            TryRegister(componentAppId, authorizerAppid);

            var accessTicketBag = TryGetItem(authorizerAppid);

            using (Cache.BeginCacheLock(LockResourceName + ".GetJsApiTicketResult", authorizerAppid))//同步锁
            {
                if (getNewTicket || accessTicketBag.JsApiTicketExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    var authorizerAccessToken = TryGetAuthorizerAccessToken(componentAppId, authorizerAppid);

                    accessTicketBag.JsApiTicketResult = ComponentApi.GetJsApiTicket(authorizerAccessToken);

                    accessTicketBag.JsApiTicketExpireTime = ApiUtility.GetExpireTime(accessTicketBag.JsApiTicketResult.expires_in);

                    Update(accessTicketBag, null);//更新到缓存
                }
            }
            return(accessTicketBag.JsApiTicketResult);
        }
コード例 #19
0
        /// <summary>
        /// 【异步方法】获取可用Ticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static async Task <JsApiTicketResult> GetJsApiTicketResultAsync(string componentAppId, string authorizerAppid, bool getNewTicket = false)
        {
            await TryRegisterAsync(componentAppId, authorizerAppid).ConfigureAwait(false);

            var accessTicketBag = await TryGetItemAsync(authorizerAppid).ConfigureAwait(false);

            using (await Cache.BeginCacheLockAsync(LockResourceName + ".GetJsApiTicketResult", authorizerAppid).ConfigureAwait(false))//同步锁
            {
                if (getNewTicket || accessTicketBag.JsApiTicketExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    var authorizerAccessToken = await TryGetAuthorizerAccessTokenAsync(componentAppId, authorizerAppid).ConfigureAwait(false);

                    accessTicketBag.JsApiTicketResult = await ComponentApi.GetJsApiTicketAsync(authorizerAccessToken).ConfigureAwait(false);

                    accessTicketBag.JsApiTicketExpireTime = ApiUtility.GetExpireTime(accessTicketBag.JsApiTicketResult.expires_in);

                    await UpdateAsync(accessTicketBag, null).ConfigureAwait(false);//更新到缓存
                }
            }
            return(accessTicketBag.JsApiTicketResult);
        }
コード例 #20
0
        /// <summary>
        /// 【异步方法】获取可用AccessToken
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="componentVerifyTicket">如果为null则自动获取</param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static async Task<ComponentAccessTokenResult> GetComponentAccessTokenResultAsync(string componentAppId, string componentVerifyTicket = null, bool getNewToken = false)
        {
            if (!CheckRegistered(componentAppId))
            {
                throw new WeixinOpenException(UN_REGISTER_ALERT);
            }

            var accessTokenBag = TryGetItem(componentAppId);
            using (Cache.BeginCacheLock(LockResourceName + ".GetComponentAccessTokenResult", componentAppId))//同步锁
            {
                if (getNewToken || accessTokenBag.ComponentAccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    componentVerifyTicket = componentVerifyTicket ?? TryGetComponentVerifyTicket(componentAppId);

                    var componentAccessTokenResult = await ComponentApi.GetComponentAccessTokenAsync(accessTokenBag.ComponentAppId, accessTokenBag.ComponentAppSecret, componentVerifyTicket);

                    accessTokenBag.ComponentAccessTokenResult = componentAccessTokenResult;
                    accessTokenBag.ComponentAccessTokenExpireTime = ApiUtility.GetExpireTime(componentAccessTokenResult.expires_in);
                }
            }
            return accessTokenBag.ComponentAccessTokenResult;
        }
コード例 #21
0
        public static string ReloadToken(Guid CompanyID)
        {
            wx_userweixin wx = wx_userweixinService.instance().SingleByCompanyID(CompanyID);
            //if (wx.AppId == null || wx.AppSecret == null || wx.AppId.Trim().Length <= 0 || wx.AppSecret.Trim().Length <= 0)
            //{
            //    return "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
            //}
            var wx_open = wx_openInfoService.instance().Single(new Guid(System.Configuration.ConfigurationManager.AppSettings["openID"]));
            RefreshAuthorizerTokenResult result = ComponentApi.ApiAuthorizerToken(wx_open.open_access_token, wx_open.open_sAppID, wx.AppId, wx.refresh_token);

            if (result.errcode == Entity.Weixin.ReturnCode.请求成功)
            {
                wx.Access_Token  = result.authorizer_access_token;
                wx.refresh_token = result.authorizer_refresh_token;
                wx.expires_in    = result.expires_in;
                wx.ModifyTime    = DateTime.Now;
                if (wx_userweixinService.instance().Update(wx) == 1)
                {
                    return("ok");
                }
                return("更新数据库出错");
            }
            return(result.errcode.ToString());
        }
コード例 #22
0
        /// <summary>
        ///【异步方法】获取可用Token
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static async Task <PreAuthCodeResult> GetPreAuthCodeResultAsync(string componentAppId, bool getNewToken = false)
        {
            if (!CheckRegistered(componentAppId))
            {
                throw new WeixinOpenException(UN_REGISTER_ALERT);
            }

            var componentBag = TryGetItem(componentAppId);

            using (Cache.BeginCacheLock(LockResourceName + ".GetPreAuthCodeResult", componentAppId))//同步锁
            {
                if (getNewToken || componentBag.PreAuthCodeExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    var componentVerifyTicket = TryGetComponentVerifyTicket(componentAppId);

                    var accessToken = TryGetComponentAccessToken(componentAppId, componentBag.ComponentAppSecret, componentVerifyTicket);

                    var preAuthCodeResult = await ComponentApi.GetPreAuthCodeAsync(componentBag.ComponentAppId, accessToken);

                    componentBag.PreAuthCodeExpireTime = ApiUtility.GetExpireTime(preAuthCodeResult.expires_in);


                    componentBag.PreAuthCodeResult = preAuthCodeResult;

                    Update(componentBag);//更新到缓存

                    ////TODO:这里有出现expires_in=0的情况,导致始终处于过期状态(也可能是因为参数过期等原因没有返回正确的数据,待观察)
                    //var expiresIn = componentBag.PreAuthCodeResult.expires_in > 0
                    //    ? componentBag.PreAuthCodeResult.expires_in
                    //    : 60 * 20;//默认为20分钟
                    //componentBag.PreAuthCodeExpireTime = DateTime.Now.AddSeconds(expiresIn);
                }
            }
            return(componentBag.PreAuthCodeResult);
        }
コード例 #23
0
        public void RefreshAuthorizerTokenTest()
        {
            var componentAccessTokenResult = ComponentContainer.GetComponentAccessTokenResult(base._appId, base._ticket);

            Assert.IsNotNull(componentAccessTokenResult.component_access_token);

            var authorizerId   = "wxd7a61edcdce336b0";
            var authorizerInfo = ComponentApi.GetAuthorizerInfo(componentAccessTokenResult.component_access_token, base._appId, authorizerId);

            var authorizer_access_token  = authorizerInfo.authorization_info.authorizer_access_token;
            var authorizer_refresh_token = authorizerInfo.authorization_info.authorizer_refresh_token;

            Assert.IsNotNull(authorizerInfo.authorization_info.authorizer_access_token);
            Assert.IsNotNull(authorizerInfo.authorization_info.authorizer_refresh_token);

            Console.WriteLine("authorizer_access_token:" + authorizer_access_token);
            Console.WriteLine("authorizer_refresh_token:" + authorizer_refresh_token);

            var result = ComponentApi.ApiAuthorizerToken(componentAccessTokenResult.component_access_token,
                                                         base._appId, authorizerId, authorizerInfo.authorization_info.authorizer_refresh_token);

            Console.WriteLine("authorizer_access_token:" + result.authorizer_access_token);
            Console.WriteLine("authorizer_access_token:" + result.authorizer_refresh_token);
        }
コード例 #24
0
        /// <summary>
        /// 获取可用的GetAuthorizerInfoResult
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizerAppid"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        ///// <exception cref="WeixinOpenException">此公众号没有高级权限</exception>
        public static GetAuthorizerInfoResult GetAuthorizerInfoResult(string componentAppId, string authorizerAppid, bool getNewTicket = false)
        {
            TryRegister(componentAppId, authorizerAppid);

            var authorizerBag = TryGetItem(authorizerAppid);

            using (Cache.BeginCacheLock(LockResourceName + ".GetAuthorizerInfoResult", authorizerAppid))//同步锁
            {
                //更新AuthorizerInfo
                if (getNewTicket || authorizerBag.AuthorizerInfo.user_name == null)
                {
                    var componentVerifyTicket = ComponentContainer.TryGetComponentVerifyTicket(componentAppId);
                    var componentAccessToken  = ComponentContainer.GetComponentAccessToken(componentAppId, componentVerifyTicket);

                    //已过期,重新获取
                    var getAuthorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentAccessToken, componentAppId, authorizerAppid);//TODO:如果是过期,可以通过刷新的方式重新获取

                    //AuthorizerInfo
                    authorizerBag.AuthorizerInfo = getAuthorizerInfoResult.authorizer_info;

                    //AuthorizationInfo
                    var getAuthorizationInfoResult = GetAuthorizationInfo(componentAppId, authorizerAppid, getNewTicket);
                    authorizerBag.AuthorizationInfo = getAuthorizationInfoResult;

                    Update(authorizerBag, null);//更新到缓存

                    //var componentBag = ComponentContainer.TryGetItem(componentAppId);
                    //if (string.IsNullOrEmpty(authorizerBag.AuthorizerInfoResult.authorization_info.authorizer_access_token))
                    //{
                    //    //账号没有此权限
                    //    throw new WeixinOpenException("此公众号没有高级权限", componentBag);
                    //}
                }
            }
            return(authorizerBag.FullAuthorizerInfoResult);
        }
コード例 #25
0
        /// <summary>
        /// 授权页回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult OpenOAuthCallback(string id)
        {
            var    reurl      = "http://openapp.vzan.com/test/index";
            var    appid      = "wx9a6ab00a752e10e8";
            string auth_code  = Request["auth_code"];
            int    areacode   = int.Parse(Request["AreaCode"]?.ToString());
            int    expires_in = Convert.ToInt32(Request["expires_in"]);

            var    currentmodel = opencomponentconfigBLL.SingleModel.getCurrentModel();
            string token        = currentmodel.component_access_token;

            //使用授权码获取小程序授权信息
            var queryAuthResult = ComponentApi.QueryAuth(token, appid, auth_code);

            try
            {
                var           authorizerInfoResult = ComponentApi.GetAuthorizerInfo(token, appid, queryAuthResult.authorization_info.authorizer_appid);
                StringBuilder str = new StringBuilder();
                foreach (FuncscopeCategoryItem item in queryAuthResult.authorization_info.func_info)
                {
                    str.Append(item.funcscope_category.id.ToString() + ",");
                }
                string func_info = str.ToString();
                if (func_info.Length > 0)
                {
                    func_info = func_info.Substring(0, func_info.Length - 1);
                }

                #region 公众号详细信息
                OpenAuthorizerConfig openconfig = OpenAuthorizerConfigBLL.SingleModel.GetModel("user_name='" + authorizerInfoResult.authorizer_info.user_name + "'");
                if (openconfig == null)
                {
                    openconfig = new OpenAuthorizerConfig();
                }
                openconfig.alias             = authorizerInfoResult.authorizer_info.alias;
                openconfig.appid             = queryAuthResult.authorization_info.authorizer_appid;
                openconfig.func_info         = func_info;
                openconfig.head_img          = authorizerInfoResult.authorizer_info.head_img;
                openconfig.nick_name         = authorizerInfoResult.authorizer_info.nick_name;
                openconfig.qrcode_url        = authorizerInfoResult.authorizer_info.qrcode_url;
                openconfig.service_type_info = (int)authorizerInfoResult.authorizer_info.service_type_info.id;
                openconfig.user_name         = authorizerInfoResult.authorizer_info.user_name;
                openconfig.verify_type_info  = (int)authorizerInfoResult.authorizer_info.verify_type_info.id;
                openconfig.state             = 1;
                //openconfig.minisnsid = areacode;
                if (openconfig.id > 0)
                {
                    OpenAuthorizerConfigBLL.SingleModel.Update(openconfig);
                }
                else
                {
                    OpenAuthorizerConfigBLL.SingleModel.Add(openconfig);
                }

                OpenAuthorizerInfo info = OpenAuthorizerInfoBLL.SingleModel.GetModel(string.Format("user_name='{0}'", authorizerInfoResult.authorizer_info.user_name));

                if (info == null)
                {
                    info = new OpenAuthorizerInfo();
                }
                info.addtime = DateTime.Now;
                info.authorizer_access_token  = queryAuthResult.authorization_info.authorizer_access_token;
                info.authorizer_appid         = authorizerInfoResult.authorization_info.authorizer_appid;
                info.authorizer_refresh_token = queryAuthResult.authorization_info.authorizer_refresh_token;
                info.refreshtime = DateTime.Now;
                info.status      = 1;
                //info.minisnsid = areacode;
                info.user_name = authorizerInfoResult.authorizer_info.user_name;
                if (info.id > 0)
                {
                    OpenAuthorizerInfoBLL.SingleModel.Update(info);
                }
                else
                {
                    OpenAuthorizerInfoBLL.SingleModel.Add(info);
                }

                #endregion
                return(Redirect(reurl));
            }
            catch (ErrorJsonResultException ex)
            {
                log4net.LogHelper.WriteError(this.GetType(), ex);
                return(Content(ex.Message));
            }
        }
コード例 #26
0
        public ActionResult Installed(string auth_code, int expires_in)
        {
            var    cts            = new ComponentTokenService();
            var    componentToken = cts.GetToken();
            string componentAppId = ConfigurationManager.AppSettings["AppId"];

            var queryAuth = Senparc.Weixin.Open.ComponentAPIs.ComponentApi.QueryAuth(
                componentToken.ComponentAccessToken,
                componentAppId, auth_code);

            string authorizerAppid = queryAuth.authorization_info.authorizer_appid;


            var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentToken.ComponentAccessToken,
                                                                      componentAppId, queryAuth.authorization_info.authorizer_appid);
            var authorizerInfo       = authorizerInfoResult.authorizer_info;
            var authorizerInfoEntity = db.MpInfos.FirstOrDefault(c => c.UserName == authorizerInfo.user_name);

            if (authorizerInfoEntity == null)
            {
                authorizerInfoEntity = new MpInfo()
                {
                    UserName      = authorizerInfo.user_name,
                    NickName      = authorizerInfo.nick_name,
                    HeadImg       = authorizerInfo.head_img,
                    ServiceType   = (int)authorizerInfo.service_type_info.id,
                    VerifyType    = (int)authorizerInfo.verify_type_info.id,
                    PrincipalName = authorizerInfo.principal_name,
                    BizStore      = authorizerInfo.business_info.open_store,
                    BizPay        = authorizerInfo.business_info.open_pay,
                    BizCard       = authorizerInfo.business_info.open_card,
                    BizScan       = authorizerInfo.business_info.open_scan,
                    BizShake      = authorizerInfo.business_info.open_shake,
                    Alias         = authorizerInfo.alias,
                    QrcodeUrl     = authorizerInfo.qrcode_url
                };
                db.MpInfos.Add(authorizerInfoEntity);
            }

            MpToken token =
                db.MpTokens.FirstOrDefault(c => c.MpAppId == authorizerAppid);

            if (token == null)
            {
                token         = new MpToken();
                token.MpAppId = authorizerAppid;
                db.MpTokens.Add(token);
            }

            token.RefreshOn      = DateTime.Now;
            token.MpAccessToken  = queryAuth.authorization_info.authorizer_access_token;
            token.MpRefreshToken = queryAuth.authorization_info.authorizer_refresh_token;
            token.ExpiredIn      = queryAuth.authorization_info.expires_in;
            token.BelongToMp     = authorizerInfoEntity;

            db.SaveChanges();

            //update preauthcode
            var updatedCode = ComponentApi.GetPreAuthCode(ConfigurationManager.AppSettings["AppId"],
                                                          componentToken.ComponentAccessToken);

            componentToken.PreAuthCodeExpiresIn = updatedCode.expires_in;
            componentToken.PreAuthCode          = updatedCode.pre_auth_code;
            componentToken.PreAuthCodeCreateOn  = DateTime.Now;
            cts.SavePreAuthCode(componentToken);


            //HomeInstalledViewModel vm = new HomeInstalledViewModel();
            //vm.AuthorizerAppId = authorizerAppid;
            //vm.AuthUrl = string.Format(ConfigurationManager.AppSettings["UserAuthEntryPointUriFmt"], authorizerAppid);
            string redirectUrl = string.Format(ConfigurationManager.AppSettings["InstallSuccessUrl"], authorizerAppid);

            return(Redirect(redirectUrl));
        }
コード例 #27
0
 private static async Task Test(ComponentApi components)
 {
     var listComponents = await components.GetListAsync();
 }
コード例 #28
0
        public ActionResult OAuthCallback(string auth_code, int expires_in, int shopId)
        {
            logger.LogInformation($"================================调试开始====================================");
            try
            {
                #region 查询授权信息
                var componentAppId    = wechatOpenOptions.AppId;
                var authorizationCode = auth_code;
                var accessToken       = ZRui.Web.BLL.AuthorizerHelper.GetComponentAccessToken();
                var queryAuthResult   = ComponentApi.QueryAuth(accessToken, componentAppId, authorizationCode);
                logger.LogInformation($"授权返回信息queryAuthResult:{queryAuthResult}");
                var authorizerAppid   = queryAuthResult.authorization_info.authorizer_appid;
                var authorizationInfo = queryAuthResult.authorization_info;
                #endregion

                WechatOpenAuthorizer authorizer = null;
                var authorizers = db.Query <WechatOpenAuthorizer>().
                                  Where(p => p.AuthorizerAppId == authorizationInfo.authorizer_appid);
                if (authorizers.Count() > 0)
                {
                    authorizer = authorizers.FirstOrDefault(p => !p.IsDel);
                    if (authorizer != null)
                    {
                        return(Content("当前店铺绑定的小程序已经存在"));
                    }
                    else
                    {
                        authorizer       = authorizers.OrderByDescending(p => p.Id).FirstOrDefault();
                        authorizer.IsDel = false;
                    }
                }
                else
                {
                    authorizer = new WechatOpenAuthorizer();
                    db.Add(authorizer);
                }


                authorizer.AddIp                  = GetIp();
                authorizer.AddTime                = DateTime.Now;
                authorizer.AddUser                = GetUsername();
                authorizer.AuthorizerAppId        = queryAuthResult.authorization_info.authorizer_appid;
                authorizer.AuthorizerAccessToken  = queryAuthResult.authorization_info.authorizer_access_token;
                authorizer.AuthorizerRefreshToken = queryAuthResult.authorization_info.authorizer_refresh_token;
                authorizer.ExpiresIn              = queryAuthResult.authorization_info.expires_in;
                authorizer.ExpiresTime            = DateTime.Now.AddSeconds(queryAuthResult.authorization_info.expires_in);


                GetAuthorizerInfoResult authorizerInfoResult = ComponentApi.GetAuthorizerInfo(accessToken, componentAppId, authorizerAppid, 0x2710);

                authorizer.AuthorizerNickname = authorizerInfoResult.authorizer_info.nick_name;
                //这里的Username是原始Id
                authorizer.AuthorizerUsername = authorizerInfoResult.authorizer_info.user_name;


                db.SaveChanges();



                ShopWechatOpenAuthorizer shopAuth = null;
                var shopAuths = db.Query <ShopWechatOpenAuthorizer>()
                                .Where(m => m.ShopId == shopId);
                if (shopAuths.Count() > 0)
                {
                    shopAuth = shopAuths.FirstOrDefault(p => !p.IsDel);
                    if (shopAuth == null)
                    {
                        shopAuth = shopAuths.OrderByDescending(p => p.Id).FirstOrDefault();
                    }
                    shopAuth.IsDel = false;
                }
                else
                {
                    shopAuth = new ShopWechatOpenAuthorizer()
                    {
                        ShopId = shopId,
                    };
                    db.Add(shopAuth);
                }
                shopAuth.WechatOpenAuthorizerId = authorizer.Id;
                db.SaveChanges();


                ///初始化
                //复制一份授权信息到auth数据库
                ZRui.Web.BLL.AuthorizerHelper.InsertOrUpdateAuthorizer(authorizer);
                //设置请求域以及添加跳转二维码
                var initShop = CodeApiExt.QRCodeJumpAddPublish(shopId, authorizer.AuthorizerAccessToken, hostingEnvironment);
                //创建开放平台--为了获取授权信息时含有unionid
                AuthorizerHelper.CreateAndBindOpen(authorizer.AuthorizerAppId);


                ViewData["QueryAuthorizationInfo"]  = queryAuthResult.authorization_info;
                ViewData["GetAuthorizerInfoResult"] = authorizerInfoResult.authorizer_info;
                return(View());
            }
            catch (ErrorJsonResultException ex)
            {
                return(Content(ex.Message));
            }
        }
コード例 #29
0
        public IActionResult Installed(string auth_code, int expires_in)
        {
            LogService.GetInstance().AddLog("Home:Installed", null, "Auth succeed", "", "Info");

            var queryAuth = Senparc.Weixin.Open.ComponentAPIs.ComponentApi.QueryAuth(ComponentKeys.GetInstance().AccessData.AccessCode,
                                                                                     _wxConfig.AppId, auth_code);

            string authorizerAppid = queryAuth.authorization_info.authorizer_appid;
            var    authorizer      = db.AppAuths.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid);

            if (authorizer == null || authorizer.Code != auth_code)
            {
                if (authorizer == null)
                {
                    authorizer                 = new AppAuthInfo();
                    authorizer.AppId           = _wxConfig.AppId;
                    authorizer.AuthorizerAppId = queryAuth.authorization_info.authorizer_appid;
                    authorizer.Authorized      = true;
                    authorizer.CreateOn        = DateTime.Now;

                    var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, queryAuth.authorization_info.authorizer_appid);
                    var authorizerInfo       = authorizerInfoResult.authorizer_info;
                    var authorizerInfoEntity =
                        db.AuthorizerInfos.FirstOrDefault(c => c.UserName == authorizerInfo.user_name);
                    if (authorizerInfoEntity == null)
                    {
                        authorizerInfoEntity = new JinZhou.Models.DbEntities.AuthorizerInfo()
                        {
                            UserName      = authorizerInfo.user_name,
                            NickName      = authorizerInfo.nick_name,
                            HeadImg       = authorizerInfo.head_img,
                            ServiceType   = (int)authorizerInfo.service_type_info.id,
                            VerifyType    = (int)authorizerInfo.verify_type_info.id,
                            PrincipalName = authorizerInfo.principal_name,
                            BizStore      = authorizerInfo.business_info.open_store,
                            BizPay        = authorizerInfo.business_info.open_pay,
                            BizCard       = authorizerInfo.business_info.open_card,
                            BizScan       = authorizerInfo.business_info.open_scan,
                            BizShake      = authorizerInfo.business_info.open_shake,
                            Alias         = authorizerInfo.alias,
                            QrcodeUrl     = authorizerInfo.qrcode_url
                        };
                    }

                    authorizer.Authorizer = authorizerInfoEntity;
                    //TODO: 这里应该存储以下信息,并自动刷新
                    //todo: queryAuth.authorization_info.authorizer_access_token
                    //TODO: queryAuth.authorization_info.authorizer_refresh_token
                    AuthorizerToken token =
                        db.AuthorizerTokens.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid);
                    if (token == null)
                    {
                        token = new AuthorizerToken();
                        db.AuthorizerTokens.Add(token);
                    }

                    token.RefreshOn              = DateTime.Now;
                    token.AuthorizerAccessToken  = queryAuth.authorization_info.authorizer_access_token;
                    token.AuthorizerRefreshToken = queryAuth.authorization_info.authorizer_refresh_token;
                    token.ExpiredIn              = queryAuth.authorization_info.expires_in;
                    db.SaveChanges();

                    //todo: 网站加入性能监控的组件,方便了解网站的运行状态

                    db.AppAuths.Add(authorizer);
                }
                //need update
                authorizer.Code         = auth_code;
                authorizer.ExpiredTime  = DateTime.Now.AddSeconds(queryAuth.authorization_info.expires_in);
                authorizer.LastUpdateOn = DateTime.Now;
                db.SaveChanges();
            }

            HomeInstalledViewModels vm = new HomeInstalledViewModels();

            vm.AuthorizerAppId = authorizerAppid;
            vm.AuthUrl         = string.Format(_wxConfig.UserAuthEntryPointUriFmt, authorizerAppid);
            return(View(vm));
        }