/// <summary> /// 调用获取秘钥api /// </summary> /// <param name="session"></param> /// <param name="secretVersion"></param> /// <returns></returns> private SecretContext CallSecretApi(string session, Nullable <Int64> secretVersion) { // 获取伪随机码 if (string.IsNullOrEmpty(randomNum)) { throw new ArgumentException("randomNum can`t be empty"); } TopSecretGetRequest request = new TopSecretGetRequest(); request.RandomNum = randomNum; request.SecretVersion = secretVersion; if (streetest) { request.AddOtherParameter("tb_eagleeyex_t", "1"); } TopSecretGetResponse response; if (session != null && session.StartsWith(UNDERLINE)) { string customerUserId = session.Substring(1); if (!StringUtil.IsDigits(customerUserId)) { throw new ArgumentException("session invalid"); } request.CustomerUserId = Convert.ToInt64(customerUserId); response = topClient.Execute(request, null); } else { response = topClient.Execute(request, session); } if (!response.IsError) { IDictionary <string, Object> appConfig = null; if (!string.IsNullOrEmpty(response.AppConfig)) { appConfig = (IDictionary <string, Object>)TopUtils.JsonToObject(response.AppConfig); putAppConfig(appConfig); } SecretContext secretContext = new SecretContext(); if (response.Secret != null) { long currentTime = TopUtils.GetCurrentTimeMillis(); secretContext.InvalidTime = currentTime + (response.Interval * 1000); secretContext.MaxInvalidTime = (currentTime + (response.MaxInterval * 1000)); secretContext.Secret = Convert.FromBase64String(response.Secret); secretContext.SecretVersion = response.SecretVersion; } else { if (appConfig != null) { object publishStatus = null; appConfig.TryGetValue(PUBLISH_STATUS, out publishStatus); if (BETA_STATUS.Equals(publishStatus)) { // 设置空缓存 SetNullCache(secretContext); } } } PutToCache(session, secretVersion, secretContext); return(secretContext); } else { // 查找不到历史秘钥 if ("20005".Equals(response.SubErrCode)) { SecretContext secretContext = new SecretContext(); // 设置空缓存 SetNullCache(secretContext); PutToCache(session, secretVersion, secretContext); return(secretContext); } throw new SecretException(response.ErrCode, response.ErrMsg, response.SubErrCode, response.SubErrMsg); } }
private T DoExecuteOApi <T>(IDingTalkRequest <T> request, string session, string accessKey, string accessSecret, string suiteTicket, string corpId, DateTime timestamp) where T : DingTalkResponse { long start = DateTime.Now.Ticks; // 提前检查业务参数 try { request.Validate(); } catch (TopException e) { return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg)); } this.format = Constants.FORMAT_JSON; // 添加协议级请求参数 TopDictionary txtParams = new TopDictionary(request.GetParameters()); txtParams.Add(DingTalkConstants.ACCESS_TOKEN, session); // 添加头部参数 if (this.useGzipEncoding) { request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP; } string realServerUrl = null; // 签名优先 if (accessKey != null) { long dingTimestamp = GetTimestamp(DateTime.UtcNow); // 验证签名有效性 String canonicalString = DingTalkSignatureUtil.GetCanonicalStringForIsv(dingTimestamp, suiteTicket); String signature = DingTalkSignatureUtil.ComputeSignature(accessSecret, canonicalString); IDictionary <String, String> ps = new Dictionary <String, String>(); ps.Add("accessKey", accessKey); ps.Add("signature", signature); ps.Add("timestamp", dingTimestamp + ""); if (suiteTicket != null) { ps.Add("suiteTicket", suiteTicket); } if (corpId != null) { ps.Add("corpId", corpId); } String queryStr = DingTalkSignatureUtil.ParamToQueryString(ps, "utf-8"); if (this.serverUrl.IndexOf("?") > 0) { realServerUrl = this.serverUrl + "&" + queryStr; } else { realServerUrl = this.serverUrl + "?" + queryStr; } } else { if (this.serverUrl.IndexOf("?") > 0) { realServerUrl = this.serverUrl + (session != null && session != "" ? ("&access_token=" + session) : ""); } else { realServerUrl = this.serverUrl + (session != null && session != "" ? ("?access_token=" + session) : ""); } } try { string body; if (request.GetHttpMethod() == "POST") { if (request is IDingTalkUploadRequest <T> ) // 是否需要上传文件 { IDingTalkUploadRequest <T> uRequest = (IDingTalkUploadRequest <T>)request; IDictionary <string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters()); body = webUtils.DoPost(realServerUrl, null, fileParams, request.GetHeaderParameters()); } else { IDictionary <String, Object> jsonParams = new Dictionary <String, Object>(); foreach (string key in request.GetParameters().Keys) { string value = request.GetParameters()[key]; if (value.StartsWith("[") && value.EndsWith("]")) { IList childMap = (IList)TopUtils.JsonToObject(value); jsonParams.Add(key, childMap); } else if (value.StartsWith("{") && value.EndsWith("}")) { IDictionary <string, Object> childMap = (IDictionary <string, Object>)TopUtils.JsonToObject(value); jsonParams.Add(key, childMap); } else { jsonParams.Add(key, value); } } body = webUtils.DoPostWithJson(realServerUrl, jsonParams, request.GetHeaderParameters()); } } else { body = webUtils.DoGet(realServerUrl, request.GetParameters()); } // 解释响应结果 T rsp; if (disableParser) { rsp = Activator.CreateInstance <T>(); rsp.Body = body; } else { ITopParser <T> tp = new DingTalkJsonParser <T>(); rsp = tp.Parse(body); } // 追踪错误的请求 if (rsp.IsError) { TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start); TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body); } return(rsp); } catch (Exception e) { TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start); TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message); throw e; } }
public static DnsConfig parse(string json) { DnsConfig dnsConfig = new DnsConfig(); IDictionary root = TopUtils.JsonToObject(json) as IDictionary; foreach (string configType in root.Keys) { if ("config".Equals(configType)) { dnsConfig.GlobalDict = new Dictionary <string, string>(); IDictionary globalInfo = root[configType] as IDictionary; foreach (string key in globalInfo.Keys) { dnsConfig.GlobalDict[key] = globalInfo[key] as string; } } else if ("env".Equals(configType)) { IDictionary envInfos = root[configType] as IDictionary; dnsConfig.EnvDict = new Dictionary <string, List <EnvConfig> >(); foreach (string envName in envInfos.Keys) { IDictionary envInfo = envInfos[envName] as IDictionary; List <EnvConfig> envConfigs = new List <EnvConfig>(); foreach (string domainName in envInfo.Keys) { IDictionary domainInfo = envInfo[domainName] as IDictionary; EnvConfig envConfig = new EnvConfig(); envConfig.Domain = domainName as string; envConfig.Protocol = domainInfo["proto"] as string; IList vipInfos = domainInfo["vip"] as IList; List <VipRule> vipRules = new List <VipRule>(); foreach (string vipInfo in vipInfos) { string[] vipInfoTmp = vipInfo.ToString().Split('|'); VipRule vipRule = new VipRule(); vipRule.Vip = vipInfoTmp[0]; vipRule.Weight = double.Parse(vipInfoTmp[1]); vipRules.Add(vipRule); } envConfig.VipRules = vipRules; envConfigs.Add(envConfig); } dnsConfig.EnvDict[envName] = envConfigs; } } else if ("api".Equals(configType)) { dnsConfig.ApiDict = new Dictionary <string, ApiConfig>(); IDictionary apiInfos = root[configType] as IDictionary; foreach (string apiName in apiInfos.Keys) { IDictionary apiInfo = apiInfos[apiName] as IDictionary; ApiConfig apiConfig = new ApiConfig(); apiConfig.User = apiInfo["user"] as string; List <ApiRule> apiRules = new List <ApiRule>(); IList apiRuleInfos = apiInfo["rule"] as IList; foreach (string apiRuleInfo in apiRuleInfos) { string[] apiRuleInfoTmp = apiRuleInfo.ToString().Split('|'); ApiRule apiRule = new ApiRule(); apiRule.Name = apiRuleInfoTmp[0]; apiRule.Weight = double.Parse(apiRuleInfoTmp[1]); apiRules.Add(apiRule); } apiConfig.Rules = apiRules; dnsConfig.ApiDict[apiName] = apiConfig; } } else if ("user".Equals(configType)) { dnsConfig.UserDict = new Dictionary <string, IDictionary <string, string> >(); IDictionary userInfos = root[configType] as IDictionary; foreach (string routeName in userInfos.Keys) { IDictionary envInfos = userInfos[routeName] as IDictionary; IDictionary <string, string> tags = new Dictionary <string, string>(); foreach (string envName in envInfos.Keys) { IList tagInfos = envInfos[envName] as IList; foreach (string tagName in tagInfos) { tags.Add(tagName, envName); } } dnsConfig.UserDict[routeName] = tags; } } } return(dnsConfig); }