public RSOutgoingCommand(RSService service, IRSCommand command, ResponseHandler callback = null, int commandId = -1) { Service = service; Command = command; Callback = callback; CommandId = commandId; }
public ProgressDialog(string title, CancelButtonType cancel_button_type, int total_count, Gtk.Window parent_window) { Title = title; this.total_count = total_count; if (parent_window != null) this.TransientFor = parent_window; HasSeparator = false; BorderWidth = 6; SetDefaultSize (300, -1); message_label = new Label (String.Empty); VBox.PackStart (message_label, true, true, 12); progress_bar = new ProgressBar (); VBox.PackStart (progress_bar, true, true, 6); switch (cancel_button_type) { case CancelButtonType.Cancel: button = (Gtk.Button)AddButton (Gtk.Stock.Cancel, (int) ResponseType.Cancel); break; case CancelButtonType.Stop: button = (Gtk.Button)AddButton (Gtk.Stock.Stop, (int) ResponseType.Cancel); break; } Response += new ResponseHandler (HandleResponse); }
public ProgressDialog(string title, CancelButtonType cancel_button_type, int totalCount, Gtk.Window parent_window) { this.WidthRequest = 350; Title = title; this.totalCount = totalCount; if (parent_window != null) this.TransientFor = parent_window; this.Modal =true; HasSeparator = false; BorderWidth = 6; SetDefaultSize (300, -1); messageLabel = new Label (String.Empty); VBox.PackStart (messageLabel, true, true, 12); progressBar = new ProgressBar (); VBox.PackStart (progressBar, true, true, 6); switch (cancel_button_type) { case CancelButtonType.Cancel: button = (Gtk.Button)AddButton (Gtk.Stock.Cancel, (int) ResponseType.Cancel); break; case CancelButtonType.Stop: button = (Gtk.Button)AddButton (Gtk.Stock.Stop, (int) ResponseType.Cancel); break; } Response += new ResponseHandler (HandleResponse); ShowAll (); while (Application.EventsPending ()) Application.RunIteration (); }
public HistoricPriceEngine(FXSession session) { _mktData = new Quantum(); _completeCounter = 0; complete = false; mHandler = HistoricDataReceived; this.session = session; }
public static void Get(string url, ResponseHandler handler) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = TryResponse(request); handler(response); response.Close(); }
public void ListenNext(ResponseHandler handler, string regex, params string[] regexes) { var cmd = new DynamicCommand() { Function = handler, Regexes = regexes.Select(o => o.ToLower()).ToList(), }; cmd.Regexes.Add(regex); _next = cmd; }
public PacketListener(IPacketFilter filter = null, int timeout = 5000, ResponseHandler responseHandler = null) { Filter = filter; Packets = new ArrayList(); FinishedFlag = new AutoResetEvent(false); ResponseHandler = responseHandler; if (timeout > 0) TimeoutTimer = new Timer(s => OnTimeout(), null, timeout, -1); }
protected void WithResponse(HttpWebRequest request, ResponseHandler handler) { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (cookieContainer != null) cookieContainer.Add(response.Cookies); #if DEBUG Console.WriteLine("Response\n{0}\n----", response.Headers); #endif handler(response); } }
/// <summary> /// Creates a new instance of the <see cref="StreamParser"/> class /// </summary> /// <param name="session">A <see cref="TcpIpSession"/></param> /// <param name="responseQueue">A <see cref="ResponseQueue"/> instance to which <see cref="ResponsePDU"/> pdu's are forwarded</param> /// <param name="requestProcessor">A callback delegate for processing <see cref="RequestPDU"/> pdu's</param> public StreamParser(TcpIpSession session, ResponseHandler responseQueue,PduProcessorCallback requestProcessor) { if (session == null) { throw new ArgumentNullException("session"); } if (requestProcessor == null) { throw new ArgumentNullException("requestProcessor"); } if (responseQueue == null) { throw new ArgumentNullException("responseQueue"); } vTcpIpSession = session; vProcessorCallback = requestProcessor; vResponseHandler = responseQueue; //--Create and initialize a trace switch vTraceSwitch = new TraceSwitch("StreamParserSwitch", "Stream perser switch"); }
public static void Put(string url, string parametrs, ResponseHandler handler) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "PUT"; request.ContentLength = request.ContentLength = System.Text.Encoding.UTF8.GetBytes(parametrs).Length; WriteToStream (request.GetRequestStream(), parametrs); HttpWebResponse response = TryResponse(request); handler(response); response.Close(); }
public void IfFormatIsNotExplicitlyDefined_ResponderIsDeterminedFromAcceptHeaders() { ResponseHandler responder = new ResponseHandler(bridge, format, new MimeType("text/html", "html")); using (mocks.Record()) { SetupResult.For(bridge.IsFormatDefined).Return(false); } responder.Respond(); Assert.AreEqual("html", handlerInvoked); }
public void IfFormatIsExplicitlyDefined_RespondserWithThatFormatIsInvoked() { ResponseHandler responder = new ResponseHandler(bridge, format); using (mocks.Record()) { SetupResult.For(bridge.IsFormatDefined).Return(true); SetupResult.For(bridge.GetFormat()).Return("html"); } responder.Respond(); Assert.AreEqual("html", handlerInvoked); }
/** * Adds a command to this command sequence. */ public void AddCommand(IRSCommand command, ResponseHandler handler) { int id = -1; if (handler != null) { id = Service.NextCommandId(); ContainsResponseHandlers = true; } if (command is RSRenderCommand) { ContainsRenderCommands = true; } commands.Add(new RSOutgoingCommand(Service, command, handler, id)); }
public void IfFormat_IsDeterminedByMimeType_FirstAvailableMimeTypeIsRendered() { ResponseHandler responder = new ResponseHandler(bridge, format, new MimeType("notfound","na"), new MimeType("text/html", "html"), new MimeType("application/xml", "xml") ); using (mocks.Record()) { SetupResult.For(bridge.IsFormatDefined).Return(false); } responder.Respond(); Assert.AreEqual("html", handlerInvoked); }
public Incoming(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) : base(instance, handler, connection, adapter, response, compress, requestId) { // // Prepare the response if necessary. // if(response) { os_.writeBlob(IceInternal.Protocol.replyHdr); // // Add the request ID. // os_.writeInt(requestId); } }
public void IfFormatIsNotExplicitlyDefined_ResponderIsDeterminedFromAcceptHeaders() { ResponseHandler responder = new ResponseHandler() { ControllerBridge = bridge, Format = format, AcceptedMimes = new MimeType[] { new MimeType() { Symbol="html",MimeString="text/html"} } }; using (mocks.Record()) { SetupResult.For(bridge.IsFormatDefined).Return(false); } responder.Respond(); Assert.AreEqual("html", handlerInvoked); }
public void Invoke(ResponseHandler responseHandler) { var request = CreateRequest(); switch (ExpectedResponse) { case Response.None: LocalXBee.SendNoReply(request); break; case Response.Single: case Response.Multiple: InitFilter(request); LocalXBee.BeginSend(request, responseHandler, Filter, TimeoutValue); break; default: throw new NotImplementedException(); } }
protected internal IncomingBase(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) { instance_ = instance; responseHandler_ = handler; response_ = response; compress_ = compress; if(response_) { os_ = new BasicStream(instance, Ice.Util.currentProtocolEncoding); } current_ = new Ice.Current(); current_.id = new Ice.Identity(); current_.adapter = adapter; current_.con = connection; current_.requestId = requestId; cookie_ = null; }
protected void Page_Load(object sender, EventArgs e) { //创建支付应答对象 ResponseHandler resHandler = new ResponseHandler(Context); resHandler.Init(); resHandler.SetKey(TenPayInfo.Key, TenPayInfo.AppKey); //判断签名 if (resHandler.IsWXsignfeedback()) { //回复服务器处理成功 Response.Write("OK"); Response.Write("OK:" + resHandler.GetDebugInfo()); } else { //sha1签名失败 Response.Write("fail"); Response.Write("fail:" + resHandler.GetDebugInfo()); } Response.End(); }
public void IfFormat_IsDeterminedByMimeType_FirstAvailableMimeTypeIsRendered() { ResponseHandler responder = new ResponseHandler() { ControllerBridge = bridge, Format = format, AcceptedMimes = new MimeType[] { new MimeType() { Symbol="na",MimeString="notfound"}, new MimeType() { Symbol="html",MimeString="text/html"}, new MimeType() {Symbol="xml",MimeString="application/xml"} } }; using (mocks.Record()) { SetupResult.For(bridge.IsFormatDefined).Return(false); } responder.Respond(); Assert.AreEqual("html", handlerInvoked); }
public AboutDialog() { Version = "0.1.0"; Website = "http://code.google.com/p/newskit/"; WebsiteLabel = "http://code.google.com/p/newskit/"; License = "LGPL"; ProgramName = "Summa"; string[] authors = new string[2]; authors[0] = "Ethan Osten"; authors[1] = "Will Farrington"; Authors = authors; Comments = StringCatalog.AboutComments; IconTheme i = IconTheme.Default; Pixbuf image_window = i.LoadIcon("add", 0, IconLookupFlags.NoSvg); LogoIconName = "summa"; Icon = image_window; Response += new ResponseHandler(OnHide); }
// ============================================ // PUBLIC Constructors // ============================================ public ProgressDialog(string password) : base(MyInfo.Name + " Login", null, DialogFlags.Modal) { // Initialize Dialog Options WindowPosition = Gtk.WindowPosition.Center; // Initialize Dialog Events Response += new ResponseHandler(OnResponse); // Initialize Dialog Components AddButton(Gtk.Stock.Close, ResponseType.Close); Gtk.HBox hbox = new Gtk.HBox(false, 2); Gtk.VBox vbox = new Gtk.VBox(false, 2); VBox.PackStart(hbox, true, true, 2); hbox.PackStart(StockIcons.GetImage("Channel"), false, false, 2); hbox.PackStart(vbox, true, true, 2); // Initialize Label labelMessage = new Gtk.Label("<b>Waiting for " + MyInfo.Name + " Login...</b>"); labelMessage.UseMarkup = true; vbox.PackStart(labelMessage, false, false, 2); // Initialize ProgressBar progressBar = new Gtk.ProgressBar(); vbox.PackStart(progressBar, false, false, 2); // Initialize Timer timer = GLib.Timeout.Add(100, new GLib.TimeoutHandler(ProgressTimeout)); // Initialize UserInfo MyInfo.LoginChecked += new LoginEventHandler(OnLoginChecked); MyInfo.Login(password); this.ShowAll(); }
/// /// \param settings is directly modified by ConfigDlg when OK is /// pressed /// public ConfigDlg( PlayerSettings settings ) { _settings = settings; Response += new ResponseHandler( _OnResponse ); AddButton( "Ok", (int)ResponseType.Ok ); AddButton( "Cancel", (int)ResponseType.Cancel ); // Now for the state editing controls: VBox.Add( new Label( "Suck" ) ); _serverName = new Entry(); _serverName.ActivatesDefault = true; _serverName.Text = _settings.serverName; VBox.Add( _serverName ); _serverPort = new Entry(); _serverPort.ActivatesDefault = true; _serverPort.Text = _settings.serverPort.ToString(); VBox.Add( _serverPort ); VBox.ShowAll(); }
public SecurityController(ISecurityApplicationService SecurityApplicationService) { _securityApplicationServic = SecurityApplicationService; responseHandler = new ResponseHandler(); }
/// <summary> /// Raises the <see cref="HttpRequest.ResponseReceived"/> event. /// </summary> /// <param name="sender">The <see cref="HttpRequest"/> object that raised the event</param> /// <param name="response">The <see cref="HttpResponse"/> object that the web server returned</param> internal void OnResponseReceivedEvent(HttpRequest sender, HttpResponse response) { if (_OnReceived == null) { _OnReceived = new ResponseHandler(OnResponseReceivedEvent); } if (Program.CheckAndInvoke(_ResponseReceived, _OnReceived, sender, response)) { _ResponseReceived(this, response); } }
protected internal void handleException__(System.Exception exc, bool amd) { Debug.Assert(responseHandler_ != null); try { throw exc; } catch(Ice.RequestFailedException ex) { if(ex.id == null || ex.id.name == null || ex.id.name.Length == 0) { ex.id = current_.id; } if(ex.facet == null || ex.facet.Length == 0) { ex.facet = current_.facet; } if(ex.operation == null || ex.operation.Length == 0) { ex.operation = current_.operation; } if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. if(ex is Ice.ObjectNotExistException) { os_.writeByte(ReplyStatus.replyObjectNotExist); } else if(ex is Ice.FacetNotExistException) { os_.writeByte(ReplyStatus.replyFacetNotExist); } else if(ex is Ice.OperationNotExistException) { os_.writeByte(ReplyStatus.replyOperationNotExist); } else { Debug.Assert(false); } ex.id.write__(os_); // // For compatibility with the old FacetPath. // if(ex.facet == null || ex.facet.Length == 0) { os_.writeStringSeq(null); } else { string[] facetPath2 = { ex.facet }; os_.writeStringSeq(facetPath2); } os_.writeString(ex.operation); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(Ice.UnknownLocalException ex) { if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownLocalException); os_.writeString(ex.unknown); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(Ice.UnknownUserException ex) { if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownUserException); os_.writeString(ex.unknown); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(Ice.UnknownException ex) { if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownException); os_.writeString(ex.unknown); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(Ice.UserException ex) { if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownUserException); os_.writeString(ex.ice_id() + "\n" + ex.StackTrace); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(Ice.Exception ex) { if(ex is Ice.SystemException) { if(responseHandler_.systemException(current_.requestId, (Ice.SystemException)ex, amd)) { return; } } if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.ice_id()); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownLocalException); os_.writeString(ex.ice_id() + "\n" + ex.StackTrace); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } catch(System.Exception ex) { if(instance_.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { warning__(ex); } if(observer_ != null) { observer_.failed(ex.GetType().FullName); } if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUnknownException); os_.writeString(ex.ToString()); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } } if(observer_ != null) { observer_.detach(); observer_ = null; } responseHandler_ = null; }
void IHttpSocketAdapter.SetResponseHandler(ResponseHandler handler) { }
/// <summary> /// Get a list of accepted quotes. /// </summary> /// <param name="currency">The source currency of the quote.</param> /// <param name="address">The sending address of the quote.</param> /// <param name="privateKey">The privateKey of the sending address.</param> /// <param name="options">Request body.</param> /// <response code="200">array of Quotes.</response> /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response> /// <response code="403_SignatureMissing">X-REQUEST-SIGNATURE header is missing.</response> /// <response code="403_SignatureExpired">X-REQUEST-SIGNATURE has expired.</response> /// <response code="403_InvalidSignature">Invalid X-REQUEST-SIGNATURE.</response> /// <response code="500">Server error.</response> /// <returns></returns> public async Task <Result <List <GetQuotesResponse>, ErrorResponse> > GetQuotesAsync( ECurrency currency, string address, string privateKey, GetQuotesOptions options) { #region if (!currency.IsGluwaExchangeCurrency()) { throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}"); } IEnumerable <ValidationResult> validation = options.Validate(); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } if (string.IsNullOrWhiteSpace(address)) { throw new ArgumentNullException(nameof(address)); } #endregion var result = new Result <List <GetQuotesResponse>, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/{currency}/Addresses/{address}/Quotes"; var queryParams = new List <string>(); if (options.StartDateTime.HasValue) { queryParams.Add($"startDateTime={options.StartDateTime.Value.ToString("o")}"); } if (options.EndDateTime.HasValue) { queryParams.Add($"endDateTime={options.EndDateTime.Value.ToString("o")}"); } if (options.Status.HasValue) { queryParams.Add($"status={options.Status}"); } queryParams.Add($"offset={options.Offset}"); queryParams.Add($"limit={options.Limit}"); requestUri = $"{requestUri}?{string.Join("&", queryParams)}"; try { using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add(X_REQUEST_SIGNATURE, GluwaService.GetAddressSignature(privateKey, currency, mEnv)); using (HttpResponseMessage response = await httpClient.GetAsync(requestUri)) { if (response.IsSuccessStatusCode) { List <GetQuotesResponse> quoteResponse = await response.Content.ReadAsAsync <List <GetQuotesResponse> >(); result.IsSuccess = true; result.Data = quoteResponse; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
/// <summary> /// Create a new order. /// </summary> /// <param name="apiKey">Your apiKey.</param> /// <param name="apiSecret">Your apiSecretKey.</param> /// <param name="sendingAddressPrivateKey">The privateKey of the sending address.</param> /// <param name="receivingAddressPrivateKey">The privateKey of the receiving address.</param> /// <param name="orderRequest">Request body.</param> /// <response code="201">Newly created order.</response> /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response> /// <response code="400_MissingBody">Request body is missing.</response> /// <response code="400_InvalidBody">Request validation errors. See InnerErrors.</response> /// <response code="400_ValidationError">Request validation errors. See InnerErrors.</response> /// <response code="403_Forbidden">Not authorized to use this endpoint.</response> /// <response code="403_WebhookNotFound">Webhook URL to send exchange request is unavailable.</response> /// <response code="500">Server error.</response> /// <response code="503">Service unavailable for the specified conversion.</response> /// <returns></returns> public async Task <Result <CreateOrderResponse, ErrorResponse> > CreateOrderAsync( string apiKey, string apiSecret, string sendingAddressPrivateKey, string receivingAddressPrivateKey, CreateOrderRequest orderRequest) { #region IEnumerable <ValidationResult> validation = orderRequest.Validate(); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } if (string.IsNullOrWhiteSpace(sendingAddressPrivateKey)) { throw new ArgumentNullException(nameof(sendingAddressPrivateKey)); } else if (string.IsNullOrWhiteSpace(receivingAddressPrivateKey)) { throw new ArgumentNullException(nameof(receivingAddressPrivateKey)); } #endregion string token = getAuthToken(apiKey, apiSecret); var result = new Result <CreateOrderResponse, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/Orders"; string btcpublicKey = null; if (orderRequest.Conversion.Value.IsSourceCurrencyBtc()) { btcpublicKey = Key.Parse(sendingAddressPrivateKey, mEnv.Network).PubKey.ToString(); } PostOrderRequest bodyParams = new PostOrderRequest() { Conversion = orderRequest.Conversion.ToString(), SendingAddress = orderRequest.SendingAddress, SendingAddressSignature = GluwaService.GetAddressSignature(sendingAddressPrivateKey, orderRequest.Conversion.Value.ToSourceCurrency(), mEnv), ReceivingAddress = orderRequest.ReceivingAddress, ReceivingAddressSignature = GluwaService.GetAddressSignature(receivingAddressPrivateKey, orderRequest.Conversion.Value.ToTargetCurrency(), mEnv), SourceAmount = orderRequest.SourceAmount, Price = orderRequest.Price, BtcPublicKey = btcpublicKey }; string json = bodyParams.ToJson(); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); try { using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add(AUTHORIZATION, $"{BASIC} {token}"); using (HttpResponseMessage response = await httpClient.PostAsync(requestUri, content)) { if (response.IsSuccessStatusCode) { CreateOrderResponse orderResponse = await response.Content.ReadAsAsync <CreateOrderResponse>(); result.IsSuccess = true; result.Data = orderResponse; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
/// <summary> /// Accept an exchange request. /// <param name="apiKey">Your apiKey.</param> /// <param name="apiSecret">Your apiSecretKey.</param> /// <param name="address"/>The address that funds the source amount.</parm> /// <param name="privateKey">The privateKey of the sending address.</param> /// </summary> /// <returns></returns> public async Task <Result <bool, ErrorResponse> > AcceptExchangeRequestAsync( string apiKey, string apiSecret, string address, string privateKey, AcceptExchangeRequest exchangeRequest) { #region IEnumerable <ValidationResult> validation = exchangeRequest.Validate(); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } if (string.IsNullOrWhiteSpace(address)) { throw new ArgumentNullException(address); } else if (string.IsNullOrWhiteSpace(privateKey)) { throw new ArgumentNullException(nameof(privateKey)); } #endregion string token = getAuthToken(apiKey, apiSecret); var result = new Result <bool, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/ExchangeRequests/{exchangeRequest.ID}"; string reserveTxnSinatrue = null; string executeTxnSignature = null; string reclaimTxnSignature = null; BigInteger nonce = BigInteger.Parse(GluwaService.GetNonceString()); if (exchangeRequest.Conversion.Value.IsSourceCurrencyBtc()) { BtcTxnSignature txnSignature = await getBtcTxnSignaturesAsync( exchangeRequest.Conversion.Value.ToSourceCurrency(), address, exchangeRequest.SourceAmount, exchangeRequest.Fee, exchangeRequest.DestinationAddress, exchangeRequest.ReservedFundsAddress, exchangeRequest.ReservedFundsRedeemScript, privateKey); reserveTxnSinatrue = txnSignature.ReserveTxnSignature; executeTxnSignature = txnSignature.ExecuteTxnSignature; reclaimTxnSignature = txnSignature.ReclaimTxnSignature; } else { BigInteger convertExpiryBlockNumber = BigInteger.Parse(exchangeRequest.ExpiryBlockNumber.ToString()); reserveTxnSinatrue = getGluwacoinReserveTxnSignature( exchangeRequest.Conversion.Value.ToSourceCurrency(), address, exchangeRequest.SourceAmount, exchangeRequest.Fee, exchangeRequest.DestinationAddress, exchangeRequest.Executor, nonce, convertExpiryBlockNumber, privateKey); } PatchExchangeRequest bodyParams = new PatchExchangeRequest() { SendingAddress = address, ReserveTxnSignature = reserveTxnSinatrue, Nonce = nonce.ToString(), ExecuteTxnSignature = executeTxnSignature, ReclaimTxnSignature = reclaimTxnSignature }; string json = bodyParams.ToJson(); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpRequestMessage request = new HttpRequestMessage { Method = new HttpMethod("PATCH"), RequestUri = new Uri(requestUri), Content = content }; try { using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add(AUTHORIZATION, $"{BASIC} {token}"); using (HttpResponseMessage response = await httpClient.SendAsync(request)) { if (response.IsSuccessStatusCode) { result.IsSuccess = true; result.Data = true; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
/// <exception cref="System.IO.IOException"></exception> public virtual T Execute <T, _T1>(HttpHost httpHost, HttpWebRequest httpRequest, ResponseHandler <_T1> responseHandler, HttpContext httpContext) where _T1 : T { throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed" ); }
void ProcessData(IRemoteServer server, INetworkData networkData, ResponseHandler responseHandler) { switch (networkData.Type) { case NetworkDataType.Request: HandleRequest(networkData as RequestData, responseHandler); break; case NetworkDataType.Heartbeat: { var heartbeat = networkData as Heartbeat; // Last heartbeat time was set before. if (PlayerIndex == 0u) { PlayerIndex = heartbeat.PlayerId; } foreach (var registeredHeartbeatHandler in registeredHeartbeatHandlers.ToArray()) { registeredHeartbeatHandler?.Invoke(heartbeat); } responseHandler?.Invoke(ResponseType.Ok); break; } case NetworkDataType.LobbyData: if (serverState != ServerState.Lobby) { responseHandler?.Invoke(ResponseType.BadState); } else { responseHandler?.Invoke(ResponseType.Ok); UpdateLobbyData(networkData as LobbyData); } break; case NetworkDataType.Response: { var responseData = networkData as ResponseData; foreach (var registeredResponseHandler in registeredResponseHandlers.ToArray()) { registeredResponseHandler?.Invoke(responseData); } break; } case NetworkDataType.InSync: { if (serverState != ServerState.Game && serverState != ServerState.Loading) { responseHandler?.Invoke(ResponseType.BadState); } else { if (Game == null) { serverState = ServerState.Offline; responseHandler?.Invoke(ResponseType.BadState); return; } try { var insyncData = networkData as InSyncData; Log.Verbose.Write(ErrorSystemType.Network, $"Processing in-sync message with game time {Misc.SecondsToTime(insyncData.GameTime)}."); if (!lastSavedGameStates.ContainsKey(insyncData.GameTime)) // We don't have the saved state anymore -> need full update { Log.Verbose.Write(ErrorSystemType.Network, $"Last saved game state with game time {Misc.SecondsToTime(insyncData.GameTime)} not available. Requesting re-sync."); RequestGameStateUpdate(); return; } Log.Verbose.Write(ErrorSystemType.Network, $"Updating last synced saved state to game time {Misc.SecondsToTime(insyncData.GameTime)} and discarding outdated saved game states."); lastVerifiedSavedGameState = lastSavedGameStates[insyncData.GameTime]; // Remove all outdated (timestamp before in-sync game time) saved states. foreach (var outdatedSavedGameState in lastSavedGameStates.Where(s => s.Key <= insyncData.GameTime).ToList()) { lastSavedGameStates.Remove(outdatedSavedGameState.Key); } } catch (Exception ex) { Log.Error.Write(ErrorSystemType.Network, "Failed to update game state: " + ex.Message); Disconnect(); throw ex; // TODO: Close game instead of crash? } } break; } case NetworkDataType.SyncData: { if (serverState != ServerState.Game && serverState != ServerState.Loading) { responseHandler?.Invoke(ResponseType.BadState); } else { if (Game == null) { serverState = ServerState.Offline; responseHandler?.Invoke(ResponseType.BadState); return; } try { var syncData = networkData as SyncData; #if DEBUG var stopWatch = System.Diagnostics.Stopwatch.StartNew(); Log.Verbose.Write(ErrorSystemType.Network, "Processing sync ... "); #endif lock (Game) { lastSavedGameStates.Clear(); if (lastVerifiedSavedGameState == null) { lastVerifiedSavedGameState = SavedGameState.FromGame(Game); } lastVerifiedSavedGameState = SavedGameState.UpdateGameAndLastState(Game, lastVerifiedSavedGameState, syncData.SerializedData, syncData.Full); } #if DEBUG Log.Verbose.Write(ErrorSystemType.Network, $"Processing sync done in {stopWatch.ElapsedMilliseconds / 1000.0} seconds"); #endif } catch (Exception ex) { Log.Error.Write(ErrorSystemType.Network, "Failed to update game state: " + ex.Message); Disconnect(); throw ex; // TODO: Close game instead of crash? } } break; } default: // Should have been handled by Server_DataReceived already. break; } }
protected override string OnNotify(System.Web.HttpContext context) { var handler = new ResponseHandler(context); handler.setKey(key); if (handler.isTenpaySign()) { ///通知id string notify_id = handler.getParameter("notify_id"); //通过通知ID查询,确保通知来至财富通 //创建查询请求 RequestHandler queryReq = new RequestHandler(context); queryReq.init(); queryReq.setKey(key); queryReq.setGateUrl("https://gw.tenpay.com/gateway/verifynotifyid.xml"); queryReq.setParameter("partner", bargainor_id); queryReq.setParameter("notify_id", notify_id); //通信对象 TenpayHttpClient httpClient = new TenpayHttpClient(); httpClient.setTimeOut(5); //设置请求内容 httpClient.setReqContent(queryReq.getRequestURL()); if (httpClient.call()) { //设置结果参数 ClientResponseHandler queryRes = new ClientResponseHandler(); queryRes.setContent(httpClient.getResContent()); queryRes.setKey(key); //判断签名及结果 //只有签名正确,retcode为0,trade_state为0才是支付成功 if (queryRes.isTenpaySign() && queryRes.getParameter("retcode") == "0" && queryRes.getParameter("trade_state") == "0" && queryRes.getParameter("trade_mode") == "1") { string out_trade_no = queryRes.getParameter("out_trade_no"); //财富通订单号 string transaction_id = queryRes.getParameter("transaction_id"); //金额,以分为单位 string total_fee = queryRes.getParameter("total_fee"); PayHistory order = OnlinePayBusiness.Instance.GetOrder(out_trade_no, ThisCompanyType); if (order == null) { CoreHelper.EventLog.Log(string.Format("在线支付确认时找不到订单{0} 订单号{1}", ThisCompanyType, out_trade_no), true); //context.Response.Write("fail"); return("fail"); } order.SpBillno = transaction_id; decimal fee = Convert.ToDecimal(total_fee); lock (thisLock) { Confirm(order, GetType(), fee / 100); } //context.Response.Write("success"); return("success"); } } } //context.Response.Write("fail"); return("fail"); }
/// <summary> /// 退款通知地址 /// </summary> /// <returns></returns> public ActionResult RefundNotifyUrl() { WeixinTrace.SendCustomLog("RefundNotifyUrl被访问", "IP" + HttpContext.UserHostAddress()?.ToString()); string responseCode = "FAIL"; string responseMsg = "FAIL"; try { ResponseHandler resHandler = new ResponseHandler(null); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); WeixinTrace.SendCustomLog("跟踪RefundNotifyUrl信息", resHandler.ParseXML()); if (return_code == "SUCCESS") { responseCode = "SUCCESS"; responseMsg = "OK"; string appId = resHandler.GetParameter("appid"); string mch_id = resHandler.GetParameter("mch_id"); string nonce_str = resHandler.GetParameter("nonce_str"); string req_info = resHandler.GetParameter("req_info"); var decodeReqInfo = TenPayV3Util.DecodeRefundReqInfo(req_info, TenPayV3Info.Key); var decodeDoc = XDocument.Parse(decodeReqInfo); //获取接口中需要用到的信息 string transaction_id = decodeDoc.Root.Element("transaction_id").Value; string out_trade_no = decodeDoc.Root.Element("out_trade_no").Value; string refund_id = decodeDoc.Root.Element("refund_id").Value; string out_refund_no = decodeDoc.Root.Element("out_refund_no").Value; int total_fee = int.Parse(decodeDoc.Root.Element("total_fee").Value); int? settlement_total_fee = decodeDoc.Root.Element("settlement_total_fee") != null ? int.Parse(decodeDoc.Root.Element("settlement_total_fee").Value) : null as int?; int refund_fee = int.Parse(decodeDoc.Root.Element("refund_fee").Value); int tosettlement_refund_feetal_fee = int.Parse(decodeDoc.Root.Element("settlement_refund_fee").Value); string refund_status = decodeDoc.Root.Element("refund_status").Value; string success_time = decodeDoc.Root.Element("success_time").Value; string refund_recv_accout = decodeDoc.Root.Element("refund_recv_accout").Value; string refund_account = decodeDoc.Root.Element("refund_account").Value; string refund_request_source = decodeDoc.Root.Element("refund_request_source").Value; //进行业务处理 } } catch (Exception ex) { responseMsg = ex.Message; WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex)); } string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", responseCode, responseMsg); return(Content(xml, "text/xml")); }
/// <summary> /// JS-SDK支付回调地址(在统一下单接口中设置notify_url) /// </summary> /// <returns></returns> public ActionResult PayNotifyUrl() { try { ResponseHandler resHandler = new ResponseHandler(HttpContext); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); string res = null; resHandler.SetKey(TenPayV3Info.Key); //验证请求是否从微信发过来(安全) if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS") { res = "success";//正确的订单处理 //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息! } else { res = "wrong";//错误的订单处理 } /* 这里可以进行订单处理的逻辑 */ //发送支付成功的模板消息 try { string appId = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。 string openId = resHandler.GetParameter("openid"); var templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态:" + return_code); Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数", appId + " , " + openId); var result = AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData); } catch (Exception ex) { Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString()); } #region 记录日志 var logDir = Server.GetMapPath(string.Format("~/App_Data/TenPayNotify/{0}", DateTime.Now.ToString("yyyyMMdd"))); if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8))); using (var fileStream = System.IO.File.OpenWrite(logPath)) { var notifyXml = resHandler.ParseXML(); //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res)); fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml)); fileStream.Close(); } #endregion string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", return_code, return_msg); return(Content(xml, "text/xml")); } catch (Exception ex) { WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex)); throw; } }
/// <summary> /// Adds a method handler for a given path and verb /// </summary> /// <param name="path">The path.</param> /// <param name="verb">The verb.</param> /// <param name="handler">The handler.</param> public void AddHandler(string path, HttpVerbs verb, ResponseHandler handler) { Handlers.Add(new Map { Path = path, Verb = verb, ResponseHandler = handler }); }
/// <summary> /// 微信支付异步通知 /// </summary> /// <returns></returns> public IActionResult notify() { XTrace.WriteLine("微信支付异步通知开始:"); try { ResponseHandler resHandler = new ResponseHandler(null); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); //配置 Core.Config cfg = Core.Config.GetSystemConfig(); string appId = cfg.WXAppId; // ConfigurationManager.AppSettings["WeixinAppId"]; string appSecrect = cfg.WXAppSecret; // ConfigurationManager.AppSettings["WeixinAppSecrect"]; string wxmchId = cfg.MCHId; // ConfigurationManager.AppSettings["WeixinMCHId"]; string wxmchKey = cfg.MCHKey; // ConfigurationManager.AppSettings["WeixinMCHKey"]; TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, Utils.GetServerUrl() + "/wxpayment/notify", Utils.GetServerUrl() + "/wxpayment/notify"); string res = null; resHandler.SetKey(TenPayV3Info.Key); //验证请求是否从微信发过来(安全) if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS") { res = "success"; //正确的订单处理 //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息! string out_trade_no = resHandler.GetParameter("out_trade_no"); //商户订单号 XTrace.WriteLine("微信异步通知订单号:" + out_trade_no + ";" + JsonConvert.SerializeObject(resHandler)); OnlinePayOrder payOrder = OnlinePayOrder.Find(OnlinePayOrder._.PayOrderNum == out_trade_no); if (payOrder == null) { XTrace.WriteLine($"支付成功,但是支付订单不存在:{out_trade_no}"); res = "wrong";//错误的订单处理 } else { if (payOrder.PaymentStatus == Utils.PaymentState[0]) { //更新支付订单 payOrder.PaymentStatus = Utils.PaymentState[1]; payOrder.ReceiveTime = DateTime.Now; payOrder.IsOK = 1; payOrder.Update(); //获取订单 Order order = Order.Find(Order._.OrderNum == payOrder.OrderNum); if (order != null) { order.PaymentStatus = Utils.PaymentState[1]; order.PayType = "微信支付"; if (order.MyType == (int)Utils.MyType.分销商认证) { order.OrderStatus = Utils.OrdersState[2]; } order.Update(); //如果是属于升级会员的,那要修改会员状态 if (order.MyType == (int)Utils.MyType.分销商认证 && order.OrderType > 0) { Member he = Member.FindById(order.UId); if (he.RoleId != order.OrderType) { he.RoleId = order.OrderType; he.IsVerifySellers = 1; he.Update(); } } //写入订单记录 OrderLog log = new OrderLog(); log.AddTime = DateTime.Now; log.OrderId = order.Id; log.OrderNum = order.OrderNum; log.UId = order.UId; log.Actions = "微信支付成功;订单号:" + order.OrderNum + ";金额:" + order.TotalPay.ToString("N2"); log.Insert(); } } } } else { res = "wrong";//错误的订单处理 } #region 记录日志 XTrace.WriteLine($"微信支付回调处理结果:{res}"); #endregion string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", return_code, return_msg); return(Content(xml, "text/xml")); } catch (Exception ex) { new WeixinException(ex.Message, ex); throw; } }
/// <summary> /// JS-SDK支付回调地址(在统一下单接口中设置notify_url) /// </summary> /// <returns></returns> public ActionResult PayNotifyUrl() { try { RCLog.Info(this, "支付返回"); ResponseHandler resHandler = new ResponseHandler(HttpContext); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); string res = null; resHandler.SetKey(WeiXinConfig.Key); //验证请求是否从微信发过来(安全) if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS") { res = "success"; //正确的订单处理 //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息! string total_fee = resHandler.GetParameter("total_fee"); string out_trade_no = resHandler.GetParameter("out_trade_no"); string openid = resHandler.GetParameter("openid"); string package = resHandler.GetParameter("attach"); Menber owner = _context.Menbers.FirstOrDefault(x => x.WeChatOpenId == openid); AccountInfo accountinfo = _context.AccountInfos.FirstOrDefault(x => x.TradeNo == out_trade_no); accountinfo.BeforeMoney = owner.AccountSum; accountinfo.AfterMoney = owner.AccountSum + int.Parse(total_fee); accountinfo.OwnerId = owner.Id; accountinfo.Money = int.Parse(total_fee); accountinfo.CreateTime = DateTime.Now; accountinfo.TradeNo = out_trade_no; accountinfo.TradeName = package; owner.AccountSum = accountinfo.AfterMoney; //_context.Add(accountinfo); _context.SaveChanges(); } else { res = "wrong";//错误的订单处理 } /* 这里可以进行订单处理的逻辑 */ //发送支付成功的模板消息 string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", return_code, return_msg); RCLog.Info(this, xml); return(Content(xml, "text/xml")); } catch (Exception ex) { RCLog.Error(this, $"发生错误{ex.ToString()}"); throw; } }
public RequestHandler(string url, object requestObject, ResponseHandler <T> responseHandler) { _responseHandler = responseHandler; _url = url; _requestObject = requestObject; }
public IHttpActionResult WechatNotify() { string reqKey = TenPayV3Util.BuildRandomStr(8); LogHelper.Payment(reqKey, $"收到微信支付异步通知,准备解析结果..."); try { ResponseHandler resHandler = new ResponseHandler(null); string return_code = resHandler.GetParameter("return_code"); string return_msg = resHandler.GetParameter("return_msg"); LogHelper.Payment(reqKey, $"解析返回结果为return_code:{return_code},return_msg:{return_msg}"); LogHelper.Info($"[{reqKey}]{resHandler.ParseXML()}"); TenPayV3Info TenPayV3Info = new TenPayV3Info(appId, appSecrect, wxmchId, wxmchKey, notifyUrl, notifyUrl); resHandler.SetKey(TenPayV3Info.Key); //验证请求是否从微信发过来(安全) if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS") { //return_code是通信标识,非交易标识,交易是否成功需要查看result_code来判断 if (resHandler.GetParameter("result_code") == "SUCCESS") { string total_fee = resHandler.GetParameter("total_fee"); //订单金额 string out_trade_no = resHandler.GetParameter("out_trade_no"); //商户订单号 string transaction_id = resHandler.GetParameter("transaction_id"); //微信支付订单号 string time_end = resHandler.GetParameter("time_end"); //支付完成时间 string openid = resHandler.GetParameter("openid"); LogHelper.Payment(reqKey, $"微信支付成功,商户订单号:{out_trade_no},支付金额:{total_fee},支付流水号:{transaction_id},openid:{openid}"); //1.判断订单是否存在 2.判断订单支付状态 3.插入修改数据等 var orderEntity = _repositoryFactory.IOrders.Single(x => x.OrderCode == out_trade_no); if (orderEntity == null) { LogHelper.Payment(reqKey, $"查找订单失败,商户订单号:{out_trade_no}"); } else if (orderEntity.OrderStatus != (int)EnumHepler.OrderStatus.Created || orderEntity.PayStatus != (int)EnumHepler.OrderPayStatus.Unpay) { LogHelper.Payment(reqKey, $"订单非待支付状态,当前状态为{orderEntity.OrderStatus},商户订单号:{out_trade_no}"); } else { LogHelper.Payment(reqKey, $"更新订单支付状态为已支付待发货,商户订单号:{out_trade_no}"); DateTime payTime = DateTime.ParseExact(time_end, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault); //更新订单状态 _repositoryFactory.IOrders.ModifyBy(x => x.OrderCode == out_trade_no, new string[] { "OrderStatus", "PayStatus", "PayTime", "PayMode" }, new object[] { (int)EnumHepler.OrderStatus.WaitSendGoods, (int)EnumHepler.OrderPayStatus.Paied, payTime, (int)EnumHepler.OrderPayMode.WechatPay }); _repositoryFactory.SaveChanges(); } } else { LogHelper.Payment(reqKey, $"微信支付失败,err_code:{resHandler.GetParameter("err_code")},err_code_des:{resHandler.GetParameter("err_code_des")}"); } } string xml = string.Format(@"<xml> <return_code><![CDATA[{0}]]></return_code> <return_msg><![CDATA[{1}]]></return_msg> </xml>", return_code, return_msg); return(Content(HttpStatusCode.OK, xml, Configuration.Formatters.XmlFormatter, "text/xml")); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, ex.Message)); } }
/// <summary> /// Get Quote for currency exchange. /// </summary> /// <param name="sendingAddressPrivateKey">The privateKey of the sending address.</param> /// <param name="receivingAddressPrivateKey">The privateKey of the receiving address.</param> /// <param name="quoteRequest">Request body.</param> /// <response code="200">Newly generated quote.</response> /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response> /// <response code="400_MissingBody">Request body is missing.</response> /// <response code="400_InvalidBody">Request validation errors. See InnerErrors.</response> /// <response code="400_ValidationError">Request validation errors. See InnerErrors.</response> /// <response code="404">No matching orders available.</response> /// <response code="500">Server error.</response> /// <returns></returns> public async Task <Result <QuoteResponse, ErrorResponse> > GetPendingQuoteAsync( string sendingAddressPrivateKey, string receivingAddressPrivateKey, GetPendingQuoteRequest quoteRequest) { #region IEnumerable <ValidationResult> validation = quoteRequest.Validate(); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } if (string.IsNullOrWhiteSpace(sendingAddressPrivateKey)) { throw new ArgumentNullException(nameof(sendingAddressPrivateKey)); } else if (string.IsNullOrWhiteSpace(receivingAddressPrivateKey)) { throw new ArgumentNullException(nameof(receivingAddressPrivateKey)); } #endregion var result = new Result <QuoteResponse, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/Quote"; string btcPublicKey = null; if (quoteRequest.Conversion.Value.IsSourceCurrencyBtc()) { btcPublicKey = Key.Parse(sendingAddressPrivateKey, mEnv.Network).PubKey.ToString(); } string sendingAddressSignature = GluwaService.GetAddressSignature(sendingAddressPrivateKey, quoteRequest.Conversion.Value.ToSourceCurrency(), mEnv); string receivingAddressSignature = GluwaService.GetAddressSignature(receivingAddressPrivateKey, quoteRequest.Conversion.Value.ToTargetCurrency(), mEnv); PostQuoteRequest bodyParams = new PostQuoteRequest() { Amount = quoteRequest.Amount, Conversion = quoteRequest.Conversion, SendingAddress = quoteRequest.SendingAddress, SendingAddressSignature = sendingAddressSignature, ReceivingAddress = quoteRequest.ReceivingAddress, ReceivingAddressSignature = receivingAddressSignature, BtcPublicKey = btcPublicKey }; string json = bodyParams.ToJson(); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); try { using (HttpClient httpClient = new HttpClient()) using (HttpResponseMessage response = await httpClient.PostAsync(requestUri, content)) { if (response.IsSuccessStatusCode) { QuoteResponse quoteResponse = await response.Content.ReadAsAsync <QuoteResponse>(); result.IsSuccess = true; result.Data = quoteResponse; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
public void CreatePersonSearchDocumentTest() { //ARRANGE //set up a person var dependencyResolver = new DependencyResolverMock(); var id = Guid.NewGuid(); var client = SearchClientFactory.GetClient(); var clientFactory = SearchClientFactory.GetClientFactory(); SearchClientFactory.RegisterDependencies(dependencyResolver); //delete person index var index = new IndexName { Name = String.Format("{0}_{1}", typeof(EsPersonSearch).Name, id).ToLower(), Type = typeof(EsPersonSearch) }; var deleteIndexResult = client.DeleteIndex(index); //set up document CRUD controller and create a mock document var responseHandler = new ResponseHandler(); var indexManager = new IndexManager(dependencyResolver, clientFactory, responseHandler); var documentDispatcher = new DocumentDispatcher(clientFactory, indexManager, responseHandler); var documentclient = new DocumentController(documentDispatcher, indexManager, responseHandler); var builder = new AddPersonContextBuilder(); var personId = Guid.NewGuid(); var ev = new NewPersonAdded( new AggregateId(personId), new CQRS.CorrelationId(personId), null, 1, 1, 1, new PersonName { FirstName = "John", LastName = "Doe" }, null); var context = builder.BuildContext(ev); try { //create person document documentclient.UpsertDocument(context); Thread.Sleep(1000); var document = client.Get <EsPersonSearch>(personId, d => d.Index(index)); var personName = new PersonName { FirstName = "John1", LastName = "Doe1" }; var builder1 = new AddPossitionContexttBuilder(); var ev1 = new NewPositionAdded( new AggregateId(personId), null, new CQRS.CorrelationId(personId), personId, Guid.NewGuid(), null, 1, 1, 1, personName, "TestOrganisation"); var newPossitionAdded = builder1.BuildContext(ev1); context = builder1.BuildContext(ev1); documentclient.UpsertDocument(context); Thread.Sleep(1000); document = client.Get <EsPersonSearch>(personId, d => d.Index(index)); var builder2 = new PersonNameEditedContextBuilder(); var ev2 = new NameEdited( new AggregateId(personId), 1, new CQRS.CorrelationId(personId), null, personName, 1); context = builder2.BuildContext(ev2); documentclient.UpsertDocument(context); Thread.Sleep(1000); document = client.Get <EsPersonSearch>(personId, d => d.Index(index)); } finally { client.DeleteIndex(index); } }
/// <summary> /// Retrieve all orders. /// </summary> /// <param name="apiKey">Your apiKey.</param> /// <param name="apiSecret">Your apiSecretKey.</param> /// <param name="options">Request body.</param> /// <response code="200">List of orders.</response> /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response> /// <response code="403">Not authorized to use this endpoint.</response> /// <response code="500">Server error.</response> /// <returns></returns> public async Task <Result <List <GetOrdersResponse>, ErrorResponse> > GetOrdersAsync(string apiKey, string apiSecret, GetOrdersOptions options) { #region IEnumerable <ValidationResult> validation = options.Validate(); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } #endregion string token = getAuthToken(apiKey, apiSecret); var result = new Result <List <GetOrdersResponse>, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/Orders"; var queryParams = new List <string>(); if (options.StartDateTime.HasValue) { queryParams.Add($"startDateTime={options.StartDateTime.Value.ToString("o")}"); } if (options.EndDateTime.HasValue) { queryParams.Add($"endDateTime={options.EndDateTime.Value.ToString("o")}"); } if (options.Status.HasValue) { queryParams.Add($"status={options.Status}"); } queryParams.Add($"offset={options.Offset}"); queryParams.Add($"limit={options.Limit}"); requestUri = $"{requestUri}?{string.Join("&", queryParams)}"; try { using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add(AUTHORIZATION, $"{BASIC} {token}"); using (HttpResponseMessage response = await httpClient.GetAsync(requestUri)) { if (response.IsSuccessStatusCode) { List <GetOrdersResponse> orderResponse = await response.Content.ReadAsAsync <List <GetOrdersResponse> >(); result.IsSuccess = true; result.Data = orderResponse; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
// // These functions allow this object to be reused, rather than reallocated. // public virtual void reset(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) { instance_ = instance; // // Don't recycle the Current object, because servants may keep a reference to it. // current_ = new Ice.Current(); current_.id = new Ice.Identity(); current_.adapter = adapter; current_.con = connection; current_.requestId = requestId; Debug.Assert(cookie_ == null); response_ = response; compress_ = compress; if(response_ && os_ == null) { os_ = new Ice.OutputStream(instance, Ice.Util.currentProtocolEncoding); } responseHandler_ = handler; interceptorAsyncCallbackList_ = null; }
/// <summary> /// Accept quote received from POST /v1/Quote endpoint. /// </summary> /// <param name="currency">The source currency of the quote.</param> /// <param name="address">The sending address of the quote.</param> /// <param name="privateKey">The privateKey of the sending address.</param> /// <param name="quoteRequest">Request body.</param> /// <response code="202">Quote is accepted.</response> /// <response code="400_InvalidUrlParameters">Invalid URL parameters.</response> /// <response code="400_MissingBody">Request body is missing.</response> /// <response code="400_InvalidBody">Request validation errors. See InnerErrors.</response> /// <response code="400_ValidationError">Request validation errors. See InnerErrors.</response> /// <response code="403">Invalid checksum. Checksum may be wrong or expired.</response> /// <response code="404">One of the matched orders are no longer available.</response> /// <response code="500">Server error.</response> /// <returns></returns> public async Task <Result <AcceptQuoteResponse, ErrorResponse> > AcceptQuoteAsync( ECurrency currency, string address, string privateKey, AcceptQuoteRequest quoteRequest) { #region if (!currency.IsGluwaExchangeCurrency()) { throw new ArgumentOutOfRangeException($"Unsupported currency: {currency}"); } foreach (var order in quoteRequest.MatchedOrders) { IEnumerable <ValidationResult> validation = quoteRequest.Validate(currency); if (validation.Any()) { foreach (var item in validation) { throw new ArgumentNullException(item.ErrorMessage); } } } if (string.IsNullOrWhiteSpace(address)) { throw new ArgumentNullException(nameof(address)); } else if (string.IsNullOrWhiteSpace(privateKey)) { throw new ArgumentNullException(nameof(privateKey)); } #endregion var result = new Result <AcceptQuoteResponse, ErrorResponse>(); string requestUri = $"{mEnv.BaseUrl}/v1/Quote"; List <MatchedOrderRequest> matchedOrders = new List <MatchedOrderRequest>(); foreach (var matchedOrder in quoteRequest.MatchedOrders) { if (currency.IsGluwaCoinCurrency()) { BigInteger nonce = BigInteger.Parse(GluwaService.GetNonceString()); BigInteger convertExpiryBlockNumber = BigInteger.Parse(matchedOrder.ExpiryBlockNumber); string signature = getGluwacoinReserveTxnSignature( currency, address, matchedOrder.SourceAmount, matchedOrder.Fee, matchedOrder.DestinationAddress, matchedOrder.Executor, nonce, convertExpiryBlockNumber, privateKey); MatchedOrderRequest matchedOrderRequest = new MatchedOrderRequest() { OrderID = matchedOrder.OrderID, ReserveTxnSignature = signature, Nonce = nonce.ToString() }; matchedOrders.Add(matchedOrderRequest); } else { BtcTxnSignature txnSignature = await getBtcTxnSignaturesAsync( currency, address, matchedOrder.SourceAmount, matchedOrder.Fee, matchedOrder.DestinationAddress, matchedOrder.ReservedFundsAddress, matchedOrder.ReservedFundsRedeemScript, privateKey); MatchedOrderRequest matchedOrderRequest = new MatchedOrderRequest() { OrderID = matchedOrder.OrderID, ReserveTxnSignature = txnSignature.ReserveTxnSignature, ExecuteTxnSignature = txnSignature.ExecuteTxnSignature, ReclaimTxnSignature = txnSignature.ReclaimTxnSignature }; matchedOrders.Add(matchedOrderRequest); } } PutQuoteRequest bodyParams = new PutQuoteRequest() { MatchedOrders = matchedOrders, Checksum = quoteRequest.Checksum }; string json = bodyParams.ToJson(); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); try { using (HttpClient httpClient = new HttpClient()) using (HttpResponseMessage response = await httpClient.PutAsync(requestUri, content)) { if (response.IsSuccessStatusCode) { AcceptQuoteResponse quoteResponse = await response.Content.ReadAsAsync <AcceptQuoteResponse>(); result.IsSuccess = true; result.Data = quoteResponse; return(result); } string contentString = await response.Content.ReadAsStringAsync(); result.Error = ResponseHandler.GetError(response.StatusCode, requestUri, contentString); } } catch (HttpRequestException) { result.IsSuccess = false; result.Error = ResponseHandler.GetExceptionError(); } return(result); }
private void HandleRequest(RequestData request, ResponseHandler responseHandler) { switch (request.Request) { case Request.Disconnect: // server closed or kicked player HandleDisconnect(); break; case Request.Heartbeat: // Response is send below. break; case Request.StartGame: if (Game != null) { responseHandler?.Invoke(ResponseType.BadState); return; } serverState = ServerState.Loading; if (PlayerIndex == 0u) { // We have to wait for first heartbeat to set the player index. SendHeartbeatRequest(response => { GameStarted?.Invoke(this, EventArgs.Empty); SendStartGameRequest(); }); } else { GameStarted?.Invoke(this, EventArgs.Empty); SendStartGameRequest(); } return; case Request.AllowUserInput: if (serverState == ServerState.Loading) { serverState = ServerState.Game; } InputAllowed?.Invoke(this, EventArgs.Empty); break; case Request.DisallowUserInput: InputDisallowed?.Invoke(this, EventArgs.Empty); break; case Request.Pause: GamePaused?.Invoke(this, EventArgs.Empty); break; case Request.Resume: GameResumed?.Invoke(this, EventArgs.Empty); break; default: // all other requests can not be send to a client throw new ExceptionFreeserf(ErrorSystemType.Network, $"Request {request} can not be send to a client."); } RespondToRequest(request); }
public async Task GeneratesCorrectDataPoint(HttpResponseOption option) { // Arrange var responseHandler = new ResponseHandler(); responseHandler.AddAction( new Uri("http://ping.server"), () => option == HttpResponseOption.Success ? JsonConvert.SerializeObject( new RemotePingServerResponse { Latency = 100, StatusCode = 200, IsError = false } ) : JsonConvert.SerializeObject( new RemotePingServerResponse { StatusCode = 503, IsError = true, Error = "Some error" } ) ); var mockHttpFactory = new Mock <IHttpClientFactory>(); mockHttpFactory .Setup(factory => factory.BuildClient()) .Returns(new HttpClient(responseHandler)); var metricServiceMock = new Mock <IMetricService>(); metricServiceMock .Setup(mock => mock.GetOrCreateMetricAsync(Metrics.Ping, "https://my.url.com")) .ReturnsAsync(new Metric()); var config = new Mock <IConfiguration>(); config .SetupGet(conf => conf["Data:PingServerUrl"]) .Returns("http://ping.server"); var pingService = new RemotePingService( metricServiceMock.Object, new Mock <ILogger <PingService> >().Object, config.Object, mockHttpFactory.Object ); // Act var dataPoint = await pingService.PingServerAsync( new PingSetting { ServerUrl = "https://my.url.com", MaxResponseTime = new TimeSpan(0, 0, 0, 0, 500) } ); // Assert switch (option) { case HttpResponseOption.Success: Assert.True(dataPoint.Success); Assert.Equal(dataPoint.ResponseTime, new TimeSpan(0, 0, 0, 0, 100)); Assert.Equal("OK", dataPoint.Message); break; case HttpResponseOption.ServiceUnavailable: Assert.False(dataPoint.Success); Assert.Equal(dataPoint.ResponseTime, new TimeSpan(0)); Assert.Equal("Some error", dataPoint.Message); break; } // Clean up responseHandler.RemoveAction( new Uri("http://ping.server") ); }
private void Awake() { responseHandler = GetComponent <ResponseHandler>(); printing = GetComponent <Printing>(); CloseDialogue(); }
public JournalTableWrapperPage(Journal journal, ResponseHandler ResponseEvent, PageEnabledHandler PageEnabledEvent, LoadingStateHandler LoadingStateEvent, CompleteStateHanlder CompleteStateEvent) { InitializeComponent(); Journal = journal; DataContext = new JournalTableWrapperPageVM(journal, ResponseEvent, PageEnabledEvent, LoadingStateEvent, CompleteStateEvent); }
public override void GetByKey(object key, ResponseHandler callback) { GetByKeys(new object[] { key }, callback); }
// // These functions allow this object to be reused, rather than reallocated. // public override void reset(Instance instance, ResponseHandler handler, Ice.ConnectionI connection, Ice.ObjectAdapter adapter, bool response, byte compress, int requestId) { _cb = null; _inParamPos = -1; base.reset(instance, handler, connection, adapter, response, compress, requestId); // // Prepare the response if necessary. // if(response) { os_.writeBlob(IceInternal.Protocol.replyHdr); // // Add the request ID. // os_.writeInt(requestId); } }
public ActionResult PayNotifyUrl() { ResponseHandler resHandler = new ResponseHandler(null); resHandler.Init(); resHandler.SetKey(TenPayInfo.Key, TenPayInfo.AppKey); string message; //判断签名 if (resHandler.IsTenpaySign()) { if (resHandler.IsWXsign()) { //商户在收到后台通知后根据通知ID向财付通发起验证确认,采用后台系统调用交互模式 string notify_id = resHandler.GetParameter("notify_id"); //取结果参数做业务处理 string out_trade_no = resHandler.GetParameter("out_trade_no"); //财付通订单号 string transaction_id = resHandler.GetParameter("transaction_id"); //金额,以分为单位 string total_fee = resHandler.GetParameter("total_fee"); //如果有使用折扣券,discount有值,total_fee+discount=原请求的total_fee string discount = resHandler.GetParameter("discount"); //支付结果 string trade_state = resHandler.GetParameter("trade_state"); string payMessage = null; //即时到账 if ("0".Equals(trade_state)) { //------------------------------ //处理业务开始 //------------------------------ //处理数据库逻辑 //注意交易单不要重复处理 //注意判断返回金额 //------------------------------ //处理业务完毕 //------------------------------ //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知 payMessage = "success 后台通知成功"; } else { payMessage = "支付失败"; } ViewData["payMessage"] = payMessage; //回复服务器处理成功 message = "success"; } else {//SHA1签名失败 message = "SHA1签名失败" + resHandler.GetDebugInfo(); } } else {//md5签名失败 message = "md5签名失败" + resHandler.GetDebugInfo(); } ViewData["message"] = message; return(Content("Success")); }
internal void adopt(IncomingBase inc) { instance_ = inc.instance_; //inc.instance_ = null; // Don't reset instance_. observer_ = inc.observer_; inc.observer_ = null; servant_ = inc.servant_; inc.servant_ = null; locator_ = inc.locator_; inc.locator_ = null; cookie_ = inc.cookie_; inc.cookie_ = null; response_ = inc.response_; inc.response_ = false; compress_ = inc.compress_; inc.compress_ = 0; // // Adopt the stream - it creates less garbage. // os_ = inc.os_; inc.os_ = null; responseHandler_ = inc.responseHandler_; inc.responseHandler_ = null; }
/// <exception cref="System.IO.IOException"></exception> public virtual T Execute <T, _T1>(HttpRequestMessage httpUriRequest, ResponseHandler <_T1> responseHandler) where _T1 : T { throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed" ); }
protected bool servantLocatorFinished__(bool amd) { Debug.Assert(locator_ != null && servant_ != null); try { locator_.finished(current_, servant_, cookie_); return true; } catch(Ice.UserException ex) { Debug.Assert(responseHandler_ != null); if(observer_ != null) { observer_.userException(); } // // The operation may have already marshaled a reply; we must overwrite that reply. // if(response_) { os_.resize(Protocol.headerSize + 4); // Reply status position. os_.writeByte(ReplyStatus.replyUserException); os_.startEncapsulation(current_.encoding, Ice.FormatType.DefaultFormat); os_.writeException(ex); os_.endEncapsulation(); if(observer_ != null) { observer_.reply(os_.size() - Protocol.headerSize - 4); } responseHandler_.sendResponse(current_.requestId, os_, compress_, amd); } else { responseHandler_.sendNoResponse(); } if(observer_ != null) { observer_.detach(); observer_ = null; } responseHandler_ = null; } catch(System.Exception ex) { handleException__(ex, amd); } return false; }
protected void Page_Load(object sender, EventArgs e) { //int wid = MyCommFun.RequestWid(); int wid = 0; BLL.wx_logs logBll = new BLL.wx_logs(); logBll.AddLog("【微支付】微信预定", "notify_url Page_Load", "从微支付返回到notify_url.aspx页面", 1); BLL.wx_payment_wxpay payBll = new BLL.wx_payment_wxpay(); ResponseHandler resHandler = new ResponseHandler(Context); resHandler.init(); //取wid string attach = resHandler.getParameter("attach"); string[] attachArr = attach.Split('|'); wid = MyCommFun.Str2Int(attachArr[0]); int otid = MyCommFun.Str2Int(attachArr[1]); Model.wx_payment_wxpay paymentInfo = payBll.GetModelByWid(wid); logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "取到wid=" + wid, 1); resHandler.setKey(paymentInfo.partnerKey, paymentInfo.paySignKey);// TenpayUtil.key, TenpayUtil.appkey); //resHandler.setKey("huyuxianghuyuxianghuyuxiang12345", "nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp"); //判断签名 if (resHandler.isTenpaySign()) { logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "resHandler.isTenpaySign()", 1); if (resHandler.isWXsign()) { //商户在收到后台通知后根据通知ID向财付通发起验证确认,采用后台系统调用交互模式 string notify_id = resHandler.getParameter("notify_id"); //取结果参数做业务处理 string out_trade_no = resHandler.getParameter("out_trade_no"); //财付通订单号 string transaction_id = resHandler.getParameter("transaction_id"); //金额,以分为单位 string total_fee = resHandler.getParameter("total_fee"); //如果有使用折扣券,discount有值,total_fee+discount=原请求的total_fee string discount = resHandler.getParameter("discount"); //支付结果 string trade_state = resHandler.getParameter("trade_state"); string pay_info = resHandler.getParameter("pay_info"); logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "notify_id=" + notify_id + " out_trade_no=" + out_trade_no + " transaction_id=" + transaction_id + " total_fee=" + total_fee + " trade_state=" + trade_state + " orderid=" + otid + " wid=" + wid + " pay_info=" + pay_info, 1); //即时到账,支付成功 if ("0".Equals(trade_state)) { logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "支付成功了", 1); //------------------------------ //处理业务开始 //------------------------------ wxOrderTmpMgr Totbll = wxOrderTmpMgr.instance(); string ret = Totbll.ProcessPaySuccess_wx("notify_url", notify_id, out_trade_no, transaction_id, pay_info, MyCommFun.Str2Int(total_fee), otid, wid); ret = ret == "" ? "处理数据同步发送成功" : ret; logBll.AddLog(wid, "微信预定", "【微支付】notify_url Page_Load", ret, 1); //处理数据库逻辑 //注意交易单不要重复处理 //注意判断返回金额 //------------------------------ //处理业务完毕 //------------------------------ //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知 Response.Write("success"); } else { logBll.AddLog(wid, "【微支付】微信预定", "notify_url Page_Load", "支付失败", 1); Response.Write("支付失败"); } //回复服务器处理成功 Response.Write("success"); } else {//SHA1签名失败 logBll.AddLog("微信预定", "【微支付】notify_url Page_Load", "fail -SHA1 failed", 0); Response.Write("fail -SHA1 failed"); Response.Write(resHandler.getDebugInfo()); } } else {//md5签名失败 logBll.AddLog(wid, "微信预定", "【微支付】notify_url Page_Load", "fail -md5 failed", 0); Response.Write("fail -md5 failed"); Response.Write(resHandler.getDebugInfo()); } }
public ActionResult NativeNotifyUrl() { ResponseHandler resHandler = new ResponseHandler(null); //返回给微信的请求 RequestHandler res = new RequestHandler(null); string openId = resHandler.GetParameter("openid"); string productId = resHandler.GetParameter("product_id"); if (openId == null || productId == null) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "回调数据异常"); } //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(null); var sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28); var nonceStr = TenPayV3Util.GetNoncestr(); //创建请求统一订单接口参数 packageReqHandler.SetParameter("appid", TenPayV3Info.AppId); packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId); packageReqHandler.SetParameter("nonce_str", nonceStr); packageReqHandler.SetParameter("body", "test"); packageReqHandler.SetParameter("out_trade_no", sp_billno); packageReqHandler.SetParameter("total_fee", "1"); packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify); packageReqHandler.SetParameter("trade_type", TenPayV3Type.NATIVE.ToString()); packageReqHandler.SetParameter("openid", openId); packageReqHandler.SetParameter("product_id", productId); string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); packageReqHandler.SetParameter("sign", sign); string data = packageReqHandler.ParseXML(); try { //调用统一订单接口 var result = TenPayV3.Unifiedorder(data); var unifiedorderRes = XDocument.Parse(result); string prepayId = unifiedorderRes.Element("xml").Element("prepay_id").Value; //创建应答信息返回给微信 res.SetParameter("return_code", "SUCCESS"); res.SetParameter("return_msg", "OK"); res.SetParameter("appid", TenPayV3Info.AppId); res.SetParameter("mch_id", TenPayV3Info.MchId); res.SetParameter("nonce_str", nonceStr); res.SetParameter("prepay_id", prepayId); res.SetParameter("result_code", "SUCCESS"); res.SetParameter("err_code_des", "OK"); string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); res.SetParameter("sign", nativeReqSign); } catch (Exception) { res.SetParameter("return_code", "FAIL"); res.SetParameter("return_msg", "统一下单失败"); } return(Content(res.ParseXML())); }
protected void Page_Load(object sender, EventArgs e) { //string out_trade_no = Request["out_trade_no"]; //Lebi_Order order = B_Lebi_Order.GetModel(out_trade_no); string out_trade_no = Request.QueryString["out_trade_no"]; Lebi_Order order = B_Lebi_Order.GetModel("Code=lbsql{'" + out_trade_no + "'}"); if (order == null) { Response.Write("系统错误"); Response.End(); return; } TenpayUtil tu = new TenpayUtil(order); //创建ResponseHandler实例 ResponseHandler resHandler = new ResponseHandler(Context); resHandler.setKey(tu.tenpay_key); //判断签名 if (resHandler.isTenpaySign()) { ///通知id string notify_id = resHandler.getParameter("notify_id"); //通过通知ID查询,确保通知来至财付通 //创建查询请求 RequestHandler queryReq = new RequestHandler(Context); queryReq.init(); queryReq.setKey(tu.tenpay_key); queryReq.setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml"); queryReq.setParameter("partner", tu.bargainor_id); queryReq.setParameter("notify_id", notify_id); //通信对象 TenpayHttpClient httpClient = new TenpayHttpClient(); httpClient.setTimeOut(5); //设置请求内容 httpClient.setReqContent(queryReq.getRequestURL()); //后台调用 if (httpClient.call()) { //设置结果参数 ClientResponseHandler queryRes = new ClientResponseHandler(); queryRes.setContent(httpClient.getResContent()); queryRes.setKey(tu.tenpay_key); //判断签名及结果 //只有签名正确,retcode为0,trade_state为0才是支付成功 if (queryRes.isTenpaySign()) { //取结果参数做业务处理 out_trade_no = queryRes.getParameter("out_trade_no"); //财付通订单号 string transaction_id = queryRes.getParameter("transaction_id"); //金额,以分为单位 string total_fee = queryRes.getParameter("total_fee"); //如果有使用折扣券,discount有值,total_fee+discount=原请求的total_fee string discount = queryRes.getParameter("discount"); //支付结果 string trade_state = resHandler.getParameter("trade_state"); //交易模式,1即时到帐 2中介担保 string trade_mode = resHandler.getParameter("trade_mode"); #region //判断签名及结果 if ("0".Equals(queryRes.getParameter("retcode"))) { //Response.Write("id验证成功"); if ("1".Equals(trade_mode)) { //即时到账 if ("0".Equals(trade_state)) { //------------------------------ //即时到账处理业务开始 //------------------------------ //处理数据库逻辑 //注意交易单不要重复处理 //注意判断返回金额 //------------------------------ //即时到账处理业务完毕 //------------------------------ Order.OnlinePaySuccess("tenpayJSDZ", out_trade_no, transaction_id); //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知 Response.Write("success"); } else { Response.Write("即时到账支付失败"); } } else if ("2".Equals(trade_mode)) { //中介担保 //------------------------------ //中介担保处理业务开始 //------------------------------ //处理数据库逻辑 //注意交易单不要重复处理 //注意判断返回金额 int iStatus = Convert.ToInt32(trade_state); switch (iStatus) { case 0: //付款成功 break; case 1: //交易创建 break; case 2: //收获地址填写完毕 break; case 4: //卖家发货成功 break; case 5: //买家收货确认,交易成功 break; case 6: //交易关闭,未完成超时关闭 break; case 7: //修改交易价格成功 break; case 8: //买家发起退款 break; case 9: //退款成功 break; case 10: //退款关闭 break; } //------------------------------ //中介担保处理业务开始 //------------------------------ //给财付通系统发送成功信息,财付通系统收到此结果后不再进行后续通知 Response.Write("success"); } } else { //错误时,返回结果可能没有签名,写日志trade_state、retcode、retmsg看失败详情。 //通知财付通处理失败,需要重新通知 Response.Write("查询验证签名失败或id验证失败"); Response.Write("retcode:" + queryRes.getParameter("retcode")); } #endregion } else { Response.Write("通知ID查询签名验证失败"); } } else { //通知财付通处理失败,需要重新通知 Response.Write("后台调用通信失败"); //写错误日志 Response.Write("call err:" + httpClient.getErrInfo() + "<br>" + httpClient.getResponseCode() + "<br>"); } } else { Response.Write("签名验证失败"); } Response.End(); }
/// <summary> /// Sends a command to the node debugger. /// </summary> /// <param name="command">Command name.</param> /// <param name="args">Command arguments.</param> /// <param name="successHandler">Successful handler.</param> /// <param name="failureHandler">Failure handler.</param> /// <param name="timeout">Timeout interval in ms.</param> /// <param name="shortCircuitPredicate"></param> /// <returns></returns> public bool SendRequest( string command, Dictionary<string, object> args = null, Action<Dictionary<string, object>> successHandler = null, Action<Dictionary<string, object>> failureHandler = null, int? timeout = null, Func<bool> shortCircuitPredicate = null) { if (shortCircuitPredicate != null && shortCircuitPredicate()) { if (failureHandler != null) { failureHandler(null); } return false; } int reqId = DispenseRequestId(); // Use response handler if followup (given success or failure handler) or synchronous (given timeout) ResponseHandler responseHandler = null; if ((successHandler != null) || (failureHandler != null) || (timeout != null)) { responseHandler = new ResponseHandler(successHandler, failureHandler, timeout, shortCircuitPredicate); if (!_requestData.TryAdd(reqId, responseHandler)) { return false; } } Socket socket = Socket; if (socket == null) { return false; } try { socket.Send(CreateRequest(command, args, reqId)); } catch (SocketException) { return false; } return responseHandler == null || responseHandler.Wait(); }
/// <summary> /// Initializes a new instance of the <see cref="Responder<T>"/> class with return value processing method /// and a fault handler method /// </summary> /// <param name="responseHandler">The response handler - invoked when the client received a response from a remote method invocation</param> /// <param name="errorHandler">The error handler - invoked if the remote method invocation throws an exception.</param> public Responder(ResponseHandler <T> responseHandler, ErrorHandler errorHandler) { this.ResponseHandler = responseHandler; this.ErrorHandler = errorHandler; }