コード例 #1
0
ファイル: BaseApi.cs プロジェクト: Vivantio/apisamples
 protected BaseApi()
 {
     var url = ConfigurationManager.AppSettings["Vivantio.ApiUrl"];
     var user = ConfigurationManager.AppSettings["Vivantio.ApiUser"];
     var password = ConfigurationManager.AppSettings["Vivantio.ApiPassword"];
     _utility = new ApiUtility(url, user, password);
 }
コード例 #2
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static JsApiTicketResult GetTicketResult(string appId, string appSecret, bool getNewTicket = false)
        {
            if (!CheckRegistered(BuildingKey(appId, appSecret)))
            {
                throw new WeixinQyException(UN_REGISTER_ALERT);
            }

            var jsApiTicketBag = TryGetItem(BuildingKey(appId, appSecret));

            lock (jsApiTicketBag.Lock)
            {
                if (getNewTicket || jsApiTicketBag.ExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);
                    jsApiTicketBag.ExpireTime        = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
                }
            }
            return(jsApiTicketBag.JsApiTicketResult);
        }
コード例 #3
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static AccessTokenResult GetAccessTokenResult(string appId, bool getNewToken = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(appId, string.Format("此appId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", appId));
            }

            var accessTokenBag = (AccessTokenBag)ItemCollection[appId];

            lock (accessTokenBag.Lock)
            {
                if (getNewToken || accessTokenBag.AccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    accessTokenBag.AccessTokenResult     = CommonApi.GetToken(accessTokenBag.AppId, accessTokenBag.AppSecret);
                    accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);
                }
            }
            return(accessTokenBag.AccessTokenResult);
        }
コード例 #4
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static AccessTokenResult GetAccessTokenResult(string appId, bool getNewToken = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(appId, string.Format("此appId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", appId));
            }

            var accessTokenBag = TryGetItem(appId);

            using (Cache.BeginCacheLock(LockResourceName, appId))//同步锁
            {
                if (getNewToken || accessTokenBag.AccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    accessTokenBag.AccessTokenResult     = CommonApi.GetToken(accessTokenBag.AppId, accessTokenBag.AppSecret);
                    accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);
                }
            }
            return(accessTokenBag.AccessTokenResult);
        }
コード例 #5
0
        public async Task <ActionResult> AddEdit(RangeModel model)
        {
            bool response = false;

            if (model.IsNew)
            {
                response = await ApiUtility.PostAsync <RangeModel>(Services.Ranges, model);
            }
            else
            {
                response = await ApiUtility.PutAsync <RangeModel>(Services.Ranges, model);
            }

            if (response)
            {
                return(RedirectToAction("List"));
            }

            return(View());
        }
コード例 #6
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static JsApiTicketResult GetJsApiTicketResult(string appId, bool getNewTicket = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(null, "此appId尚未注册,请先使用JsApiTicketContainer.Register完成注册(全局执行一次即可)!");
            }

            var jsApiTicketBag = TryGetItem(appId);

            using (Cache.BeginCacheLock(LockResourceName, appId))//同步锁
            {
                if (getNewTicket || jsApiTicketBag.JsApiTicketExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    jsApiTicketBag.JsApiTicketResult     = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);
                    jsApiTicketBag.JsApiTicketExpireTime = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
                }
            }
            return(jsApiTicketBag.JsApiTicketResult);
        }
コード例 #7
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);
        }
コード例 #8
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="code">code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。</param>
        /// <param name="getNewToken">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static OAuthAccessTokenResult GetOAuthAccessTokenResult(string appId, string code, bool getNewToken = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(null, "此appId尚未注册,请先使用OAuthAccessTokenContainer.Register完成注册(全局执行一次即可)!");
            }

            var oAuthAccessTokenBag = (OAuthAccessTokenBag)ItemCollection[appId];

            lock (oAuthAccessTokenBag.Lock)
            {
                if (getNewToken || oAuthAccessTokenBag.OAuthAccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    oAuthAccessTokenBag.OAuthAccessTokenResult     = OAuthApi.GetAccessToken(oAuthAccessTokenBag.AppId, oAuthAccessTokenBag.AppSecret, code);
                    oAuthAccessTokenBag.OAuthAccessTokenExpireTime =
                        ApiUtility.GetExpireTime(oAuthAccessTokenBag.OAuthAccessTokenResult.expires_in);
                }
            }
            return(oAuthAccessTokenBag.OAuthAccessTokenResult);
        }
