/// <summary> /// 修改消息状态接口 /// </summary> /// <param name="id">Id</param> /// <param name="status">状态</param> /// <returns></returns> public int UpDateStatus(int id, int status) { try { string parameter = GetChangeOutWindowParameter(id, status); string res = RequestHelper.WebRequest(ChangeOutWindow, "post", parameter, "UTF-8", true); if (!string.IsNullOrEmpty(res)) { res = new EncDecUtil().decyptData(res, accesskey); } Loger.Info("PlanId:" + id + ",修改消息状态接口返回结果:" + res); SsoRes listSsoRes = JsonHelper.DeserializeJson <SsoRes>(res); if (listSsoRes == null) { return(-1); } return(listSsoRes.error); } catch (Exception ex) { Loger.Error(ex, "\r\n=====error=====\r\nPlanId:" + id + ",修改消息状态异常:"); return(-1); } }
protected User GetUser() { string infoStr = EncDecUtil.Decrypt(Request.Cookies[Keywords.USER].Value, Configs.CRYPTO_PASSWORD); User user = SerializeUtil.DeSerializeAnObject(infoStr, typeof(User)) as User; return(user); }
/// <summary> /// 推送(炒股大赛) /// </summary> public void SsoPushStockContest(StockContestData scd) { SsoOutWindowBLL ssoOutWindowBll = Factory.BusinessFactory.CreateBll <SsoOutWindowBLL>(); string msgTitle = string.Format(ConfigurationManager.AppSettings["StockContestMobileMsg"], scd.OperateUserName, scd.OperateType, scd.StockName, scd.Price); //pc端推送 string parameter = GetAddOutWindowParameter(scd); string res = RequestHelper.WebRequest(AddOutWindow, "post", parameter, "UTF-8", false); if (!string.IsNullOrEmpty(res)) { res = new EncDecUtil().decyptData(res, accesskey); SsoRes ssoRes = JsonHelper.DeserializeJson <SsoRes>(res); // 调用接口状态码,0:成功,1:该消息id 已存在,2:链接地址不存在,3:用户群组不存在,4:开始时间与结束时间不匹配,9:其它异常 if (ssoRes.error != 0) { Loger.Error("[炒股大赛] SSO数据推送返回失败, 返回:" + res + "\r\n相关参数:" + JsonHelper.ToJson(scd)); } } else { Loger.Error("SSO接口调用返回空=====error=====(一般情况不会出现, 出现在超时或者无法调用)"); } Loger.Info("[炒股大赛] id=" + scd.Id + " SSO数据推送返回结果: " + res + "\r\n相关参数:" + JsonHelper.ToJson(scd) + "\r\n手机推送中..."); //入手机端推送表 int num = ssoOutWindowBll.UpDataTB_MOBPUSH_USERINFO_StockContest(scd, msgTitle); Loger.Info("[炒股大赛] id=" + scd.Id + " 手机推送表更新数:" + num); }
public void Test3DESKeyEncrypt() { string key = EncDecUtil.GetEncryptKey("654321"); string encryptedKey = EncDecUtil.Base64Encrypt(EncDecUtil.RSAEncrypt("D:/cer/700000000000001.pfx", "000000", key)); Assert.IsTrue(encryptedKey != null); }
public void TestEncrypt() { string s1 = EncDecUtil.GetEncryptKey("654321"); string rightEncryptedS1 = "HyWvyTPmlX2M/XJruMxKMIldV42XG2eCoV5o8Gi6CgifcIlKky3a8+tVnof8pnz34+HvKt9tk2C0wa2LEy9Vz0cXiBn2DTh/G8hka9QKdyjER+YtZYRqfU/qpJnw+xvcWvPo9HZXykWAYHuCPjnbPoKLex6xh6Xh0g2ES10Gxhc="; var encryptedS1 = EncDecUtil.Base64Encrypt(EncDecUtil.RSAEncrypt("D:/cer/630056832596.pfx", "123456", s1)); Assert.IsTrue(encryptedS1 != null); Assert.IsTrue(encryptedS1 == rightEncryptedS1); }
public void TestTripleDesEncrypt() { string s1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><upbp application=\"MGw.Req\" version =\"1.0.0\" sendTime =\"20131223155031\" sendSeqId =\"12345888888000\"><frontUrl>http://www.163.com</frontUrl><merchantOrderDesc></merchantOrderDesc><misc></misc><gwType>01</gwType><transTimeout>ssssss</transTimeout><backUrl>http://192.168.1.156:8080/Test/Notify</backUrl><merchantOrderCurrency>156</merchantOrderCurrency><merchantOrderAmt>1</merchantOrderAmt><merchantOrderDesc>呵呵</merchantOrderDesc><merchantId>630056832596</merchantId><merchantOrderTime>20131223155031</merchantOrderTime><merchantOrderId>20131223155031</merchantOrderId><merchantUserId></merchantUserId><mobileNum>15388157741</mobileNum><cardNum></cardNum></upbp>"; string key = EncDecUtil.GetEncryptKey("654321"); string rightEncryptedS1 = "Dau3eXih4xg1yrTZhvQ9RCd/nMVK4dNRiTWXjAh9OT0uyUEroFMYrAmndlfsulEQsqjwZu3W7AVpqiDQdsOJmiKD83+xtm1Zks5CUhvzPirQH2yzyTVnycXWkGUzYE2NZzoo4BtTPWmK1BMtXc8Edm2VvT0LpghUYGji+D2B2cJKuNlFrBXb/VU2hOK3xF7VFnLYax79Vdtdnj9HUR4Jnk5i1bCLWzQT+l07WkLcpTkKY3ud7NrP/lqKXScLWoCXR9glH24OLIb8BHmNcwMKNEVbWgJHWmsxdJHG0BKhi7pOzKabx5LbqWl6UWGaun9Ll7NZYVTwYekA6yynWk5L+OCOFcM32pCzRY8cMM+nV0zakyyyKJ3MUS6sXMFXfXUOFnLYax79VdsKUt1osFs7Yf/yCpnfAOcMxfOxWmaThaGIZhkxOILqZMuBj6eduJF7tc+RUaOClbVPI/rtai13xrk5BjIjNam72WMD0Qsffu8bmf1lvDMuVoovUujpjGx13fesDllvf5X8BHmNcwMKNBD8j+EOIidzPqf0D8gxU1arGJzIkdTGxn9Z9BzE68q0TyP67Wotd8a+o9HAhfJAwGi5rLQTaH26/AR5jXMDCjRFW1oCR1prMbp6Y1t3I1YT/QGIquncWYxggdTCBg7jIT6n9A/IMVNWvc9EfUBtNPv8BHmNcwMKNCUwZThqh4f9tz8WDOJGDc/69FiKnWivNn1UwC4pOEzmWAwqYmShn73bDfvoTQ1Mcuwx1m51Qv6d7jaq9dMk1TTRr2q/xF+7oKmSrko/d9qp7DHWbnVC/p2PTW+ta0IdUKITi57cBHPbGm2hsCCCWGkocaY7ZvTsMkB5fUWRlHPjxYQQtmSCXpRp+d8eGu4LOixT8QQOUv3zDIggDEqf900a3FMkTQngKby0H5cpi1yZBK/VZOjeGKhpVm+NHIcoeg=="; var encryptedS1 = EncDecUtil.Base64Encrypt(EncDecUtil.TripleDESEncrypt(key, s1)); Assert.IsTrue(encryptedS1 != null); Assert.IsTrue(encryptedS1 == rightEncryptedS1); }
//static string API_URL = "http://58.246.136.11:8006/wapDetect/gateWay!gate.ac"; #region 工具方法 /// <summary> /// 调用API /// </summary> /// <typeparam name="TRequest">向支付接口发送的请求的类型</typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="pChannel"></param> /// <param name="pRequest"></param> /// <returns></returns> private static TResponse CallAPI <TRequest, TResponse>(UnionPayChannel pChannel, TRequest pRequest) where TRequest : BaseAPIRequest where TResponse : BaseAPIResponse, new() { //参数校验 if (pChannel == null) { throw new ArgumentNullException("pChannel"); } if (string.IsNullOrWhiteSpace(pChannel.MerchantID)) { throw new ArgumentNullException("pChannel.MerchantID"); } if (pRequest == null) { throw new ArgumentNullException("pRequest"); } // var reqContent = pRequest.GetContent(); var merchantID = EncDecUtil.Base64Encrypt(pChannel.MerchantID); //Base64加密商户ID var desKey = EncDecUtil.GetEncryptKey(pChannel.PacketEncryptKey); //获取实际加密密钥 //采用Base64(RSA(加密密钥))计算出报文中的加密密钥 var encryptedDesKey = EncDecUtil.Base64Encrypt(EncDecUtil.RSAEncrypt(pChannel.CertificateFilePath, pChannel.CertificateFilePassword, desKey + "11111111")); //采用Base64(3DES(报文))加密报文 var encryptedContent = EncDecUtil.Base64Encrypt(EncDecUtil.TripleDESEncrypt(desKey, reqContent)); // var requestContent = merchantID + "|" + encryptedDesKey + "|" + encryptedContent; using (WebClient wc = new WebClient()) { string strResponse = wc.UploadString(IVRGateway.API_URL, requestContent); string[] responseSections = strResponse.Split('|'); string rspCode = responseSections[0]; string rspContent = responseSections[1]; // if (rspCode == "1") { var decRspBytes = EncDecUtil.TripleDESDecrypt(desKey, EncDecUtil.Base64Decrypt(rspContent)); string decRspContent = Encoding.UTF8.GetString(decRspBytes); decRspContent = decRspContent.Replace("\0", string.Empty); TResponse rsp = new TResponse(); rsp.Load(decRspContent); // return(rsp); } else { string errorCode = rspContent; string errorMsg = Encoding.UTF8.GetString(EncDecUtil.Base64Decrypt(responseSections[2])); UnionPayException ex = new UnionPayException(errorMsg); ex.Code = errorCode; throw ex; } } }
public static ReqResponse CallAPI <TRequest>(NegotiationPayChannel pChannel, TRequest pRequest) where TRequest : NeBaseAPIRequest { if (pRequest == null) { throw new ArgumentNullException("pRequest"); } var reqContent = pRequest.GetContent(); var merchantID = JIT.CPOS.BS.Web.ApplicationInterface.Negotiation.Util.EncDecUtil.Base64Encrypt(pChannel.MerchantID); string CertificateFilePath = HttpContext.Current.Server.MapPath("~/" + pChannel.CertificateFilePath); RSAGenerator rsa = new RSAGenerator(); string key = rsa.getPublicKey(); var desKey = EncDecUtil.GetEncryptKey(key); //获取实际加密密钥 //采用Base64(RSA(加密密钥))计算出报文中的加密密钥 var encryptedDesKey = EncDecUtil.Base64Encrypt(EncDecUtil.RSAEncrypt(CertificateFilePath, pChannel.CertificateFilePassword, desKey + "11111111")); //采用Base64(3DES(报文))加密报文 var encryptedContent = EncDecUtil.Base64Encrypt(EncDecUtil.TripleDESEncrypt(desKey, reqContent)); //使用md5生成摘要 var md5 = EncDecUtil.CreateMD5Encod(reqContent); var requestContent = merchantID + "|" + encryptedDesKey + "|" + encryptedContent + "|" + md5; using (WebClient wc = new WebClient()) { string strResponse = wc.UploadString(url, requestContent); string[] responseSections = strResponse.Split('|'); string rspCode = responseSections[0]; string rspContent = responseSections[1]; if (rspCode == "1") { var decRspBytes = EncDecUtil.TripleDESDecrypt(desKey, EncDecUtil.Base64Decrypt(rspContent)); string decRspContent = Encoding.UTF8.GetString(decRspBytes); decRspContent = decRspContent.Replace("\0", string.Empty); ReqResponse req = new ReqResponse(); req.ResultCode = rspCode; req.Data = decRspContent; return(req); } else { string errorCode = rspContent; string errorMsg = Encoding.UTF8.GetString(EncDecUtil.Base64Decrypt(responseSections[2])); UnionPayException ex = new UnionPayException(errorMsg); ex.Code = errorCode; Log.Loggers.Exception(new Log.ExceptionLogInfo(ex) { ErrorMessage = ex.ToString() }); ReqResponse req = new ReqResponse(); req.ResultCode = errorCode; req.Message = errorMsg; return(req); } } }
/// <summary> /// 参数加密 /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> private string EncodeString(string jsonStr) { string result = string.Empty; EncDecUtil encDecUtil = new EncDecUtil(); string key = encDecUtil.encyptData(jsonStr, accesskey); string sign = encDecUtil.signData(key, accesskey); result = string.Format("key={0}&sign={1}&clientId={2}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(sign), clientId); return(result); }
protected void SetUserInfoToCooke(User user) { string encVal = null; if (user != null) { string serUser = SerializeUtil.SerializeAnObject(user); encVal = EncDecUtil.Encrypt(serUser, Configs.CRYPTO_PASSWORD); } HttpCookie cookie = new HttpCookie(Keywords.USER) { Value = encVal, Expires = DateTime.Now.AddDays(user != null ? Configs.COOKIE_LIFE_TIME : -1) }; Response.Cookies.Add(cookie); }
/// <summary> /// SSO数据推送, 重推 /// </summary> /// <param name="ssoResultId">ssoResultId</param> public void SsoPushOne(int ssoResultId) { int planId = 0; try { SSOResultBLL ssoResultBll = Factory.BusinessFactory.CreateBll <SSOResultBLL>(); SSOResult ssoResult = ssoResultBll.Get("Id", ssoResultId); if (ssoResult != null) { PopupMsgPlanBLL opupMsgPlanBll = Factory.BusinessFactory.CreateBll <PopupMsgPlanBLL>(); PopupMsgPlan popupMsgPlan = opupMsgPlanBll.Get("PlanId", ssoResult.PlanId); planId = (int)ssoResult.PlanId; if (popupMsgPlan != null) { List <string> listUserName = GetUserNameToGroup(ssoResult.ErrorUser); //所有错误用户, 每100个一组 string parameter = string.Empty; int i = 0; foreach (var userName in listUserName) { parameter = GetAddOutWindowParameter(popupMsgPlan, userName); string res = RequestHelper.WebRequest(AddOutWindow, "post", parameter, "UTF-8", true); if (!string.IsNullOrEmpty(res)) { res = new EncDecUtil().decyptData(res, accesskey); } Loger.Info("PlanId:" + planId + ",SSO数据重推返回结果:" + res); UpDataSsoResult(userName, res, ssoResult, i); i++; } } } } catch (Exception ex) { Loger.Error(ex, "\r\n=====error=====\r\nPlanId:" + planId + ",SSO数据重推异常:"); } }
/// <summary> /// search by track title /// </summary> /// <param name="search"></param> /// <returns></returns> public async Task <IActionResult> OnPostSearchByTrackTitleAsync(string search, bool secondtime = false) { List <TrackQueryResult> tracks = new List <TrackQueryResult>(); if (bool.Parse(Configuration["MockSpotify"])) { tracks.Add( new TrackQueryResult() { Name = "من بی می ناب زیستن نتوانم", Id = "1", Url = "https://beeptunes.com/track/3434445", Image = "https://api.ganjoor.net/api/rimages/d32a98c3-a20c-4d37-45a9-08d93cffb0b7.jpg", ArtistName = "محمدرضا شجریان", ArtistId = "1", ArtistUrl = "https://beeptunes.com/artist/3403349", AlbumName = "رباعیات خیام", AlbumId = "1", AlbunUrl = "https://beeptunes.com/album/3412806" } ); } else { if (!_memoryCache.TryGetValue("SpotifyAccessToken", out string spotifyAccessToken)) { using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseOption = await secureClient.GetAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken"); if (!responseOption.IsSuccessStatusCode) { spotifyAccessToken = ""; return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()))); } else { string encryptedAccessToken = JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()); spotifyAccessToken = EncDecUtil.Decrypt(encryptedAccessToken, Configuration.GetSection("Spotify")["Salt"]); _memoryCache.Set("SpotifyAccessToken", spotifyAccessToken); } } else { return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>("لطفا از گنجور خارج و مجددا به آن وارد شوید."))); } } } string spotifyToken = $"Bearer {spotifyAccessToken}"; var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spotify.com/v1/search?q={search}&type=track"); request.Headers.Add("Authorization", spotifyToken); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); var parsed = JObject.Parse(json); foreach (JToken track in parsed.SelectTokens("tracks.items[*]")) { string imageUrl = ""; NameIdUrlImage artistInfo = new NameIdUrlImage() { Id = "0", Name = "", Url = "", Image = "" }; foreach (JToken artist in track.SelectTokens("artists[*]")) { artistInfo.Name = artist.SelectToken("name").Value <string>(); artistInfo.Id = artist.SelectToken("id").Value <string>(); artistInfo.Url = artist.SelectToken("external_urls.spotify").Value <string>(); break; } NameIdUrlImage albumInfo = new NameIdUrlImage() { Id = "0", Name = "", Url = "", Image = "" }; JToken album = track.SelectToken("album"); if (album != null) { albumInfo.Name = album.SelectToken("name").Value <string>(); albumInfo.Id = album.SelectToken("id").Value <string>(); albumInfo.Url = album.SelectToken("external_urls.spotify").Value <string>(); foreach (JToken image in album.SelectTokens("images[*].url")) { imageUrl = image.Value <string>(); break; } } tracks.Add( new TrackQueryResult() { Name = track.SelectToken("name").Value <string>(), Id = track.SelectToken("id").Value <string>(), Url = track.SelectToken("external_urls.spotify").Value <string>(), Image = imageUrl, ArtistName = artistInfo.Name, ArtistId = artistInfo.Id, ArtistUrl = artistInfo.Url, AlbumName = albumInfo.Name, AlbumId = albumInfo.Id, AlbunUrl = albumInfo.Url } ); } } else { if (!secondtime) { await _RefreshSpotifyToken(); return(await OnPostSearchByTrackTitleAsync(search, true)); } return(BadRequest(response.ToString())); } } return(new PartialViewResult() { ViewName = "_SpotifySearchPartial", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = new _SpotifySearchPartialModel() { Tracks = tracks.ToArray() } } }); }
/// <summary> /// fill album tracks /// </summary> /// <param name="album">is an ID and consists of numeric and non-numeric characters</param> /// <returns></returns> public async Task <IActionResult> OnPostFillTracksAsync(string album, bool secondtime = false) { List <NameIdUrlImage> tracks = new List <NameIdUrlImage>(); if (bool.Parse(Configuration["MockSpotify"])) { tracks.Add( new NameIdUrlImage() { Name = "من بی می ناب زیستن نتوانم", Id = "1", Url = "https://beeptunes.com/track/3434445", Image = "https://api.ganjoor.net/api/rimages/d32a98c3-a20c-4d37-45a9-08d93cffb0b7.jpg" } ); } else { if (!_memoryCache.TryGetValue("SpotifyAccessToken", out string spotifyAccessToken)) { using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseOption = await secureClient.GetAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken"); if (!responseOption.IsSuccessStatusCode) { spotifyAccessToken = ""; return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()))); } else { string encryptedAccessToken = JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()); spotifyAccessToken = EncDecUtil.Decrypt(encryptedAccessToken, Configuration.GetSection("Spotify")["Salt"]); _memoryCache.Set("SpotifyAccessToken", spotifyAccessToken); } } else { return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>("لطفا از گنجور خارج و مجددا به آن وارد شوید."))); } } } string spotifyToken = $"Bearer {spotifyAccessToken}"; var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spotify.com/v1/albums/{album}/tracks?limit=50"); request.Headers.Add("Authorization", spotifyToken); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); var parsed = JObject.Parse(json); foreach (JToken track in parsed.SelectTokens("items[*]")) { string imageUrl = ""; foreach (JToken image in track.SelectTokens("images[*].url")) { imageUrl = image.Value <string>(); break; } tracks.Add( new NameIdUrlImage() { Name = track.SelectToken("name").Value <string>(), Id = track.SelectToken("id").Value <string>(), Url = track.SelectToken("external_urls.spotify").Value <string>(), Image = imageUrl } ); } } else { if (!secondtime) { await _RefreshSpotifyToken(); return(await OnPostFillTracksAsync(album, true)); } return(BadRequest(response.ToString())); } } return(new OkObjectResult(tracks.ToArray())); }
/// <summary> /// fill artist albums /// </summary> /// <param name="artist">is an ID and consists of numeric and non-numeric characters</param> /// <returns></returns> public async Task <IActionResult> OnPostFillAlbumsAsync(string artist, bool secondtime = false) { List <NameIdUrlImage> albums = new List <NameIdUrlImage>(); if (bool.Parse(Configuration["MockSpotify"])) { albums.Add( new NameIdUrlImage() { Name = "رباعیات خیام", Id = "1", Url = "https://beeptunes.com/track/3434445", Image = "https://api.ganjoor.net/api/rimages/d32a98c3-a20c-4d37-45a9-08d93cffb0b7.jpg" } ); } else { if (!_memoryCache.TryGetValue("SpotifyAccessToken", out string spotifyAccessToken)) { using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseOption = await secureClient.GetAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken"); if (!responseOption.IsSuccessStatusCode) { spotifyAccessToken = ""; return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()))); } else { string encryptedAccessToken = JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()); spotifyAccessToken = EncDecUtil.Decrypt(encryptedAccessToken, Configuration.GetSection("Spotify")["Salt"]); _memoryCache.Set("SpotifyAccessToken", spotifyAccessToken); } } else { return(new BadRequestObjectResult(JsonConvert.DeserializeObject <string>("لطفا از گنجور خارج و مجددا به آن وارد شوید."))); } } } string spotifyToken = $"Bearer {spotifyAccessToken}"; int offest = 0; int limit = 50; bool newItems; do { var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spotify.com/v1/artists/{artist}/albums?limit={limit}&offset={offest}"); request.Headers.Add("Authorization", spotifyToken); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); var parsed = JObject.Parse(json); newItems = false; foreach (JToken album in parsed.SelectTokens("items[*]")) { newItems = true; string imageUrl = ""; foreach (JToken image in album.SelectTokens("images[*].url")) { imageUrl = image.Value <string>(); break; } string album_type = album.SelectToken("album_type").Value <string>(); if (album_type == "album" || album_type == "single") { albums.Add( new NameIdUrlImage() { Name = album.SelectToken("name").Value <string>(), Id = album.SelectToken("id").Value <string>(), Url = album.SelectToken("external_urls.spotify").Value <string>(), Image = imageUrl } ); } } } else { if (!secondtime && offest == 0) { await _RefreshSpotifyToken(); return(await OnPostFillAlbumsAsync(artist, true)); } return(BadRequest(response.ToString())); } offest += limit; }while (newItems); albums.Sort((a, b) => a.Name.CompareTo(b.Name)); } return(new OkObjectResult(albums.ToArray())); }
private async Task _RefreshSpotifyToken() { if (_memoryCache.TryGetValue("SpotifyAccessToken", out string spotifyAccessToken)) { using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseOption = await secureClient.GetAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken"); if (!responseOption.IsSuccessStatusCode) { return; } else { string encryptedAccessToken = JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()); string newSpotifyAccessToken = EncDecUtil.Decrypt(encryptedAccessToken, Configuration.GetSection("Spotify")["Salt"]); if (newSpotifyAccessToken != spotifyAccessToken) { _memoryCache.Set("SpotifyAccessToken", newSpotifyAccessToken); return; } } } else { return; } } } string refresh_token; using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseOption = await secureClient.GetAsync($"{APIRoot.Url}/api/options/global/SpotifyRefreshToken"); if (!responseOption.IsSuccessStatusCode) { return; } else { string encryptedRefreshToken = JsonConvert.DeserializeObject <string>(await responseOption.Content.ReadAsStringAsync()); refresh_token = EncDecUtil.Decrypt(encryptedRefreshToken, Configuration.GetSection("Spotify")["Salt"]); } } else { return; } } var nvc = new List <KeyValuePair <string, string> >(); nvc.Add(new KeyValuePair <string, string>("grant_type", "refresh_token")); nvc.Add(new KeyValuePair <string, string>("refresh_token", refresh_token)); var formContent = new FormUrlEncodedContent(nvc); var request = new HttpRequestMessage(HttpMethod.Post, "https://accounts.spotify.com/api/token"); request.Content = formContent; string authValue = Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{Configuration.GetSection("Spotify")["client_id"]}:{Configuration.GetSection("Spotify")["client_secret"]}")); request.Headers.Add("Authorization", $"Basic {authValue}"); var response = await _httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); var parsed = JObject.Parse(json); string access_token = parsed.SelectToken("access_token").Value <string>(); string encryptedAccessToken = EncDecUtil.Encrypt(access_token, Configuration.GetSection("Spotify")["Salt"]); using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseSaveOption = await secureClient.PutAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken", new StringContent(JsonConvert.SerializeObject(encryptedAccessToken), Encoding.UTF8, "application/json")); if (!responseSaveOption.IsSuccessStatusCode) { return; } _memoryCache.Set("SpotifyAccessToken", access_token); } } } }
public async Task <ActionResult> OnPostAsync(string code) { if (string.IsNullOrEmpty(Request.Cookies["Token"])) { return(Redirect("/")); } var nvc = new List <KeyValuePair <string, string> >(); nvc.Add(new KeyValuePair <string, string>("grant_type", "authorization_code")); nvc.Add(new KeyValuePair <string, string>("code", code)); string callbackUrl = $"{Configuration["SiteUrl"]}/Admin/SpotifyCallback"; nvc.Add(new KeyValuePair <string, string>("redirect_uri", callbackUrl)); var formContent = new FormUrlEncodedContent(nvc); var client = _clientFactory.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://accounts.spotify.com/api/token"); request.Content = formContent; string authValue = Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{Configuration.GetSection("Spotify")["client_id"]}:{Configuration.GetSection("Spotify")["client_secret"]}")); request.Headers.Add("Authorization", $"Basic {authValue}"); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); var parsed = JObject.Parse(json); access_token = parsed.SelectToken("access_token").Value <string>(); refresh_token = parsed.SelectToken("refresh_token").Value <string>(); token_type = parsed.SelectToken("token_type").Value <string>(); expires_in = parsed.SelectToken("expires_in").Value <string>(); string encryptedAccessToken = EncDecUtil.Encrypt(access_token, Configuration.GetSection("Spotify")["Salt"]); string encryptedRefreshToken = EncDecUtil.Encrypt(refresh_token, Configuration.GetSection("Spotify")["Salt"]); using (HttpClient secureClient = new HttpClient()) { if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response)) { var responseSaveOption = await secureClient.PutAsync($"{APIRoot.Url}/api/options/global/SpotifyAccessToken", new StringContent(JsonConvert.SerializeObject(encryptedAccessToken), Encoding.UTF8, "application/json")); if (!responseSaveOption.IsSuccessStatusCode) { Error = JsonConvert.DeserializeObject <string>(await responseSaveOption.Content.ReadAsStringAsync()); } else { responseSaveOption = await secureClient.PutAsync($"{APIRoot.Url}/api/options/global/SpotifyRefreshToken", new StringContent(JsonConvert.SerializeObject(encryptedRefreshToken), Encoding.UTF8, "application/json")); if (!responseSaveOption.IsSuccessStatusCode) { Error = JsonConvert.DeserializeObject <string>(await responseSaveOption.Content.ReadAsStringAsync()); } } } else { Error = "لطفا از گنجور خارج و مجددا به آن وارد شوید."; } } } else { Error = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync()); } return(new OkResult()); }
/// <summary> /// SSO数据推送 /// </summary> /// <param name="planId">planId</param> /// <param name="version">推送版本,金蝴蝶:1000, 严林版:3100, 金牡丹:5100, 渤商版:6100, 所有版本:0</param> public void SsoPush(int planId, string version) { if (string.IsNullOrEmpty(version)) { version = "0"; } try { PopupMsgPlanBLL opupMsgPlanBll = Factory.BusinessFactory.CreateBll <PopupMsgPlanBLL>(); PopupMsgPlan popupMsgPlan = opupMsgPlanBll.Get("PlanId", planId); List <string> listUserName = new List <string>(); if (popupMsgPlan != null) { int ssoResultId = 0; List <CustomerGroup> allUserName = new List <CustomerGroup>(); //判断是否用户组 if (popupMsgPlan.ReceiverType == 0 || popupMsgPlan.ReceiverType == 2) { allUserName = GetUserName(popupMsgPlan.Receiver, version); string versionLog = version == "0" ? "所有" : (version == "1000" ? "金蝴蝶" : (version == "3100" ? "严林版" : (version == "5100" ? "金牡丹" : (version == "6100" ? "渤商版" : "其它")))); Loger.Info("\r\n=====推送类型: " + popupMsgPlan.DataType + "\r\n=====推送用户组: " + popupMsgPlan.Receiver + "\r\n=====推送版本: " + versionLog + "\r\n=====推送平台: " + popupMsgPlan.PushPlatform + "\r\n=====planId: " + planId); if (allUserName != null) { listUserName = GetUserNameToGroup(allUserName); } else { Loger.Info("PlanId:" + planId + ", 此用户组, 不存在用户!"); return; } } else if (popupMsgPlan.ReceiverType == 1) { allUserName = AddUserName(popupMsgPlan.Receiver); listUserName.Add(popupMsgPlan.Receiver); } //更新计划接收用户数 popupMsgPlan.ReceiverCount = allUserName.Count; opupMsgPlanBll.Update(popupMsgPlan); if (popupMsgPlan.DataType == "资讯弹窗") { //包括移动终端推送 if (popupMsgPlan.PushPlatform.IndexOf("android") >= 0 || popupMsgPlan.PushPlatform.IndexOf("ios") >= 0) { Thread thOracle = new Thread(new ThreadStart(delegate() { UpDataMoveData(popupMsgPlan, allUserName); })); thOracle.Start(); } //不包括PC终端, 返回 if (popupMsgPlan.PushPlatform.IndexOf("pc") < 0) { return; } if (popupMsgPlan.ReceiverType == 0 || popupMsgPlan.ReceiverType == 2) //用户组 { Thread th = new Thread(new ThreadStart(delegate() { NewsPopupUserUpdataIn(popupMsgPlan, allUserName, version); })); th.Start(); } else if (popupMsgPlan.ReceiverType == 1) //用户(手动输入) { Thread th = new Thread(new ThreadStart(delegate() { NewsPopupUserUpdata(popupMsgPlan, allUserName); })); th.Start(); } } ; //return; string parameter = string.Empty; List <SsoRes> listSsoRes = new List <SsoRes>(); if (listUserName.Count > 0) { Loger.Info(" [SSO][开始] SSO推送中..."); } else { return; } DateTime srb = DateTime.Now; foreach (var userName in listUserName) { parameter = GetAddOutWindowParameter(popupMsgPlan, userName); string res = RequestHelper.WebRequest(AddOutWindow, "post", parameter, "UTF-8", true); if (!string.IsNullOrEmpty(res)) { res = new EncDecUtil().decyptData(res, accesskey); SsoRes ssoRes = JsonHelper.DeserializeJson <SsoRes>(res); listSsoRes.Add(ssoRes); // 调用接口状态码,0:成功,1:该消息id 已存在,2:链接地址不存在,3:用户群组不存在,4:开始时间与结束时间不匹配,9:其它异常 if (ssoRes.error != 0)//失败部分单独更新 { Loger.Info("SSO接口调用返回失败, 此批用户入库<失败用户>"); Loger.Info("PlanId:" + planId + ",SSO数据推送返回结果:" + res); ssoResultId = UpDataSsoResult(popupMsgPlan, userName, ssoRes, ssoResultId); } //Loger.Info("PlanId:" + planId + ",SSO数据推送返回结果: ssoRes = " + ssoRes.error); } else { Loger.Info("SSO接口调用返回空=====error=====(一般情况不会出现, 出现在超时或者无法调用)"); } } Loger.Info(" [SSO][结束] SSO推送完毕, 用时: " + (int)(DateTime.Now - srb).TotalSeconds + " 秒"); UpDataSsoResult(popupMsgPlan, listSsoRes, ssoResultId); //if (popupMsgPlan.DataType == "广告弹窗") // ReceiveMsgPush(popupMsgPlan, allUserName); //else //if (popupMsgPlan.DataType == "资讯弹窗") //{ // //InformationOfUserPush(popupMsgPlan, allUserName); // NewsPopupUserUpdata(popupMsgPlan, allUserName); //} } } catch (Exception ex) { Loger.Error(ex, "\r\n=====error=====\r\nPlanId:" + planId + ",SSO数据推送异常:"); } }