public async Task <bool> CreateOrUpdateHook() { // POST https://{accountName}.{environment}.com.br/api/orders/hook/config string baseUrl = this._httpContextAccessor.HttpContext.Request.Headers[StorePickUpConstants.FORWARDED_HOST]; HookNotification createOrUpdateHookResponse = new HookNotification(); OrderHook orderHook = new OrderHook { Filter = new Filter { Status = new List <string> { StorePickUpConstants.Status.ReadyForHandling, } }, Hook = new Hook { Headers = new Headers { Key = StorePickUpConstants.EndPointKey }, Url = new Uri($"https://{baseUrl}/{StorePickUpConstants.AppName}/{StorePickUpConstants.EndPointKey}") } }; var jsonSerializedOrderHook = JsonConvert.SerializeObject(orderHook); Console.WriteLine($"Url = https://{baseUrl}/{StorePickUpConstants.AppName}/{StorePickUpConstants.EndPointKey}"); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri($"http://{this._httpContextAccessor.HttpContext.Request.Headers[StorePickUpConstants.VTEX_ACCOUNT_HEADER_NAME]}.{StorePickUpConstants.ENVIRONMENT}.com.br/api/orders/hook/config"), Content = new StringContent(jsonSerializedOrderHook, Encoding.UTF8, StorePickUpConstants.APPLICATION_JSON) }; request.Headers.Add(StorePickUpConstants.USE_HTTPS_HEADER_NAME, "true"); string authToken = this._httpContextAccessor.HttpContext.Request.Headers[StorePickUpConstants.HEADER_VTEX_CREDENTIAL]; if (authToken != null) { request.Headers.Add(StorePickUpConstants.AUTHORIZATION_HEADER_NAME, authToken); request.Headers.Add(StorePickUpConstants.PROXY_AUTHORIZATION_HEADER_NAME, authToken); } MerchantSettings merchantSettings = await _storePickupRepository.GetMerchantSettings(); request.Headers.Add(StorePickUpConstants.AppKey, merchantSettings.AppKey); request.Headers.Add(StorePickUpConstants.AppToken, merchantSettings.AppToken); var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"[-] CreateOrUpdateHook Response {response.StatusCode} Content = '{responseContent}' [-]"); _context.Vtex.Logger.Info("CreateOrUpdateHook", "Response", $"[{response.StatusCode}] {responseContent}"); return(response.IsSuccessStatusCode); }
public async Task <IActionResult> ProcessNotification() { bool success = false; ActionResult status = BadRequest(); if ("post".Equals(HttpContext.Request.Method, StringComparison.OrdinalIgnoreCase)) { string bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync(); Console.WriteLine($"[Hook Notification] : '{bodyAsText}'"); dynamic notification = JsonConvert.DeserializeObject <dynamic>(bodyAsText); if (notification != null && notification.hookConfig != null && notification.hookConfig == StorePickUpConstants.HookPing) { status = Ok(); success = true; } else { HookNotification hookNotification = JsonConvert.DeserializeObject <HookNotification>(bodyAsText); success = await _storePickupService.ProcessNotification(hookNotification); status = success ? Ok() : StatusCode(StatusCodes.Status500InternalServerError); } _context.Vtex.Logger.Info("ProcessNotification", null, $"Success? [{success}] for {bodyAsText}"); } else { Console.WriteLine($"[Hook Notification] : '{HttpContext.Request.Method}'"); } Console.WriteLine($"[Process Notification] : '{success}'"); return(status); }
/// <summary> /// Register or add subscription, based on given recieverKey, type and hook handler /// </summary> /// <param name="recieverKey">the Job id for which the handler is interested to recieve or get message notification</param> /// <param name="type">type of message</param> /// <param name="handler">the handler, is the one responsible to recieve push notification</param> /// <returns>Guid as key</returns> public Guid RegisterHook(JobId recieverKey, MessageType type, IHookHandler <JobId> handler) { if (recieverKey == default(JobId)) { throw new ArgumentNullException(nameof(recieverKey)); } if (handler == default(IHookHandler <JobId>)) { throw new ArgumentNullException(nameof(handler)); } var val = _hooks.Values.Where(h => h.Id.Equals(recieverKey) && h.Type == type && object.Equals(h.Handler, handler)); if (val.Any()) { return(val.FirstOrDefault().Key); } var id = Guid.NewGuid(); _hooks[id] = new HookNotification() { Key = id, Id = recieverKey, Type = type, Handler = handler }; return(id); }
public async Task <IActionResult> CreateHook() { HookNotification createOrUpdateHookResponse = await this._orderFeedAPI.CreateOrUpdateHook(); Response.Headers.Add("Cache-Control", "private"); return(Json(createOrUpdateHookResponse)); }
public async Task <HookNotification> CreateOrUpdateHook() { // POST https://{accountName}.{environment}.com.br/api/orders/hook/config HookNotification createOrUpdateHookResponse = new HookNotification(); OrderHook orderHook = new OrderHook { Filter = new Filter { Status = new List <string> { Constants.Status.ReadyForHandling, Constants.Status.Invoiced } }, Hook = new Hook { Headers = new Headers { Key = Constants.EndPointKey }, Url = new Uri($"https://{this._httpContextAccessor.HttpContext.Request.Headers[Constants.VTEX_ACCOUNT_HEADER_NAME]}.myvtex.com/{Constants.AppName}") } }; var jsonSerializedOrderHook = JsonConvert.SerializeObject(orderHook); //Console.WriteLine($"Hook = {jsonSerializedOrderHook}"); //Console.WriteLine($"Url = http://{this._httpContextAccessor.HttpContext.Request.Headers[Constants.VTEX_ACCOUNT_HEADER_NAME]}.{Constants.ENVIRONMENT}.com.br/api/orders/hook/config"); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri($"http://{this._httpContextAccessor.HttpContext.Request.Headers[Constants.VTEX_ACCOUNT_HEADER_NAME]}.{Constants.ENVIRONMENT}.com.br/api/orders/hook/config"), Content = new StringContent(jsonSerializedOrderHook, Encoding.UTF8, Constants.APPLICATION_JSON) }; string authToken = this._httpContextAccessor.HttpContext.Request.Headers[Constants.HEADER_VTEX_CREDENTIAL]; if (authToken != null) { request.Headers.Add(Constants.AUTHORIZATION_HEADER_NAME, authToken); request.Headers.Add(Constants.PROXY_AUTHORIZATION_HEADER_NAME, authToken); } var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"[-] Response {response.StatusCode} Content = '{responseContent}' [-]"); createOrUpdateHookResponse = JsonConvert.DeserializeObject <HookNotification>(responseContent); return(createOrUpdateHookResponse); }
public async Task <bool> ProcessNotification(HookNotification hookNotification) { bool success = false; switch (hookNotification.Domain) { case StorePickUpConstants.Domain.Fulfillment: switch (hookNotification.State) { case StorePickUpConstants.Status.ReadyForHandling: VtexOrder vtexOrder = await this.GetOrderInformation(hookNotification.OrderId); if (vtexOrder != null && vtexOrder.ShippingData != null && vtexOrder.ShippingData.LogisticsInfo != null) { List <LogisticsInfo> pickUpItems = vtexOrder.ShippingData.LogisticsInfo.Where(i => i.Slas.Any(s => s.PickupStoreInfo.IsPickupStore)).ToList(); if (pickUpItems != null && pickUpItems.Count > 0) { Console.WriteLine($"{pickUpItems.Count} Items for pickup."); success = await this.SendEmail(StorePickUpConstants.MailTemplateType.ReadyForPacking, vtexOrder); if (success) { success = await this.AddOrderComment(StorePickUpConstants.OrderCommentText.ReadyForPacking, vtexOrder.OrderId); } } else { Console.WriteLine("No items for pickup."); success = true; } } break; default: Console.WriteLine($"State {hookNotification.State} not implemeted."); _context.Vtex.Logger.Info("ProcessNotification", null, $"State {hookNotification.State} not implemeted."); break; } break; case StorePickUpConstants.Domain.Marketplace: break; default: Console.WriteLine($"Domain {hookNotification.Domain} not implemeted."); _context.Vtex.Logger.Info("ProcessNotification", null, $"Domain {hookNotification.Domain} not implemeted."); break; } return(success); }
private void Push(JobId senderKey, MessageHook message, HookNotification h) { ErrorHandle.Expect(() => { h.Handler.DoHandle(senderKey, message); return(true); }, out bool anyError, string.Format(_errorInHanlder, senderKey.Id, senderKey.Name, message.Type, h.Handler.Id, h.Handler.Name), string.Format(_errorMessage, message.Text)); }
public async Task <bool> ProcessNotification(HookNotification hookNotification) { bool success = false; // Use our server - side Track API for the following: // Placed Order - When an order successfully processes on your system // Ordered Product - An event for each item in a processed order // Fulfilled Order - When an order is sent to the customer // Cancelled Order - When a customer cancels their order // Refunded Order - When a customer’s order is refunded string orderId = hookNotification.OrderId; DateTimeOffset lastChange = hookNotification.LastChange; KlaviyoEvent klaviyoEvent; VtexOrder vtexOrder = await _orderFeedAPI.GetOrderInformation(orderId); switch (hookNotification.Domain) { case Constants.Domain.Fulfillment: switch (hookNotification.State) { case Constants.Status.ReadyForHandling: klaviyoEvent = await BuildEvent(vtexOrder, Constants.Events.PlacedOrder, lastChange); if (klaviyoEvent != null) { success = await SendEvent(klaviyoEvent); // Send each item as a separate event foreach (Item item in vtexOrder.Items) { VtexOrder order = vtexOrder; order.Items = new List <Item> { item }; klaviyoEvent = await BuildEvent(vtexOrder, Constants.Events.OrderedProduct, lastChange); success = success && await SendEvent(klaviyoEvent); } } break; case Constants.Status.Invoiced: klaviyoEvent = await BuildEvent(vtexOrder, Constants.Events.FulfilledOrder, lastChange); if (klaviyoEvent != null) { success = await SendEvent(klaviyoEvent); } break; //case Constants.Status.Canceled: // break; default: Console.WriteLine($"State {hookNotification.State} not implemeted."); _context.Vtex.Logger.Info("ProcessNotification", null, $"State {hookNotification.State} not implemeted."); break; } break; case Constants.Domain.Marketplace: break; default: Console.WriteLine($"Domain {hookNotification.Domain} not implemeted."); _context.Vtex.Logger.Info("ProcessNotification", null, $"Domain {hookNotification.Domain} not implemeted."); break; } return(success); }