コード例 #9
0
        /// <summary>
        /// 获取可用Token
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static ProviderTokenResult GetTokenResult(string corpId, string corpSecret, bool getNewToken = false)
        {
            if (!CheckRegistered(BuildingKey(corpId, corpSecret)))
            {
                throw new WeixinQyException(UN_REGISTER_ALERT);
            }

            var providerTokenBag = TryGetItem(BuildingKey(corpId, corpSecret));

            lock (providerTokenBag.Lock)
            {
                if (getNewToken || providerTokenBag.ExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    providerTokenBag.ProviderTokenResult = SsoApi.GetProviderToken(providerTokenBag.CorpId,
                                                                                   providerTokenBag.CorpSecret);
                    providerTokenBag.ExpireTime = ApiUtility.GetExpireTime(providerTokenBag.ProviderTokenResult.expires_in);
                }
            }
            return(providerTokenBag.ProviderTokenResult);
        }
コード例 #10
0
        /// <summary>
        /// 获取ComponentVerifyTicket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="getNewToken"></param>
        /// <returns>如果不存在,则返回null</returns>
        public static string TryGetComponentVerifyTicket(string componentAppId, bool getNewToken = false)
        {
            if (!CheckRegistered(componentAppId))
            {
                throw new WeixinOpenException(UN_REGISTER_ALERT);
            }

            var bag = TryGetItem(componentAppId);
            var componentVerifyTicket = bag.ComponentVerifyTicket;
            if (getNewToken || componentVerifyTicket == default(string) || bag.ComponentVerifyTicketExpireTime < DateTime.Now)
            {
                if (GetComponentVerifyTicketFunc == null)
                {
                    throw new WeixinOpenException("GetComponentVerifyTicketFunc必须在注册时提供!", bag);
                }
                componentVerifyTicket = GetComponentVerifyTicketFunc(componentAppId); //获取最新的componentVerifyTicket
                bag.ComponentVerifyTicket = componentVerifyTicket;
                bag.ComponentVerifyTicketExpireTime = ApiUtility.GetExpireTime(COMPONENT_VERIFY_TICKET_UPDATE_MINUTES * 60);
            }
            return componentVerifyTicket;
        }
コード例 #11
0
        /// <summary>
        /// 获取可用Token
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static AccessTokenResult GetTokenResult(string corpId, string corpSecret, bool getNewToken = false)
        {
            if (!CheckRegistered(BuildingKey(corpId, corpSecret)))
            {
                throw new WeixinQyException(UN_REGISTER_ALERT);
            }

            var accessTokenBag = TryGetItem(BuildingKey(corpId, corpSecret));

            lock (accessTokenBag.Lock)
            {
                if (getNewToken || accessTokenBag.ExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    accessTokenBag.AccessTokenResult = CommonApi.GetToken(accessTokenBag.CorpId,
                                                                          accessTokenBag.CorpSecret);
                    accessTokenBag.ExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);
                }
            }
            return(accessTokenBag.AccessTokenResult);
        }
コード例 #12
0
        /// <summary>
        /// 获取可用Token
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static ProviderTokenResult GetTokenResult(string corpId, bool getNewToken = false)
        {
            if (!CheckRegistered(corpId))
            {
                throw new WeixinQyException(UN_REGISTER_ALERT);
            }

            var providerTokenBag = (ProviderTokenBag)ItemCollection[corpId];

            lock (providerTokenBag.Lock)
            {
                if (getNewToken || providerTokenBag.ExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    providerTokenBag.ProviderTokenResult = CommonApi.GetProviderToken(providerTokenBag.CorpId,
                                                                                      providerTokenBag.CorpSecret);
                    providerTokenBag.ExpireTime = ApiUtility.GetExpireTime(providerTokenBag.ProviderTokenResult.expires_in);
                }
            }
            return(providerTokenBag.ProviderTokenResult);
        }
