/// <summary> /// Sends given notificaiton message to required destination /// </summary> /// <param name="notification"></param> public void SendNotification(OrderNotification notification) { try { // Read account information ReadSenderAccountInformation(); ReadReceiverAccountInformation(); string accountType; if (_senderInformation.TryGetValue("username", out accountType)) { // Get sender account type accountType = (accountType.Split('@')[1]).Split('.')[0]; if ((_smtpAddress = GetSmtpAddress(accountType)) != String.Empty) { string subject = CreateSubject(notification.OrderNotificationType); string body = CreateBody(notification); // Send email using the specified credentials SendEmail(subject, body); } } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "SendNotification"); } }
public void NewNotification_SendNotificationToServer_NotificationReceivedByServer() { Thread.Sleep(5000); bool notificationReceived = false; var notificationManualResetEvent = new ManualResetEvent(false); // Create Order Object OrderNotification orderNotification = new OrderNotification(NotificationType.Email, OrderNotificationType.Accepted); MarketOrder marketOrder = new MarketOrder("Test Provider"); orderNotification.SetOrder(marketOrder); _notificationEngineMqServer.OrderNotificationEvent += delegate(OrderNotification notificationObject) { var notificationObjectReceived = notificationObject; notificationReceived = true; notificationManualResetEvent.Set(); }; _notificationEngineClient.SendNotification(orderNotification); notificationManualResetEvent.WaitOne(10000, false); Assert.AreEqual(true, notificationReceived, "Notification Received"); }
/// <summary> /// Creates email body test depending on the notification message /// </summary> private string CreateBody(OrderNotification notification) { string body = String.Empty; if (notification.OrderNotificationType.Equals(OrderNotificationType.New) || notification.OrderNotificationType.Equals(OrderNotificationType.Accepted)) { // Get basic order details body = GetOrderInformation(notification); } else if (notification.OrderNotificationType.Equals(OrderNotificationType.Executed)) { // Get basic Order details body = GetOrderInformation(notification); // Get Fill details body += GetFillInformation(notification); } else if (notification.OrderNotificationType.Equals(OrderNotificationType.Rejected)) { // Get Rejection details body = GetRejectionInformation(notification); } return(body); }
/// <summary> /// Sends Executions to MQ Exchange on the depending routing key /// </summary> /// <param name="notification">Contains execution stream to be published</param> public void SendNotification(OrderNotification notification) { try { if (Logger.IsDebugEnabled) { Logger.Debug("Order notification recieved for publishing", _type.FullName, "SendNotification"); } string routingKey; if (_serverMqParameters.TryGetValue(MqParameters.NotificationEngineServer.OrderMessageRoutingKey, out routingKey)) { //Send Message for publishing PublishNotifications(notification, routingKey); } else { Logger.Info("Notification not sent for publishing as routing key is unavailable.", _type.FullName, "SendNotification"); } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "SendNotification"); } }
public ActionResult Notify(OrderNotification notification) { //TODO: check if payUServer request var order = dbContext.Orders .Where(o => o.ExternalOrderId == notification.order.extOrderId) .Where(o => o.PayUOrderId == notification.order.orderId) .FirstOrDefault(); if (order != null) { if (notification.order.status == "COMPLETED") { order.OrderStatus = OrderStatus.Success; dbContext.Entry <Order>(order).State = EntityState.Modified; dbContext.SaveChanges(); var serviceDefinition = dbContext.Services.Find(order.DefinitionId); var service = paymentServices.FindService(order.ServiceId, serviceDefinition.HandlerName); service.Activate(serviceDefinition); } else if (notification.order.status == "CANCELLED" || notification.order.status == "REJECTED") { order.OrderStatus = OrderStatus.Failed; dbContext.Entry <Order>(order).State = EntityState.Modified; dbContext.SaveChanges(); } } return(View()); }
/// <summary> /// Handles new incoming Order Notification /// </summary> /// <param name="notification">Contains notification details specific to Orders</param> public void NewNotificationArrived(OrderNotification notification) { if (notification.NotificationType.Equals(NotificationType.Email)) { _emailManager.SendNotification(notification); } }
/// <summary> /// Publishes received message to respective queue /// </summary> /// <param name="notification">notification to be sent to server</param> /// <param name="routingKey">routing key to send message to respective queue</param> private void PublishNotifications(OrderNotification notification, string routingKey) { // Wrap notification in EasyNetQ message interface IMessage <OrderNotification> message = new Message <OrderNotification>(notification); // Send message to queue _advancedBus.Publish(_exchange, routingKey, true, false, message); }
/// <summary> /// A sample notifications callback from the NotificationHandler /// Will be called each time a new notification is received at the local webhook /// </summary> /// <param name="notification">The notification object that was received</param> private static void NotificationReceived(OrderNotification notification) { Console.WriteLine("\n\nNew " + notification.Status + " Notification Received for order with ID:" + notification.Id + " With description: " + notification.Description + " With app_dom_id: " + notification.Custom.AppDomId + (notification.Warnings == null ? "" : "Warnings:\n" + string.Join("\n", notification.Warnings)) + "\n\n"); }
/// <summary> /// Starts the process to send incoming notification to the server /// </summary> /// <param name="notification"></param> public void SendNotification(OrderNotification notification) { // Add to local collection _orderNotificationsCollection.Add(notification); if (Logger.IsDebugEnabled) { Logger.Debug("New Order Notification received for publishing", _type.FullName, "SendNotifications"); } }
public async Task Consume(ConsumeContext <RegisterOrder> context) { var command = context.Message; await Console.Out.WriteLineAsync($"Message has been received for {command.Name}"); var orderNotification = new OrderNotification(context.Message.Name, context.Message.Email); await context.Publish(orderNotification); }
/// <summary> /// Returns string containg necessary Rejection details /// </summary> /// <param name="notification"></param> /// <returns></returns> private string GetRejectionInformation(OrderNotification notification) { StringBuilder rejectionDetails = new StringBuilder(); rejectionDetails.AppendLine("REJECTION:"); rejectionDetails.AppendLine("Connector: " + notification.Rejection.OrderExecutionProvider); rejectionDetails.AppendLine("ID: " + notification.Rejection.OrderId); rejectionDetails.AppendLine("Symbol: " + notification.Rejection.Security.Symbol); rejectionDetails.AppendLine("Reason: " + notification.Rejection.RejectioReason); return(rejectionDetails.ToString()); }
/// <summary> /// Returns string containg necessary Fill details /// </summary> /// <param name="notification"></param> /// <returns></returns> private string GetFillInformation(OrderNotification notification) { StringBuilder fillDetails = new StringBuilder(); fillDetails.AppendLine("FILL:"); fillDetails.AppendLine("Status: " + notification.Fill.ExecutionType); fillDetails.AppendLine("Size: " + notification.Fill.ExecutionSize); fillDetails.AppendLine("Price: " + notification.Fill.ExecutionPrice); fillDetails.AppendLine("Execution ID: " + notification.Fill.ExecutionId); return(fillDetails.ToString()); }
/// <summary> /// Forwards Execution message to Communicator to be sent to Server /// </summary> /// <param name="notification">Contains Order Notification information to be sent</param> public void SendNotification(OrderNotification notification) { try { // Forward information to Communicator _communicator.SendNotification(notification); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "SendNotification"); } }
public bool AddNotification(TKey id, OrderNotification notification) { var order = _repository.Find(x => x.Compare(x.Id, id)).FirstOrDefault(); if (order == null) { return(false); } order.OrderStatus.Notifications.Add(notification); _repository.Update(order); return(true); }
public void NewNotification_SendEmailNotificationToReceiver() { OrderNotification orderNotification = new OrderNotification(NotificationType.Email, OrderNotificationType.Accepted); Order order = new Order("1234", OrderSide.BUY, 100, OrderTif.DAY, "", new Security() { Symbol = "TC" }, OrderExecutionProvider.Simulated); orderNotification.SetOrder(order); _notificationController.NewNotificationArrived(orderNotification); }
public static void Main(string[] args) { var consoleConfiguration = new ConsoleConfiguration().Get(); using (var bus = RabbitHutch.CreateBus(consoleConfiguration[RabbitMqServer.ConStr])) { bus.SubscribeAsync <RegisterOrder>(RabbitMqServer.Registration.OrderQueue, message => Task.Factory.StartNew(() => { Console.WriteLine("Payment = <" + message.CardNumber + ", " + message.CardHolderName + ", " + message.ExpiryDate + ", " + message.Amount + ">", Color.Lime); var cardPaymentRequest = new CardPaymentRequest() { Amount = message.Amount, CardHolderName = message.CardHolderName, CardNumber = message.CardNumber, ExpiryDate = message.ExpiryDate }; var paymentResponse = bus.Request <CardPaymentRequest, CardPaymentResponse>(cardPaymentRequest); var orderNotification = new OrderNotification() { Address = message.Address, AuthCode = paymentResponse.AuthCode, DeliveryDate = DateTime.Now.AddDays(14), Email = message.Email, Name = message.Name }; bus.Publish(orderNotification, cfg => cfg.WithQueueName(RabbitMqServer.Notification.NotificationQueue)); }).ContinueWith(task => { if (task.IsCompleted && !task.IsFaulted) { Console.WriteLine("Finished processing all messages", Color.Gray); } else { throw new EasyNetQException("Message processing exception - look in the default error queue (broker)"); } })); Console.WriteLine("Listening for messages. Hit <return> to quit."); Console.ReadLine(); } }
/// <summary> /// Called when new order notification message is received from Communicator Server /// </summary> /// <param name="notification">Execution containing Order and Fill information</param> private void OnNewOrderNotificationReceived(OrderNotification notification) { try { if (Logger.IsDebugEnabled) { Logger.Debug("New Execution received " + notification, _type.FullName, "OnNewOrderNotificationReceived"); } // Forward new message received to notification controller _notificationController.NewNotificationArrived(notification); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "OnNewOrderNotificationReceived"); } }
/// <summary> /// Returns string containg necessary order details /// </summary> /// <param name="notification"></param> /// <returns></returns> private string GetOrderInformation(OrderNotification notification) { StringBuilder orderDetails = new StringBuilder(); orderDetails.AppendLine("ORDER DETAILS:"); orderDetails.AppendLine("Connector: " + notification.Order.OrderExecutionProvider); orderDetails.AppendLine("Symbol: " + notification.Order.Security.Symbol); orderDetails.AppendLine("Side: " + notification.Order.OrderSide); orderDetails.AppendLine("Size: " + notification.Order.OrderSize); if (notification.LimitPrice != default(decimal)) { orderDetails.AppendLine("Price: " + notification.LimitPrice); } orderDetails.AppendLine("Status: " + notification.Order.OrderStatus); orderDetails.AppendLine("ID: " + notification.Order.OrderID); orderDetails.AppendLine("Broker ID: " + notification.Order.BrokerOrderID); return(orderDetails.ToString()); }
private async void SendMessage(OrderNotification notification) { await Task.Run(() => { _callBacks.RemoveAll(c => ((ICommunicationObject)c).State != CommunicationState.Opened); List <IOrderSubscription> toRemove = new List <IOrderSubscription>(); Parallel.ForEach(_callBacks, orderSubscription => { try { orderSubscription.SendOrderNotification(notification); } catch { toRemove.Add(orderSubscription); } }); _callBacks.RemoveAll(os => toRemove.Contains(os)); }); }
public void NewNotification_SendNotificationToServer_NotificationReceivedByServer() { Thread.Sleep(5000); bool notificationReceived = false; var notificationManualResetEvent = new ManualResetEvent(false); // Create Order Object OrderNotification orderNotification = new OrderNotification(NotificationType.Email, OrderNotificationType.Accepted); _notificationEngineMqServer.OrderNotificationEvent += delegate(OrderNotification notificationObject) { notificationReceived = true; notificationManualResetEvent.Set(); }; IMessage <OrderNotification> message = new Message <OrderNotification>(orderNotification); _advancedBus.Publish(_adminExchange, "notificationengine.order.message", true, false, message); notificationManualResetEvent.WaitOne(10000, false); Assert.AreEqual(true, notificationReceived, "Notification Received"); }
public static void SendOrdersToRiskifiedExample() { #region preprocessing and loading config string domain = ConfigurationManager.AppSettings["MerchantDomain"]; string authToken = ConfigurationManager.AppSettings["MerchantAuthenticationToken"]; RiskifiedEnvironment riskifiedEnv = (RiskifiedEnvironment)Enum.Parse(typeof(RiskifiedEnvironment), ConfigurationManager.AppSettings["RiskifiedEnvironment"]); // Generating a random starting order number // we need to send the order with a new order number in order to create it on riskified var rand = new Random(); int orderNum = rand.Next(1000, 200000); // Make orderNum a string to use as customer id string idString = $"customerId_{orderNum.ToString()}"; #endregion #region order object creation // generate a new order - the sample generates a fixed order with same details but different order number each time // see GenerateOrder for more info on how to create the Order objects var order = GenerateOrder(orderNum); #endregion #region sending data to riskified // read action from console const string menu = "Commands:\n" + "'p' for checkout\n" + "'e' for checkout denied\n" + "'c' for create\n" + "'u' for update\n" + "'s' for submit\n" + "'d' for cancel\n" + "'r' for partial refund\n" + "'f' for fulfill\n" + "'x' for decision\n" + "'h' for historical sending\n" + "'y' for chargeback submission\n" + "'v' for decide (sync only)\n" + "'l' for eligible for Deco payment \n" + "'o' for opt-in to Deco payment \n" + "'account' for account actions menu\n" + "'q' to quit"; const string accountActionsMenu = "Account Action Commands:\n" + "'li' for login(account)\n" + "'cc' for customer create (account)\n" + "'cu' for customer update (account)\n" + "'lo' for logout (account)\n" + "'pw' for password reset (account)\n" + "'wl' for wishlist (account)\n" + "'re' for redeem (account)\n" + "'co' for contact (account)\n" + "'menu' for main menu\n" + "'q' to quit"; Console.WriteLine(menu); string commandStr = Console.ReadLine(); // loop on console actions while (commandStr != null && (!commandStr.Equals("q"))) { // the OrdersGateway is responsible for sending orders to Riskified servers OrdersGateway gateway = new OrdersGateway(riskifiedEnv, authToken, domain); try { OrderNotification res = null; AccountActionNotification accRes = null; switch (commandStr) { case "menu": case "account": break; case "p": Console.WriteLine("Order checkout Generated with merchant order number: " + orderNum); var orderCheckout = GenerateOrderCheckout(orderNum.ToString()); orderCheckout.Id = orderNum.ToString(); // sending order checkout for creation (if new orderNum) or update (if existing orderNum) res = gateway.Checkout(orderCheckout); break; case "a": Console.WriteLine("Order Advise Generated with merchant order number: " + orderNum); var orderAdviseCheckout = GenerateAdviseOrderCheckout(orderNum.ToString()); orderAdviseCheckout.Id = orderNum.ToString(); // sending order checkout for creation (if new orderNum) or update (if existing orderNum) res = gateway.Advise(orderAdviseCheckout); break; case "e": Console.WriteLine("Order checkout Generated."); var orderCheckoutDenied = GenerateOrderCheckoutDenied(orderNum); Console.Write("checkout to deny id: "); string orderCheckoutDeniedId = Console.ReadLine(); orderCheckoutDenied.Id = orderCheckoutDeniedId; // sending order checkout for creation (if new orderNum) or update (if existing orderNum) res = gateway.CheckoutDenied(orderCheckoutDenied); break; case "c": Console.WriteLine("Order Generated with merchant order number: " + orderNum); order.Id = orderNum.ToString(); orderNum++; // sending order for creation (if new orderNum) or update (if existing orderNum) res = gateway.Create(order); break; case "s": Console.WriteLine("Order Generated with merchant order number: " + orderNum); order.Id = orderNum.ToString(); orderNum++; // sending order for submitting and analysis // it will generate a callback to the notification webhook (if defined) with a decision regarding the order res = gateway.Submit(order); break; case "v": Console.WriteLine("Order Generated with merchant order number: " + orderNum); order.Id = orderNum.ToString(); orderNum++; // sending order for synchronous decision // it will generate a synchronous response with the decision regarding the order // (for sync flow only) res = gateway.Decide(order); break; case "u": Console.Write("Updated order id: "); string upOrderId = Console.ReadLine(); order.Id = int.Parse(upOrderId).ToString(); res = gateway.Update(order); break; case "d": Console.Write("Cancelled order id: "); string canOrderId = Console.ReadLine(); res = gateway.Cancel( new OrderCancellation( merchantOrderId: int.Parse(canOrderId), cancelledAt: DateTime.Now, cancelReason: "Customer cancelled before shipping")); break; case "r": Console.Write("Refunded order id: "); string refOrderId = Console.ReadLine(); res = gateway.PartlyRefund( new OrderPartialRefund( merchantOrderId: int.Parse(refOrderId), partialRefunds: new[] { new PartialRefundDetails( refundId: "12345", refundedAt: DateTime.Now, // make sure to initialize DateTime with the correct timezone amount: 5.3, currency: "USD", reason: "Customer partly refunded on shipping fees") })); break; case "f": Console.Write("Fulfill order id: "); string fulfillOrderId = Console.ReadLine(); OrderFulfillment orderFulfillment = GenerateFulfillment(int.Parse(fulfillOrderId)); res = gateway.Fulfill(orderFulfillment); break; case "x": Console.Write("Decision order id: "); string decisionOrderId = Console.ReadLine(); OrderDecision orderDecision = GenerateDecision(int.Parse(decisionOrderId)); res = gateway.Decision(orderDecision); break; case "h": int startOrderNum = orderNum; var orders = new List <Order>(); var financialStatuses = new[] { "paid", "cancelled", "chargeback" }; for (int i = 0; i < 22; i++) { Order o = GenerateOrder(orderNum++); o.FinancialStatus = financialStatuses[i % 3]; orders.Add(o); } Console.WriteLine("Orders Generated with merchant order numbers: {0} to {1}", startOrderNum, orderNum - 1); // sending 3 historical orders with different processing state Dictionary <string, string> errors; bool success = gateway.SendHistoricalOrders(orders, out errors); if (success) { Console.WriteLine("All historical orders sent successfully"); } else { Console.WriteLine("Some historical orders failed to send:"); Console.WriteLine(String.Join("\n", errors.Select(p => p.Key + ":" + p.Value).ToArray())); } break; case "y": Console.Write("Chargeback order id: "); string chargebackOrderId = Console.ReadLine(); OrderChargeback orderChargeback = GenerateOrderChargeback(chargebackOrderId); res = gateway.Chargeback(orderChargeback); break; case "l": Console.Write("Check Deco eligibility on id: "); string eligibleOrderId = Console.ReadLine(); OrderIdOnly eligibleOrderIdOnly = GenerateOrderIdOnly(eligibleOrderId); res = gateway.Eligible(eligibleOrderIdOnly); break; case "o": Console.Write("Opt-in to Deco payment on id: "); string optInOrderId = Console.ReadLine(); OrderIdOnly optInOrderIdOnly = GenerateOrderIdOnly(optInOrderId); res = gateway.OptIn(optInOrderIdOnly); break; case "li": Console.Write("Login account action"); Login login = GenerateLogin(idString); accRes = gateway.Login(login); break; case "cc": Console.Write("Customer Create account action"); CustomerCreate customerCreate = GenerateCustomerCreate(idString); accRes = gateway.CustomerCreate(customerCreate); break; case "cu": Console.Write("Customer Update account action"); CustomerUpdate customerUpdate = GenerateCustomerUpdate(idString); accRes = gateway.CustomerUpdate(customerUpdate); break; case "lo": Console.Write("Logout account action"); Logout logout = GenerateLogout(idString); accRes = gateway.Logout(logout); break; case "pw": Console.Write("ResetPasswordRequest account action"); ResetPasswordRequest resetPasswordRequest = GenerateResetPasswordRequest(idString); accRes = gateway.ResetPasswordRequest(resetPasswordRequest); break; case "wl": Console.Write("WishlistChanges account action"); WishlistChanges wishlistChanges = GenerateWishlistChanges(idString); accRes = gateway.WishlistChanges(wishlistChanges); break; case "re": Console.Write("Redeem account action"); Redeem redeem = GenerateRedeem(idString); accRes = gateway.Redeem(redeem); break; case "co": Console.Write("Customer Reach-Out account action"); CustomerReachOut customerReachOut = GenerateCustomerReachOut(idString); accRes = gateway.CustomerReachOut(customerReachOut); break; } if (res != null) { Console.WriteLine("\n\nOrder sent successfully:" + "\nStatus at Riskified: " + res.Status + "\nOrder ID received:" + res.Id + "\nDescription: " + res.Description + "\nWarnings: " + (res.Warnings == null ? "---" : string.Join(" \n", res.Warnings)) + "\n\n"); } if (accRes != null) { Console.WriteLine("\n\nAccount Action sent successfully:" + "\nDecision: " + accRes.Decision); } } catch (OrderFieldBadFormatException e) { // catching Console.WriteLine("Exception thrown on order field validation: " + e.Message); } catch (RiskifiedTransactionException e) { Console.WriteLine("Exception thrown on transaction: " + e.Message); } // ask for next action to perform Console.WriteLine(); if (commandStr.Equals("account")) { Console.WriteLine(accountActionsMenu); } else { Console.WriteLine(menu); } commandStr = Console.ReadLine(); } #endregion }
public static int runAll() { try { string domain = ConfigurationManager.AppSettings["MerchantDomain"]; string authToken = ConfigurationManager.AppSettings["MerchantAuthenticationToken"]; RiskifiedEnvironment riskifiedEnv = (RiskifiedEnvironment)Enum.Parse(typeof(RiskifiedEnvironment), ConfigurationManager.AppSettings["RiskifiedEnvironment"]); OrderNotification res = null; var rand = new Random(); int orderNum = rand.Next(1000, 200000); var order = GenerateOrder(orderNum); OrdersGateway gateway = new OrdersGateway(riskifiedEnv, authToken, domain); var orderCheckout = GenerateOrderCheckout(orderNum.ToString()); orderCheckout.Id = orderNum.ToString(); res = gateway.Checkout(orderCheckout); var orderCheckoutDenied = GenerateOrderCheckoutDenied(orderNum); orderNum++; orderCheckoutDenied.Id = orderNum.ToString(); res = gateway.CheckoutDenied(orderCheckoutDenied); orderNum++; order.Id = orderNum.ToString(); res = gateway.Create(order); order.Id = orderNum.ToString(); orderNum++; res = gateway.Submit(order); res = gateway.Update(order); res = gateway.Cancel( new OrderCancellation( merchantOrderId: order.Id, cancelledAt: DateTime.Now, cancelReason: "Customer cancelled before shipping")); order.Id = orderNum.ToString(); orderNum++; // sending order for creation (if new orderNum) or update (if existing orderNum) res = gateway.Create(order); order.Id = orderNum.ToString(); orderNum++; // sending order for submitting and analysis // it will generate a callback to the notification webhook (if defined) with a decision regarding the order res = gateway.Submit(order); order.Id = order.Id; res = gateway.Update(order); res = gateway.Cancel( new OrderCancellation( merchantOrderId: int.Parse(order.Id), cancelledAt: DateTime.Now, cancelReason: "Customer cancelled before shipping")); res = gateway.PartlyRefund( new OrderPartialRefund( merchantOrderId: int.Parse(order.Id), partialRefunds: new[] { new PartialRefundDetails( refundId: "12345", refundedAt: DateTime.Now, // make sure to initialize DateTime with the correct timezone amount: 5.3, currency: "USD", reason: "Customer partly refunded on shipping fees") })); OrderFulfillment orderFulfillment = GenerateFulfillment(int.Parse(order.Id)); res = gateway.Fulfill(orderFulfillment); OrderDecision orderDecision = GenerateDecision(int.Parse(order.Id)); res = gateway.Decision(orderDecision); } catch (Exception ex) { Console.WriteLine("[failed] " + ex.ToString()); return(-1); } return(0); }
/// <summary> /// Runs the notification server /// This method is blocking and will not return until StopReceiveNotifications is called /// </summary> /// <exception cref="NotifierServerFailedToStartException">Thrown when the listener was unable to start due to server network configuration errors</exception> /// <exception cref="NotifierAlreadyRunningException">Thrown when server is already running</exception> public void ReceiveNotifications() { if (!_isStopped) { throw new NotifierAlreadyRunningException("Notification handler already running"); } if (!_listener.IsListening) { try { _listener.Start(); } catch (Exception e) { string errorMsg = string.Format( "Unable to start the HTTP webhook listener on: {0}. Check firewall configuration and make sure the app is running under admin privleges", _localListeningEndpoint); LoggingServices.Fatal(errorMsg, e); throw new NotifierServerFailedToStartException(errorMsg, e); } } _isStopped = false; while (!_isStopped) { try { //blocking call var context = _listener.GetContext(); // reaches here when a connection was made var request = context.Request; if (!request.HasEntityBody) { LoggingServices.Error("Received HTTP notification with no body - shouldn't happen"); continue; } string responseString; bool acionSucceeded = false; try { var notificationData = HttpUtils.ParsePostRequestToObject <OrderWrapper <Notification> >(request, _authToken); OrderNotification n = new OrderNotification(notificationData); responseString = string.Format( "<HTML><BODY>Merchant Received Notification For Order {0} with status {1} and description {2}</BODY></HTML>", n.Id, n.Status, n.Description); // running callback to call merchant code on the notification Task.Factory.StartNew(() => _notificationReceivedCallback(n)); acionSucceeded = true; } catch (RiskifiedAuthenticationException uae) { LoggingServices.Error("Notification message authentication failed", uae); responseString = "<HTML><BODY>Merchant couldn't authenticate notification message</BODY></HTML>"; } catch (Exception e) { LoggingServices.Error("Unable to parse notification message. Some or all of the post params are missing or invalid", e); responseString = "<HTML><BODY>Merchant couldn't parse notification message</BODY></HTML>"; } // Obtain a response object to write back a ack response to the riskified server HttpListenerResponse response = context.Response; // Construct a simple response. HttpUtils.BuildAndSendResponse(response, _authToken, _shopDomain, responseString, acionSucceeded); } catch (Exception e) { LoggingServices.Error("An error occured will receiving notification. Specific request was skipped", e); // trying to restart listening - maybe connection was cut shortly if (!_listener.IsListening) { RestartHttpListener(); } } } }
public void SendOrderNotification(OrderNotification notification) { throw new NotImplementedException(); }
public void SendOrderNotification(OrderNotification notification) { tbMessages.AppendText($"New status for order №{notification.OrderId} is {notification.NewStatus}" + Environment.NewLine); }
public void SendOrderNotification(OrderNotification notification) { }
public Task <bool> UpdateStatusAsync(TKey id, CurrentOrderStatus status, OrderNotification notification) { return(Task.FromResult(UpdateStatus(id, status, notification))); }
public Task <bool> AddNotificationAsync(TKey id, OrderNotification notification) { return(Task.FromResult(AddNotification(id, notification))); }
public async Task SendMessage(OrderNotification msg) { await Clients.All.ReceiveMessage(msg.Msg); }
/// <summary> ///抓取商城订单 /// </summary> /// <param name="orderInfoList"></param> public void OrderSync(IList <OrderInfo> orderInfoList, string siId, out List <OrderNotification> orderNotifications) { if (orderInfoList.Count > 0) { var orderNotificationResults = new List <OrderNotification>(); foreach (var itemOrderInfo in orderInfoList) { var order_sn = string.Empty;//OMS系统这边对应的SerialNumber //抓取商城订单操作事务 using (var tran = _omsAccessor.OMSContext.Database.BeginTransaction()) { if (_orderService.GetOrderByPSerialNumber(itemOrderInfo.order_id) == null) { var insertErrorCount = 0; var errInfo = ""; try { //订单插入 Order newOrder = new Order { SerialNumber = _commonService.GetOrderSerialNumber("SC"), UserName = itemOrderInfo.user_name, PayState = PayState.Success, SumPrice = Convert.ToDecimal(itemOrderInfo.order_sum_price), PayPrice = Convert.ToDecimal(itemOrderInfo.order_fact_price), PayDate = DateTime.Now, CustomerName = itemOrderInfo.consignee_info.fullname, CustomerPhone = itemOrderInfo.consignee_info.mobile, AddressDetail = itemOrderInfo.consignee_info.province.Trim() + " " + itemOrderInfo.consignee_info.city.Trim() + " " + itemOrderInfo.consignee_info.county.Trim() + " " + itemOrderInfo.consignee_info.full_address.Trim(), CreatedBy = 0, //代表系统本身 CustomerMark = itemOrderInfo.order_remark, //订单备注 ShopId = 97, //97为网上商城在新系统数据库Dictionary表中的Id PSerialNumber = itemOrderInfo.order_id.Trim(), IsNeedPaperBag = itemOrderInfo.is_need_invoice, }; //机场店地址 if (itemOrderInfo.consignee_info.full_address.Contains("深圳宝安机场到达出口直行150米大厅右侧(星巴克对面)")) { newOrder.AddressDetail = "广东省" + " " + "深圳市" + " " + "宝安区" + " " + itemOrderInfo.consignee_info.full_address.Trim(); } //匹配仓库 newOrder.WarehouseId = _orderService.MatchWarehouseId(itemOrderInfo.product_info_list, newOrder.AddressDetail); //订单类型 string[] XHString = { "1", "2", "3", "10" }; if (((IList)XHString).Contains(itemOrderInfo.order_type)) { //商城现货 newOrder.Type = OrderType.B2C_XH; } else if (itemOrderInfo.order_type == "4") { //商城跨境 newOrder.Type = OrderType.B2C_KJ; } else if (itemOrderInfo.order_type == "9") { //合作商 newOrder.Type = OrderType.B2C_HZS; } if (itemOrderInfo.order_state == "WAIT_SELLER_STOCK_OUT") { newOrder.State = OrderState.Paid; } else if (itemOrderInfo.order_state == "PAY_REVOKE") { newOrder.State = OrderState.Cancel; } //订单物流信息 newOrder.DeliveryTypeId = _deliveriesService.GetDeliveryByShopCode(itemOrderInfo.delivery_name.Trim()) == null ?0 : _deliveriesService.GetDeliveryByShopCode(itemOrderInfo.delivery_name.Trim()).Id; //客户自提修改快递方式 if (itemOrderInfo.seller_remark.Contains("自提码")) { newOrder.DeliveryTypeId = _deliveriesService.ConfirmDeliveryIsExist("KHZT") == null ? 0 : _deliveriesService.ConfirmDeliveryIsExist("KHZT").Id; } if (newOrder.DeliveryTypeId == 0) { _logService.InsertSystemLog(LogLevelEnum.AddOrderErr, "订单" + itemOrderInfo.order_id + "快递方式:快递方式不匹配" + itemOrderInfo.delivery_name); tran.Commit(); insertErrorCount++; continue; } //订单发票类型 if (!itemOrderInfo.is_need_invoice) { newOrder.InvoiceType = InvoiceType.NoNeedInvoice; } else { switch (itemOrderInfo.order_invoice_info.invoice_title_type.Trim()) { case "1": newOrder.InvoiceType = InvoiceType.PersonalInvoice; break; case "2": newOrder.InvoiceType = InvoiceType.CompanyInvoice; break; case "3": newOrder.InvoiceType = InvoiceType.SpecialInvoice; break; } } //订单支付类型 var payType = _omsAccessor.Get <Dictionary>().Where(x => x.Isvalid && x.Type == DictionaryType.PayType && x.Value.Trim().Contains("网银在线")).FirstOrDefault(); newOrder.PayType = payType == null ? 119 : payType.Id; //下单时间 if (itemOrderInfo.order_generate_date.Trim() != "") { newOrder.CreatedTime = Convert.ToDateTime(itemOrderInfo.order_generate_date.Trim()); } //支付时间 if (itemOrderInfo.order_paydate.Trim() != "") { newOrder.PayDate = Convert.ToDateTime(itemOrderInfo.order_paydate.Trim()); } //商城代金券优惠 newOrder.ProductCoupon = itemOrderInfo.product_coupon_info; newOrder.AdminMark = itemOrderInfo.seller_remark; var zmjfPrice = itemOrderInfo.coupon_detail_list.Where(r => r.coupon_type.Equals("IntegralValue_New")).FirstOrDefault(); if (zmjfPrice != null) { newOrder.ZMIntegralValuePrice = Convert.ToDecimal(zmjfPrice.coupon_price); } //订单所使用的中民券 var zmCoupon = itemOrderInfo.coupon_detail_list.Where(r => r.coupon_type.Equals("ZMCoupon")).FirstOrDefault(); if (zmCoupon != null) { newOrder.ZMCoupon = float.Parse(zmCoupon.coupon_price); } else { newOrder.ZMCoupon = 0; } //订单所使用的中民红酒券 var zmWineCoupon = itemOrderInfo.coupon_detail_list.Where(r => r.coupon_type.Equals("WineCoupon")).FirstOrDefault(); if (zmWineCoupon != null) { newOrder.ZMWineCoupon = Math.Round(float.Parse(zmWineCoupon.coupon_price), 2); } else { newOrder.ZMWineCoupon = 0; } //订单所使用的的红酒网红酒券 var wineWorldCoupon = itemOrderInfo.coupon_detail_list.Where(r => r.coupon_type.Equals("WineWorldCoupon")).FirstOrDefault(); if (wineWorldCoupon != null) { newOrder.WineWorldCoupon = Math.Round(float.Parse(wineWorldCoupon.coupon_price), 2); } else { newOrder.WineWorldCoupon = 0; } //总价要加上中民红酒券以及红酒网红酒券 newOrder.SumPrice += (decimal)newOrder.ZMWineCoupon; newOrder.SumPrice += (decimal)newOrder.WineWorldCoupon; _omsAccessor.Insert(newOrder); _omsAccessor.SaveChanges(); #region 新增订单日志 _logService.InsertOrderLog(newOrder.Id, "新增订单", newOrder.State, newOrder.PayState, "商城接口新增订单"); #endregion order_sn = newOrder.SerialNumber; //订单商品插入 if (itemOrderInfo.product_info_list.Count > 0) { foreach (var itemProduct in itemOrderInfo.product_info_list) { if (string.IsNullOrEmpty(itemProduct.goods_sn)) { errInfo += "订单" + itemOrderInfo.order_id + "商品插入失败:商品" + itemProduct.goods_name + ",编码为空或NULL!"; insertErrorCount++; break; } SaleProduct saleProduct = _productService.GetSaleProductByGoodSn(itemProduct.goods_sn); if (saleProduct != null && saleProduct.ProductId != 0 && saleProduct.Stock >= Convert.ToInt32(itemProduct.item_total.Trim())) { if (saleProduct.AvailableStock < Convert.ToInt32(itemProduct.item_total.Trim())) { errInfo += "订单" + itemOrderInfo.order_id + "商品插入失败:商品库存不足" + itemProduct.goods_name + ",商品编码为" + itemProduct.goods_sn; insertErrorCount++; break; } OrderProduct newOrderProduct = new OrderProduct { OrderId = newOrder.Id, SaleProductId = saleProduct.Id, Quantity = Convert.ToInt32(itemProduct.item_total.Trim()), OrginPrice = _productService.GetSaleProductPriceById(saleProduct.Id, 103).Price, Price = Convert.ToDecimal(itemProduct.sale_price.Trim()), SumPrice = Convert.ToInt32(itemProduct.item_total.Trim()) * Convert.ToDecimal(itemProduct.sale_price.Trim()), CreatedBy = 0 }; //销售商品总库存判断及锁定 saleProduct.LockStock += Convert.ToInt32(itemProduct.item_total.Trim()); saleProduct.AvailableStock = saleProduct.Stock - saleProduct.LockStock; _omsAccessor.Update(saleProduct); _omsAccessor.Insert(newOrderProduct); _omsAccessor.SaveChanges(); //新增锁定库存记录 _productService.CreateSaleProductLockedTrackAndWareHouseStock(newOrder.Id, saleProduct.Id, newOrder.WarehouseId, newOrderProduct.Quantity, newOrderProduct.Id); } else { errInfo += "订单" + itemOrderInfo.order_id + "商品插入失败:不存在商品" + itemProduct.goods_name + ",商品编码为" + itemProduct.goods_sn; insertErrorCount++; break; } } } if (insertErrorCount == 0) { //插入发票信息 if (newOrder.InvoiceType != InvoiceType.NoNeedInvoice) { InvoiceInfo newOrderInvoiceInfo = new InvoiceInfo { OrderId = newOrder.Id, CustomerEmail = string.IsNullOrEmpty(itemOrderInfo.order_invoice_info.InvoiceEmail)?"": itemOrderInfo.order_invoice_info.InvoiceEmail, Title = itemOrderInfo.order_invoice_info.invoice_title_info, TaxpayerID = itemOrderInfo.order_invoice_info.taxpayer_id, RegisterAddress = itemOrderInfo.order_invoice_info.register_address, RegisterTel = itemOrderInfo.order_invoice_info.register_tel, BankOfDeposit = itemOrderInfo.order_invoice_info.bank_of_deposit, BankAccount = itemOrderInfo.order_invoice_info.bank_account, CreatedBy = 0, }; _omsAccessor.Insert(newOrderInvoiceInfo); _omsAccessor.SaveChanges(); } //支付信息插入 OrderPayPrice newOrderPayPrice = new OrderPayPrice { OrderId = newOrder.Id, IsPay = true, Price = Convert.ToDecimal(itemOrderInfo.order_fact_price.Trim()), CreatedBy = 0 }; if (itemOrderInfo.order_paydate.Trim() == "") { newOrderPayPrice.CreatedTime = DateTime.Now; } else { newOrderPayPrice.CreatedTime = Convert.ToDateTime(itemOrderInfo.order_paydate.Trim()); } //订单支付类型 newOrderPayPrice.PayType = payType == null ? 119 : payType.Id; _omsAccessor.Insert(newOrderPayPrice); _omsAccessor.SaveChanges(); } } catch (Exception ex) { insertErrorCount++; errInfo += "订单" + itemOrderInfo.order_id + "插入错误" + ex.Message; } if (insertErrorCount > 0) { tran.Rollback(); //最后插入异常 _logService.InsertSystemLog(LogLevelEnum.AddOrderErr, errInfo); } else { tran.Commit(); //获取成功下单的订单 var orderNatification = new OrderNotification { order_id = itemOrderInfo.order_id, order_sn = order_sn, operation_result = "1", sd_id = siId }; orderNotificationResults.Add(orderNatification); } } } } orderNotifications = orderNotificationResults; } else { orderNotifications = null; } }