Beispiel #1
0
        public string GetToken(PushConfig config, string source = "")
        {
            object token = null;

            if (config.EnableTokenCache.ToLower() == "true")
            {
                token = cache.Get <object>(config.Value);
            }
            if (token == null)
            {
                lock (cacheLock)
                {
                    if (token == null)
                    {
                        string GetTokenUrl = config.TokenUrl;
                        string appId       = config.AppId;
                        string appSecret   = config.AppSecret;
                        long   t           = DateTimeOffset.Now.ToUnixTimeSeconds();  // 相差秒数
                        var    key         = ToMD5(appId + appSecret + t);
                        var    p           = JsonConvert.SerializeObject(new { AppID = appId, t = t.ToString(), sign = key });
                        string res         = string.Empty;
                        if (source.Contains("api"))
                        {
                            res = PostHttps(GetTokenUrl, p);
                        }
                        else
                        {
                            res = Post(GetTokenUrl, p);
                        }
                        if (res.IndexOf("ErrorCode") < 0)
                        {
                            //成功
                            var info = JsonConvert.DeserializeObject <dynamic>(res);
                            token = info.access_token;
                            if (config.EnableTokenCache.ToLower() == "true")
                            {
                                var expires = Convert.ToInt32(info.expires_in);//token 过期时间
                                var st      = DateTime.Now.AddSeconds(expires);
                                cache.Insert(config.Value, token, st);
                            }
                        }
                        else
                        {
                            //错误,记录日志
                            throw new Exception("获取Token出错,错误信息:" + res + "; 请求参数,1_GetTokenUrl:" + GetTokenUrl + " 2_p:" + p + ";config:" + JsonConvert.SerializeObject(config));
                        }
                    }
                }
            }
            return(token.ToString());
        }