コード例 #13
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="code">code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。</param>
        /// <param name="getNewToken">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static OAuthAccessTokenResult GetOAuthAccessTokenResult(string appId, string code, bool getNewToken = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(null, "此appId尚未注册,请先使用OAuthAccessTokenContainer.Register完成注册(全局执行一次即可)!");
            }

            var oAuthAccessTokenBag = TryGetItem(appId);

            using (Cache.BeginCacheLock(LockResourceName, appId))//同步锁
            {
                if (getNewToken || oAuthAccessTokenBag.OAuthAccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    oAuthAccessTokenBag.OAuthAccessTokenResult     = OAuthApi.GetAccessToken(oAuthAccessTokenBag.AppId, oAuthAccessTokenBag.AppSecret, code);
                    oAuthAccessTokenBag.OAuthAccessTokenExpireTime =
                        ApiUtility.GetExpireTime(oAuthAccessTokenBag.OAuthAccessTokenResult.expires_in);
                }
            }
            return(oAuthAccessTokenBag.OAuthAccessTokenResult);
        }
コード例 #14
0
        public BpmsCartableApiControlBase()
        {
            if (this.MyRequest.Headers.AllKeys.Contains("clientIp"))
            {
                this.ClientIp = this.MyRequest.Headers["clientIp"].ToStringObj();
            }
            else
            {
                this.ClientIp = ApiUtility.GetIPAddress();
            }

            using (APIAccessService apiAccessService = new APIAccessService())
            {
                //api call using toke header,which is password, or formToken ,which is a parameter like antiforgerytoken cosist of sessionId and mainDynamicFormId encripted by sessionId.
                if (!this.MyRequest.Headers.AllKeys.Contains("token"))
                {
                    this.ClientUserName  = DomainUtility.IsTestEnvironment ? "bpms_expert" : base.UserInfo.Username;
                    this.ClientFormToken = this.MyRequest.QueryString[FormTokenUtility.FormToken].ToStringObj();
                    this.ClientId        = HttpContext.Current.Session.SessionID;
                    this.ApiSessionId    = DomainUtility.CreateApiSessionID(this.ClientId, this.ClientIp);
                    this.IsEncrypted     = FormTokenUtility.GetIsEncrypted(this.ClientFormToken, this.ClientId);
                }
                else
                {
                    if (this.MyRequest.Headers.AllKeys.Contains("userName"))
                    {
                        this.ClientUserName = this.MyRequest.Headers["userName"].ToStringObj();
                    }

                    this.ClientId     = this.MyRequest.Headers["clientId"].ToStringObj();
                    this.ApiSessionId = DomainUtility.CreateApiSessionID(this.ClientId, this.ClientIp);;
                    //set ApiSessionID
                    if (!apiAccessService.HasAccess(ApiUtility.GetIPAddress(), this.MyRequest.Headers.GetValues("token").FirstOrDefault()))
                    {
                        throw new Exception("You are not authorized to access this application.");
                    }
                    this.IsEncrypted = this.MyRequest.Headers["isEncrypted"].ToStringObj() == "1";
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static async Task <AccessTokenResult> GetAccessTokenResultAsync(string clientId, bool getNewToken = false, SessionType sessionType = SessionType.Prod)
        {
            if (!CheckRegistered(clientId))
            {
                throw new UnRegisterClientIdException(clientId, string.Format("此clientId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", clientId));
            }

            var accessTokenBag = TryGetItem(clientId);

            using (Cache.BeginCacheLock(LockResourceName, clientId))//同步锁
            {
                if (getNewToken || accessTokenBag.AccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    var accessTokenResult = await CommonApi.GetAccessTokenAsync(accessTokenBag.ClientId, accessTokenBag.ClientSecret, accessTokenBag.PreAuthCode, accessTokenBag.RedirectUri, sessionType);

                    accessTokenBag.AccessTokenResult     = accessTokenResult;
                    accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.data.expires_in);
                }
            }
            return(accessTokenBag.AccessTokenResult);
        }
コード例 #16
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);
        }
コード例 #17
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);
        }
