public async Task <CallBackResponse> GetDocumentInfo(string accountId, string documentId) { CallBackResponse callBackResponse = new CallBackResponse(); HttpCustomClient client; string stringResponse = string.Empty; try { client = new HttpCustomClient(); stringResponse = await client.Get(documentId, Constants.Constants.mhActionRecepcion); if (!string.IsNullOrEmpty(stringResponse)) { callBackResponse = JsonConvert.DeserializeObject <CallBackResponse>(stringResponse); } else { throw new Exception(Constants.Constants.fail_get_document_from_hacienda); } } catch (Exception ex) { ex.Message.ToString(); throw ex; } return(callBackResponse); }
public IHttpActionResult DocumentCallBack([FromBody] CallBackResponse request) { IRequestRecordLog requestRecordLog = new RequestRecordLog(); actionDocument = new Document(); try { RequestRecord record = new RequestRecord() { clave = request.clave, docDatetime = DateTime.Parse(request.fecha), indState = request.indEstado, responseXML = request.respuestaXml, callBacakDatetime = DateTime.Now }; requestRecordLog.UpdateRequestRecord(record); //actionDocument.StoreCallBackResponse(request); } catch (Exception ex) { ex.Message.ToString(); LogManager.RegisterCallBackFailToDataBase(JsonConvert.SerializeObject(request)); } return(Ok()); }
public async Task <bool> SendCallBackResponse(SalesCatalogueProductResponse salesCatalogueProductResponse, SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage) { if (!string.IsNullOrWhiteSpace(scsResponseQueueMessage.CallbackUri)) { try { ExchangeSetResponse exchangeSetResponse = SetExchangeSetResponse(salesCatalogueProductResponse, scsResponseQueueMessage); CallBackResponse callBackResponse = SetCallBackResponse(exchangeSetResponse); callBackResponse.Subject = essCallBackConfiguration.Value.Subject; if (ValidateCallbackRequestPayload(callBackResponse)) { string payloadJson = JsonConvert.SerializeObject(callBackResponse); return(await SendResponseToCallBackApi(false, payloadJson, scsResponseQueueMessage)); } else { logger.LogError(EventIds.ExchangeSetCreatedPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} as payload data is incorrect.", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId); return(false); } } catch (Exception ex) { logger.LogError(EventIds.ExchangeSetCreatedPostCallbackUriNotCalled.ToEventId(), ex, "Post Callback uri is not called after exchange set is created for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} and Exception:{Message}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId, ex.Message); return(false); } } else { logger.LogInformation(EventIds.ExchangeSetCreatedPostCallbackUriNotProvided.ToEventId(), "Post callback uri was not provided by requestor for successful exchange set creation for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId); return(false); } }
public void StoreCallBackResponse(CallBackResponse callBack) { try { using (DigitalInvoiceEntities context = new DigitalInvoiceEntities()) { context.CallBackReceived.Add(new CallBackReceived() { IdCallBack = Guid.NewGuid().ToString(), clave = callBack.clave, fecha = callBack.fecha, indEstado = callBack.indEstado, respuestaXml = callBack.respuestaXml, callBackUrl = callBack.callbackUrl, fechaCallBack = DateTime.Now }); context.SaveChanges(); } } catch (Exception ex) { ex.Message.ToString(); } }
/** * リクエストを送信し、レスポンスを受信する * * @param url URL * @param pCallBack コールバック */ public IEnumerator Fetch( string url, CallBackResponse pCallBack ) { WWW www = new WWW( url ); // レスポンスが返ってくるまで待つ while ( ! www.isDone ){ yield return www; } HttpResponseInfo info = new HttpResponseInfo(); MatchCollection mc = Regex.Matches( www.responseHeaders[ "STATUS" ], "[0-9]{3}" ); info.code = ( 0 == mc.Count ) ? 0 : Convert.ToInt32( mc[ 0 ].Value ); info.str = String.IsNullOrEmpty( www.error ) ? www.text : www.error; info.www = www; pCallBack( info ); }
public async Task <bool> SendCallBackErrorResponse(SalesCatalogueProductResponse salesCatalogueProductResponse, SalesCatalogueServiceResponseQueueMessage scsResponseQueueMessage) { salesCatalogueProductResponse.ProductCounts.ReturnedProductCount = 0; salesCatalogueProductResponse.ProductCounts.RequestedProductsNotReturned = new List <RequestedProductsNotReturned> { new RequestedProductsNotReturned { ProductName = null, Reason = essCallBackConfiguration.Value.Reason } }; if (!string.IsNullOrWhiteSpace(scsResponseQueueMessage.CallbackUri)) { try { ExchangeSetResponse exchangeSetResponse = SetExchangeSetResponse(salesCatalogueProductResponse, scsResponseQueueMessage); exchangeSetResponse.Links.ExchangeSetFileUri = null; exchangeSetResponse.Links.ExchangeSetErrorFileUri = new LinkSetErrorFileUri { Href = $"{fileShareServiceConfig.Value.PublicBaseUrl}/batch/{scsResponseQueueMessage.BatchId}/files/{fileShareServiceConfig.Value.ErrorFileName}" }; CallBackResponse callBackResponse = SetCallBackResponse(exchangeSetResponse); callBackResponse.Subject = essCallBackConfiguration.Value.ErrorSubject; if (ValidateCallbackErrorRequestPayload(callBackResponse)) { string payloadJson = JsonConvert.SerializeObject(callBackResponse); return(await SendResponseToCallBackApi(true, payloadJson, scsResponseQueueMessage)); } else { logger.LogError(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} as payload data is incorrect.", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId); return(false); } } catch (Exception ex) { logger.LogError(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotCalled.ToEventId(), "Post Callback uri is not called after exchange set is created with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId} and Exception:{Message}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId, ex.Message); return(false); } } else { logger.LogInformation(EventIds.ExchangeSetCreatedWithErrorPostCallbackUriNotProvided.ToEventId(), "Post callback uri was not provided by requestor for exchange set creation with error for BatchId:{BatchId} and _X-Correlation-ID:{CorrelationId}", scsResponseQueueMessage.BatchId, scsResponseQueueMessage.CorrelationId); return(false); } }
/** * リクエストを送信し、レスポンスを受信する * * @param url URL * @param pCallBack コールバック */ public IEnumerator Fetch(string url, CallBackResponse pCallBack) { WWW www = new WWW(url); // レスポンスが返ってくるまで待つ while (!www.isDone) { yield return(www); } HttpResponseInfo info = new HttpResponseInfo(); MatchCollection mc = Regex.Matches(www.responseHeaders["STATUS"], "[0-9]{3}"); info.code = (0 == mc.Count) ? 0 : Convert.ToInt32(mc[0].Value); info.str = String.IsNullOrEmpty(www.error) ? www.text : www.error; info.www = www; pCallBack(info); }
public void LoginWithAccessToken(ETypeSocial social) { CallBackResponse callBack = null; WWWForm form = new WWWForm(); form.AddField(ServerWeb.PARAM_TYPE, social.ToString()); form.AddField(ServerWeb.PARAMS_ACCESS_TOKEN, (social == ETypeSocial.facebook ? FB.AccessToken : social == ETypeSocial.google ? Google.instance.accessToken : social == ETypeSocial.twitter ? "" : "")); form.AddField(ServerWeb.PARAMS_APP_ID, Convert.ToString(GameManager.GAME)); switch (social) { case ETypeSocial.facebook: callBack = ProressAfterLoginFacebook; break; case ETypeSocial.google: callBack = ProressAfterLoginGoogle; break; } form.AddField(ServerWeb.PARAM_PARTNER_ID, GameSettings.Instance.ParnerCodeIdentifier); ServerWeb.StartThread(ServerWeb.URL_GET_ACCESS_TOKEN, form, callBack); }
public AsyncTcpClient(String stringIpAddr, int port, CallBackResponse mainReceiveCallBack) { // Connect to a remote device. try { //Store the callback function _receiveCallBack = mainReceiveCallBack; // Establish the remote endpoint for the socket. IPAddress ipAddress = IPAddress.Parse(stringIpAddr); _remoteEp = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/** * リクエストの送信 * * @param requestType リクエストタイプ * @param apiUrl APIのURL * @param paramMap パラメーターマップ * @param pCallBack コールバック */ public void SendRequest( RequestType requestType, string apiUrl, Hashtable paramMap, CallBackResponse pCallBack ) { string url; url = m_RootUrl + apiUrl; string paramStr; List<string> list = new List<string>(); foreach( DictionaryEntry param in paramMap ){ list.Add( param.Key + "=" + param.Value ); } if ( 0 < list.Count ){ paramStr = string.Join( "&", list.ToArray() ); mln.Logger.MLNLOG_DEBUG( "ParamStr="+ paramStr ); if ( RequestType.GET == requestType ){ url += "?" + paramStr; } } mln.Logger.MLNLOG_DEBUG( "Type="+ requestType +" URL="+ url ); m_Coroutine = Fetch( url, pCallBack ); }
/// <summary> /// 获取图片验证码 /// </summary> /// <returns></returns> public ValidatePicOutput GetValidatePicUrl() { try { string token = Guid.NewGuid().ToString(); IList <RestResponseCookie> cookieContainer = new List <RestResponseCookie>(); #region GetJs var client_getjs = new RestClient("https://kyfw.12306.cn/otn/HttpZF/GetJS"); var request_getjs = new RestRequest(Method.GET); request_getjs.AddHeader("Referer", "https://www.12306.cn/index/"); request_getjs.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); IRestResponse response_getjs = client_getjs.Execute(request_getjs); //int startIndex = response_getjs.Content.IndexOf("logdevice"); //int endIndex = response_getjs.Content.IndexOf("x26hashCode"); //string algIDStr = response_getjs.Content.Substring(startIndex, endIndex - startIndex); //startIndex = algIDStr.IndexOf("x3d") + 3; //endIndex = algIDStr.LastIndexOf("\\"); //string algID = algIDStr.Substring(startIndex, endIndex - startIndex); #endregion #region https://kyfw.12306.cn/otn/HttpZF/logdevice var client_0 = new RestClient(WebConfig.LogDeviceUrl + (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000); var request_0 = new RestRequest(Method.GET); request_0.AddHeader("Referer", "https://www.12306.cn/index/"); request_0.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); request_0.AddParameter("BIGipServerotn", response_getjs.Cookies.Where(c => c.Name == "BIGipServerotn").FirstOrDefault().Value, ParameterType.Cookie); IRestResponse response_0 = client_0.Execute(request_0); string resJsonStr = response_0.Content.Substring(response_0.Content.IndexOf("'") + 1, response_0.Content.LastIndexOf("'") - response_0.Content.IndexOf("'") - 1); CallBackResponse callBackFunction = JsonConvert.DeserializeObject <CallBackResponse>(resJsonStr); cookieContainer.Add(new RestResponseCookie { Name = "RAIL_DEVICEID", Value = callBackFunction.Dfp }); cookieContainer.Add(new RestResponseCookie { Name = "RAIL_EXPIRATION", Value = callBackFunction.Exp }); #endregion #region https://kyfw.12306.cn/otn/resources/login.html var client_0_1 = new RestClient("https://kyfw.12306.cn/otn/resources/login.html"); var request_0_1 = new RestRequest(Method.GET); request_0_1.AddHeader("cache-control", "no-cache"); request_0_1.AddHeader("Host", "kyfw.12306.cn"); request_0_1.AddHeader("Referer", "https://kyfw.12306.cn/otn/resources/login.html"); request_0_1.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); if (cookieContainer.Count > 0) { foreach (var cookie in cookieContainer) { request_0_1.AddParameter(cookie.Name, cookie.Value, ParameterType.Cookie); } } IRestResponse response_0_1 = client_0_1.Execute(request_0_1); #endregion #region https://kyfw.12306.cn/otn/login/conf var client_1 = new RestClient("https://kyfw.12306.cn/otn/login/conf"); var request_1 = new RestRequest(Method.POST); request_1.AddHeader("cache-control", "no-cache"); request_1.AddHeader("Host", "kyfw.12306.cn"); request_1.AddHeader("Referer", "https://kyfw.12306.cn/otn/resources/login.html"); request_1.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); if (cookieContainer.Count > 0) { foreach (var cookie in cookieContainer) { if (cookie.Name != "JSESSIONID") { request_1.AddParameter(cookie.Name, cookie.Value, ParameterType.Cookie); } } } IRestResponse response_1 = client_1.Execute(request_1); //if (response_1.Cookies != null && response_1.Cookies.Count > 0) //{ // var cookie = response_1.Cookies.Where(c => c.Name == "route").FirstOrDefault(); // cookieContainer.Add(new RestResponseCookie // { // Name = cookie.Name, // Value = cookie.Value // }); //} #endregion #region https://kyfw.12306.cn/otn/index12306/getLoginBanner var client_2 = new RestClient("https://kyfw.12306.cn/otn/index12306/getLoginBanner"); var request_2 = new RestRequest(Method.GET); request_2.AddHeader("cache-control", "no-cache"); request_2.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); request_2.AddParameter("RAIL_DEVICEID", callBackFunction.Dfp, ParameterType.Cookie); request_2.AddParameter("RAIL_EXPIRATION", callBackFunction.Exp, ParameterType.Cookie); IRestResponse response_2 = client_2.Execute(request_2); #endregion cookieContainer.Add(new RestResponseCookie { Name = "route", Value = response_1.Cookies.Where(c => c.Name == "route").FirstOrDefault().Value }); cookieContainer.Add(new RestResponseCookie { Name = "JSESSIONID", Value = response_2.Cookies.Where(c => c.Name == "JSESSIONID").FirstOrDefault().Value }); cookieContainer.Add(new RestResponseCookie { Name = "BIGipServerotn", Value = response_2.Cookies.Where(c => c.Name == "BIGipServerotn").FirstOrDefault().Value }); #region https://kyfw.12306.cn/passport/web/auth/uamtk-static var client_3 = new RestClient("https://kyfw.12306.cn/passport/web/auth/uamtk-static"); var request_3 = new RestRequest(Method.POST); request_3.AddHeader("cache-control", "no-cache"); request_3.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"); if (cookieContainer.Count > 0) { foreach (var cookie in cookieContainer) { if (cookie.Name != "JSESSIONID") { request_3.AddParameter(cookie.Name, cookie.Value, ParameterType.Cookie); } } } if (response_1.Cookies != null && response_1.Cookies.Count > 0) { foreach (var cookie in response_1.Cookies) { if (cookie.Name != "JSESSIONID") { request_3.AddParameter(cookie.Name, cookie.Value, ParameterType.Cookie); } } } request_3.AddParameter("application/x-www-form-urlencoded", "appid=otn", ParameterType.RequestBody); IRestResponse response_3 = client_3.Execute(request_3); cookieContainer.Add(new RestResponseCookie { Name = "_passport_session", Value = response_3.Cookies.Where(c => c.Name == "_passport_session").FirstOrDefault().Value }); if (response_3.Cookies.Where(c => c.Name == "BIGipServerpassport").FirstOrDefault() != null) { cookieContainer.Add(new RestResponseCookie { Name = "BIGipServerpassport", Value = response_3.Cookies.Where(c => c.Name == "BIGipServerpassport").FirstOrDefault().Value }); } if (response_3.Cookies.Where(c => c.Name == "BIGipServerpool_passport").FirstOrDefault() != null) { cookieContainer.Add(new RestResponseCookie { Name = "BIGipServerpool_passport", Value = response_3.Cookies.Where(c => c.Name == "BIGipServerpool_passport").FirstOrDefault().Value }); } #endregion #region 获取验证码 https://kyfw.12306.cn/passport/captcha/captcha-image64?login_site=E&module=login&rand=sjrand var client = new RestClient("https://kyfw.12306.cn/passport/captcha/captcha-image64?login_site=E&module=login&rand=sjrand"); var request = new RestRequest(Method.GET); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); if (cookieContainer.Count > 0) { foreach (var cookie in cookieContainer) { if (cookie.Name == "JSESSIONID") { continue; } request.AddParameter(cookie.Name, cookie.Value, ParameterType.Cookie); } } IRestResponse response = client.Execute(request); cookieContainer.Add(new RestResponseCookie { Name = "_passport_ct", Value = response.Cookies.Where(c => c.Name == "_passport_ct").FirstOrDefault().Value }); #endregion CaptchaImageDto captchaImage = JsonConvert.DeserializeObject <CaptchaImageDto>(response.Content); StringBuilder sb = new StringBuilder(); sb.Append("data:image/jpg;base64,"); sb.Append(captchaImage.Image); CacheHelper.SetCache(token, cookieContainer, new TimeSpan(0, 2, 0)); return(new ValidatePicOutput { Flag = true, Token = token, ImgUrl = sb.ToString(), Msg = "success" }); } catch (Exception ex) { return(new ValidatePicOutput { Flag = false, Msg = "异常错误" }); } }
/** * リクエストの送信 * * @param requestType リクエストタイプ * @param apiUrl APIのURL * @param paramMap パラメーターマップ * @param pCallBack コールバック */ public void SendRequest(RequestType requestType, string apiUrl, Hashtable paramMap, CallBackResponse pCallBack) { string url; url = m_RootUrl + apiUrl; string paramStr; List <string> list = new List <string>(); foreach (DictionaryEntry param in paramMap) { list.Add(param.Key + "=" + param.Value); } if (0 < list.Count) { paramStr = string.Join("&", list.ToArray()); mln.Logger.MLNLOG_DEBUG("ParamStr=" + paramStr); if (RequestType.GET == requestType) { url += "?" + paramStr; } } mln.Logger.MLNLOG_DEBUG("Type=" + requestType + " URL=" + url); m_Coroutine = Fetch(url, pCallBack); }
public void setResponsClass(CallBackResponse who) { responseClass = who; }
public static void StartThread(string url, CallBackResponse function, params object[] arrayParams) { GameManager.Instance.StartCoroutine(__Thread(url, null, null, function, arrayParams)); }
/// <summary> /// Đặt tên hàm là Thread cho nó nguy hiểm thôi. Chứ nó chỉ là send mỗi cái WWW đi thôi. /// </summary> static IEnumerator __Thread(string url, WWWForm form, object[] forms, CallBackResponse function, params object[] arrayParams) { WWW www; if (forms != null && forms.Length > 0) { if (form == null) { form = new WWWForm(); } if (forms.Length % 2 != 0) { Debug.LogError("Thông tin form sai, đề nghị truyền lại thông tin cho form\n" + "Một form hợp lệ. WWWForm.AddField(string, int or string);"); yield break; } else { for (int i = 0; i < forms.Length; i += 2) { string key = (string)forms[i]; object obj = forms[i + 1]; if (obj.GetType() == typeof(int)) { form.AddField(key, Convert.ToInt32(obj)); } else if (obj.GetType() == typeof(string)) { form.AddField(key, obj.ToString()); } else { Debug.LogError("WWWForm.AddField phải là kiểu int hoặc string"); yield break; } } } } if (arrayParams != null && arrayParams.Length > 0) { Hashtable newHeader = arrayParams[0] as Hashtable; //Trên windows phone 8 cái headers nó là dùng Dictionary chứ không phải Hashtable nhé //(sau này phát triển windows phone 8 thì anh em ở lại chú ý thêm nhé) #if UNITY_WP8 Dictionary <string, string> headers = form.headers; foreach (DictionaryEntry entry in newHeader) { headers.Add(entry.Key.ToString(), entry.Value.ToString()); } #else Hashtable headers = form.headers; foreach (DictionaryEntry entry in newHeader) { headers.Add(entry.Key, entry.Value); } #endif www = (form == null) ? new WWW(url) : new WWW(url, form.data, headers); yield return(www); } else { www = (form == null) ? new WWW(url) : new WWW(url, form); yield return(www); } if (!www.isDone || !string.IsNullOrEmpty(www.error)) { Debug.LogWarning(string.Format(url + " - Fail Whale!\n{0}", www.error)); if (url.StartsWith(PROTOCOL_FIRST_REQUEST)) { url = url.Replace(PROTOCOL_FIRST_REQUEST, PROTOCOL_RETRY_REQUEST); Debug.Log("Retry request by protocal https: " + url); StartThread(url, form, function, arrayParams); } yield break; } Debug.Log("ServerPHP Response: - " + url + " - " + Utility.Convert.TimeToStringFull(System.DateTime.Now) + "\n" + www.text); if (function != null) { bool isDone = www.isDone || string.IsNullOrEmpty(www.error); IDictionary json = !www.isDone || !string.IsNullOrEmpty(www.error) ? null : (IDictionary)JSON.JsonDecode(www.text); function(isDone, www, json); } }
public bool ValidateCallbackErrorRequestPayload(CallBackResponse callBackResponse) { return(callBackResponse.Data.RequestedProductCount >= 0 && !string.IsNullOrWhiteSpace(callBackResponse.Data.Links.ExchangeSetBatchStatusUri.Href) && !string.IsNullOrWhiteSpace(callBackResponse.Data.Links.ExchangeSetBatchDetailsUri.Href) && Links.Equals(callBackResponse.Data.Links.ExchangeSetFileUri, null) && !string.IsNullOrWhiteSpace(callBackResponse.Id) && int.Equals(callBackResponse.Data.ExchangeSetCellCount, 0)); }