コード例 #18
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="wxOpenAppId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public static async Task<IAccessTokenResult> GetAccessTokenResultAsync(string wxOpenAppId, bool getNewToken = false)
        {
            if (!await CheckRegisteredAsync(wxOpenAppId).ConfigureAwait(false))
            {
                throw new UnRegisterAppIdException(wxOpenAppId, string.Format("此wxOpenAppId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", wxOpenAppId));
            }

            var accessTokenBag = await TryGetItemAsync(wxOpenAppId).ConfigureAwait(false);

            using (await Cache.BeginCacheLockAsync(LockResourceName, wxOpenAppId).ConfigureAwait(false))//同步锁
            {
                if (getNewToken || accessTokenBag.AccessTokenExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    var accessTokenResult = await CommonApi.GetTokenAsync(accessTokenBag.WxOpenAppId, accessTokenBag.WxOpenAppSecret).ConfigureAwait(false);
                    accessTokenBag.AccessTokenResult = accessTokenResult;
                    accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);
                    await UpdateAsync(accessTokenBag, null).ConfigureAwait(false);//更新到缓存
                }
            }
            return accessTokenBag.AccessTokenResult;
        }
コード例 #19
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;
        }
コード例 #20
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <param name="isAgentConfig">是否为“应用jsapi_ticket”,如果是某个特定应用,则输入 true(用于计算 agentConfig 的签名),否则为 false。参考:<see href="https://developer.work.weixin.qq.com/document/path/90506#14924"/></param>
        /// <returns></returns>
        public static JsApiTicketResult GetTicketResult(string appId, string appSecret, bool isAgentConfig, bool getNewTicket = false)
        {
            var appKey = BuildingKey(appId, appSecret, isAgentConfig);

            if (!CheckRegistered(appKey))
            {
                throw new WeixinWorkException(UN_REGISTER_ALERT);
            }

            var jsApiTicketBag = TryGetItem(appKey);

            lock (jsApiTicketBag.Lock)
            {
                if (getNewTicket || jsApiTicketBag.ExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.CorpId, jsApiTicketBag.CorpSecret, isAgentConfig);
                    jsApiTicketBag.ExpireTime        = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
                    Update(jsApiTicketBag, null);//更新到缓存
                }
            }
            return(jsApiTicketBag.JsApiTicketResult);
        }
コード例 #21
0
        /// <summary>
        /// 获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static JsApiTicketResult GetWxCardApiTicketResult(string appId, bool getNewTicket = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new UnRegisterAppIdException(null, "此appId尚未注册,请先使用WxCardApiTicketContainer.Register完成注册(全局执行一次即可)!");
            }

            WxCardApiTicketBag wxCardApiTicketBag = TryGetItem(appId);

            using (Cache.BeginCacheLock(LockResourceName, appId))//同步锁
            {
                if (getNewTicket || wxCardApiTicketBag.WxCardApiTicketExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    wxCardApiTicketBag.WxCardApiTicketResult = CommonApi.GetTicket(wxCardApiTicketBag.AppId,
                                                                                   wxCardApiTicketBag.AppSecret,
                                                                                   "wx_card");
                    wxCardApiTicketBag.WxCardApiTicketExpireTime = ApiUtility.GetExpireTime(wxCardApiTicketBag.WxCardApiTicketResult.expires_in);
                    Update(wxCardApiTicketBag, null);
                }
            }
            return(wxCardApiTicketBag.WxCardApiTicketResult);
        }
コード例 #22
0
        /// <summary>
        /// 【异步方法】获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static async Task <JsApiTicketResult> GetTicketResultAsync(string appId, bool getNewTicket = false)
        {
            if (!CheckRegistered(appId))
            {
                throw new WeixinQyException(UN_REGISTER_ALERT);
            }

            var jsApiTicketBag = (JsApiTicketBag)ItemCollection[appId];

            //lock (jsApiTicketBag.Lock)
            {
                if (getNewTicket || jsApiTicketBag.ExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    var jsApiTicketResult = await CommonApi.GetTicketAsync(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);

                    jsApiTicketBag.JsApiTicketResult = jsApiTicketResult;
                    //jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);
                    jsApiTicketBag.ExpireTime = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
                }
            }
            return(jsApiTicketBag.JsApiTicketResult);
        }
コード例 #23
0
        public AccountModel Post([FromUri] string option, [FromBody] AccountModel model, int id)
        {
            AccountModel result = null;

            switch (option)
            {
            case "current":
                var ca = DataSession.Query <ClientAccount>().FirstOrDefault(x => x.ClientOrg.ClientOrgID == id && x.Account.AccountID == model.AccountID);

                if (ca == null)
                {
                    //no existing ClientAccount record so create a new one
                    ca = new ClientAccount()
                    {
                        ClientOrg = DataSession.Single <ClientOrg>(id),
                        Account   = DataSession.Single <Account>(model.AccountID),
                        IsDefault = false,
                        Manager   = false
                    };

                    DataSession.Insert(ca);
                }

                Provider.Data.ActiveLog.Enable(ca);

                //may need to restore physical access because there is now an active acct and other requirements are met
                string  alert;
                IClient c = DataSession.Single <ClientInfo>(ca.ClientOrg.Client.ClientID);
                Provider.Data.Client.UpdatePhysicalAccess(c, out alert);

                result = ApiUtility.CreateAccountModel(ca.Account);

                break;
            }

            return(result);
        }
コード例 #24
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <param name="sessionType"></param>
        /// <param name="requestUriSchema"></param>
        /// <returns></returns>
        public static AccessTokenResult GetAccessTokenResult(
            string clientId,
            bool getNewToken           = false,
            SessionType sessionType    = SessionType.Prod,
            UriSchema requestUriSchema = UriSchema.https)
        {
            if (!CheckRegistered(clientId))
            {
                throw new UnRegisterClientIdException(clientId, string.Format("此clientId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", clientId));
            }

            var accessTokenBag = TryGetItem(clientId);

            using (Cache.BeginCacheLock(LockResourceName, clientId))//同步锁
            {
                if (getNewToken || accessTokenBag.AccessTokenExpireTime <= DateTime.Now)
                {
                    //已过期,重新获取
                    //accessTokenBag.AccessTokenResult = CommonApi.GetToken(accessTokenBag.clientId, accessTokenBag.clientSecret);
                    //accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);

                    //accessTokenBag.AccessTokenResult = CommonApi.GetAccessToken(accessTokenBag.ClientId, accessTokenBag.ClientSecret, accessTokenBag.PreAuthCode, accessTokenBag.RedirectUri, sessionType);


                    accessTokenBag.AccessTokenResult = Com.Alibaba.Open.OAuthAPIs.OAuthApi.GetAccessToken(
                        clientId: accessTokenBag.ClientId,
                        clientSecret: accessTokenBag.ClientSecret,
                        preAuthCode: accessTokenBag.PreAuthCode,
                        redirectUrl: accessTokenBag.RedirectUri,
                        sessionType: sessionType,
                        requestSchema: requestUriSchema);

                    accessTokenBag.AccessTokenExpireTime = ApiUtility.GetExpireTime(accessTokenBag.AccessTokenResult.expires_in);
                }
            }
            return(accessTokenBag.AccessTokenResult);
        }
コード例 #25
0
        public static async Task <List <League> > ScrapeAsync(HttpClient client)
        {
            var json = await ApiUtility.GetAsync(client, URL);

            var data = JsonConvert.DeserializeObject <_1XBetData>(json, Converter.Settings);

            if (data == null)
            {
                return(null);
            }

            var filteredData = data.Value.FirstOrDefault(x => x.N == CATEGORY_SOCCER);

            if (filteredData == null)
            {
                throw new Exception("No soccer category");
            }

            var leagues = new List <League>();

            foreach (var lg in filteredData.L)
            {
                if (lg.LL.ToLower().Contains("statistics") || lg.LL.ToLower().Contains("friendlies") || lg.LL.ToLower().Contains("special") || lg.LL.ToLower().Contains("specials"))
                {
                    continue;
                }

                (var country, var countryId, var leagueName, var leagueId) = (lg.Cn, lg.Ci, lg.LL, lg.Li);

                leagues.Add(new League {
                    Country = country, CountryId = countryId.ToString(), LeagueId = leagueId.ToString(), LeagueName = leagueName, Site = BetConstants.ONEXBETNAME
                });
            }

            return(leagues);
        }
コード例 #26
0
        /// <summary>
        /// 【异步方法】获取可用Ticket
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
        /// <returns></returns>
        public static async Task <JsApiTicketResult> GetTicketResultAsync(string appId, string appSecret, bool getNewTicket = false)
        {
            if (!await CheckRegisteredAsync(BuildingKey(appId, appSecret)))
            {
                throw new WeixinWorkException(UN_REGISTER_ALERT);
            }

            var jsApiTicketBag = await TryGetItemAsync(BuildingKey(appId, appSecret));

            //lock (jsApiTicketBag.Lock)
            {
                if (getNewTicket || jsApiTicketBag.ExpireTime <= SystemTime.Now)
                {
                    //已过期,重新获取
                    var jsApiTicketResult = await CommonApi.GetTicketAsync(jsApiTicketBag.CorpId, jsApiTicketBag.CorpSecret);

                    jsApiTicketBag.JsApiTicketResult = jsApiTicketResult;
                    //jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);
                    jsApiTicketBag.ExpireTime = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
                    await UpdateAsync(jsApiTicketBag, null);//更新到缓存
                }
            }
            return(jsApiTicketBag.JsApiTicketResult);
        }
コード例 #27
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);
        }
コード例 #28
0
        public System.Net.Http.HttpResponseMessage GetData(string controller, string action, string formToken = "")
        {
            if (FormTokenUtility.ValidateFormToken(formToken, HttpContext.Current.Session.SessionID))
            {
                SingleActionSettingDTO setting = new SingleActionSettingDTO(new HttpRequestWrapper(HttpContext.Current.Request), base.PortalSettings.PortalId);
                //when calling main bpms api from client application, there  is no need to pass formToken to main bpms api.
                string url    = UrlUtility.GetApiUrl(setting.WebApiAddress, action, controller, "", this.GetParameters().ToArray());
                var    result = ApiUtility.GetData(url, setting.WebServicePass, base.UserInfo.Username, ApiUtility.GetIPAddress(), HttpContext.Current.Session.SessionID, FormTokenUtility.GetIsEncrypted(formToken, HttpContext.Current.Session.SessionID));

                /*
                 * In ReportEngine.cs response would be flushed and as a result sessionID will be rewrite with server
                 * session ID which is different with singleAction sessionID because it sends data using api to server
                 * and therefore it must rewrite sessionid there in case user call report or download a file.
                 */
                SessionIDManager Manager = new SessionIDManager();
                Manager.SaveSessionID(HttpContext.Current, HttpContext.Current.Session.SessionID, out bool redirected, out bool IsAdded);

                return(result);
            }
            else
            {
                throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.Unauthorized);
            }
        }
コード例 #29
0
        public ActionResult OrderDetails(int id)
        {
            Session["OrderNo"] = id;
            bool isLogin = false;

            if (Session["isLogin"] != null)
            {
                isLogin = (bool)Session["isLogin"];
            }
            if (!isLogin)
            {
                Session["isLogin"] = false;
                return(RedirectToAction("Login", "Home"));
            }


            UserDetails userDetails = new UserDetails();

            userDetails = ApiUtility.GetUserDetailsByOrderId(id);


            List <OrderDetails> orderDetailsList = new List <OrderDetails>();

            orderDetailsList = ApiUtility.GetOrderDetailsByOrderId(id);


            OrderPriceVM orderPrice = new OrderPriceVM();

            orderPrice = ApiUtility.GetOrderPriceCalculationByOrderId(id);

            Session["CustomerDetails"]         = userDetails;
            Session["OrderProductDetailsList"] = orderDetailsList;
            Session["OrderPriceCalculation"]   = orderPrice;
            Session["CustomerDetails"]         = userDetails;
            return(View());
        }
コード例 #30
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 = (ComponentBag)ItemCollection[componentAppId];

            // lock (accessTokenBag.Lock)
            {
                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);
        }
コード例 #31
0
        /// <summary>
        /// TryCommonApi 方法的基类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="platformType">平台类型,PlatformType枚举</param>
        /// <param name="accessTokenContainer_GetFirstOrDefaultAppIdFunc">AccessTokenContainer中的GetFirstOrDefaultAppId()方法</param>
        /// <param name="accessTokenContainer_CheckRegisteredFunc">AccessTokenContainer中的bool CheckRegistered(appId,getNew)方法</param>
        /// <param name="accessTokenContainer_GetAccessTokenResultFunc">AccessTokenContainer中的AccessTokenResult GetAccessTokenResult(appId)方法</param>
        /// <param name="invalidCredentialValue">"ReturnCode.获取access_token时AppSecret错误或者access_token无效"枚举的值</param>
        /// <param name="fun"></param>
        /// <param name="accessTokenOrAppId"></param>
        /// <param name="retryIfFaild"></param>
        /// <returns></returns>
        public static T TryCommonApiBase <T>(
            PlatformType platformType,
            Func <string> accessTokenContainer_GetFirstOrDefaultAppIdFunc,
            Func <string, bool> accessTokenContainer_CheckRegisteredFunc,
            Func <string, bool, IAccessTokenResult> accessTokenContainer_GetAccessTokenResultFunc,
            int invalidCredentialValue,
            Func <string, T> fun, string accessTokenOrAppId = null, bool retryIfFaild = true) where T : BaseJsonResult
        {
            //ApiHandlerWapperFactory.ApiHandlerWapperFactoryCollection["s"] = ()=> new Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson();

            //var platform = ApiHandlerWapperFactory.CurrentPlatform;//当前平台

            /*
             * 对于企业微信来说,AppId = key = CorpId+CorpSecret
             */

            string appId       = null;
            string accessToken = null;

            if (accessTokenOrAppId == null)
            {
                appId = accessTokenContainer_GetFirstOrDefaultAppIdFunc != null?accessTokenContainer_GetFirstOrDefaultAppIdFunc() : null;  // AccessTokenContainer.GetFirstOrDefaultAppId();

                if (appId == null)
                {
                    throw new UnRegisterAppIdException(null,
                                                       "尚无已经注册的AppId,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!模块:" + platformType);
                }
            }
            else if (ApiUtility.IsAppId(accessTokenOrAppId, platformType))
            {
                //if (!AccessTokenContainer.CheckRegistered(accessTokenOrAppId))
                if (!accessTokenContainer_CheckRegisteredFunc(accessTokenOrAppId))
                {
                    throw new UnRegisterAppIdException(accessTokenOrAppId, string.Format("此appId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!模块:" + platformType, accessTokenOrAppId));
                }

                appId = accessTokenOrAppId;
            }
            else
            {
                accessToken = accessTokenOrAppId;//accessToken
            }

            T result = null;

            try
            {
                if (accessToken == null)
                {
                    var accessTokenResult = accessTokenContainer_GetAccessTokenResultFunc(appId, false); //AccessTokenContainer.GetAccessTokenResult(appId, false);
                    accessToken = accessTokenResult.access_token;
                }
                result = fun(accessToken);
            }
            catch (ErrorJsonResultException ex)
            {
                if (retryIfFaild &&
                    appId != null       //如果 appId 为 null,已经没有重试的意义(直接提供的 AccessToken 是错误的)
                                        //&& ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效)
                    && (int)ex.JsonResult.errcode == invalidCredentialValue)
                {
                    //尝试重新验证
                    var accessTokenResult = accessTokenContainer_GetAccessTokenResultFunc(appId, true);//AccessTokenContainer.GetAccessTokenResult(appId, true);
                    //强制获取并刷新最新的AccessToken
                    accessToken = accessTokenResult.access_token;
                    result      = TryCommonApiBase(platformType,
                                                   accessTokenContainer_GetFirstOrDefaultAppIdFunc,
                                                   accessTokenContainer_CheckRegisteredFunc,
                                                   accessTokenContainer_GetAccessTokenResultFunc,
                                                   invalidCredentialValue,
                                                   fun, accessToken, false);
                }
                else
                {
                    ex.AccessTokenOrAppId = accessTokenOrAppId;
                    throw;
                }
            }
            catch (WeixinException ex)
            {
                ex.AccessTokenOrAppId = accessTokenOrAppId;
                throw;
            }

            return(result);
        }