/// <inheritdoc/> public async Task ChangeQuantityAsync(WebhookPayload payload) { await this.NotifyAndAck( payload, new UpdateOperation { Quantity = payload.Quantity, Status = UpdateOperationStatusEnum.Success }, this.notificationHelper.NotifyChangeQuantityAsync); }
/// <inheritdoc/> public async Task UnsubscribedAsync(WebhookPayload payload) { await this.NotifyAndAck( payload, new UpdateOperation { Status = UpdateOperationStatusEnum.Success }, this.notificationHelper.NotifyUnsubscribedAsync); }
/// <inheritdoc/> public async Task ChangePlanAsync(WebhookPayload payload) { await this.NotifyAndAck( payload, new UpdateOperation { PlanId = payload.PlanId, Status = UpdateOperationStatusEnum.Success }, this.notificationHelper.NotifyChangePlanAsync); }
public async Task <bool> SendWebhookAsync(WebhookPayload payload, string url, IntegrationEventSubscription eventSubscription) { string payloadString = JsonConvert.SerializeObject(payload); var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (!String.IsNullOrEmpty(eventSubscription.HTTP_AddHeader_Key)) { httpWebRequest.Headers[eventSubscription.HTTP_AddHeader_Key] = eventSubscription?.HTTP_AddHeader_Value ?? ""; } string myJson = payloadString; using (var client = new HttpClient()) { var response = await client.PostAsync( url, new StringContent(myJson, Encoding.UTF8, "application/json")).ConfigureAwait(false); return(response.IsSuccessStatusCode); } }
public async Task HandleAsync(WebhookPayload payload) { var settings = await this.mediator.Send( new GetPullDogSettingsByGitHubInstallationIdQuery( payload.Installation.Id)); if (settings == null) { throw new InvalidOperationException($"Could not find Pull Dog settings for an installation ID of {payload.Installation.Id}."); } if (payload.RepositoriesRemoved != null) { foreach (var repository in payload.RepositoriesRemoved) { await this.mediator.Send(new DeletePullDogRepositoryCommand( repository.Id.ToString(CultureInfo.InvariantCulture))); } } if (payload.RepositoriesAdded != null) { await this.mediator.Send( new AddPullDogToGitHubRepositoriesCommand( payload.Installation.Id, settings, payload.RepositoriesAdded .Select(x => x.Id) .ToArray())); } }
private async Task SendWebhookNotificationEmailAsync( string subject, string mailBody, string actionName, WebhookPayload payload, CancellationToken cancellationToken) { var queryParams = new List <Tuple <string, string> > { new Tuple <string, string>("subscriptionId", payload.SubscriptionId.ToString()), new Tuple <string, string>("publisherId", payload.PublisherId), new Tuple <string, string>("offerId", payload.OfferId), new Tuple <string, string>("planId", payload.PlanId), new Tuple <string, string>("quantity", payload.Quantity.ToString()), new Tuple <string, string>("operationId", payload.OperationId.ToString()) }; var subscriptionDetails = await this.fulfillmentClient.GetSubscriptionAsync( payload.SubscriptionId, Guid.Empty, Guid.Empty, cancellationToken); await this.SendEmailAsync( () => $"{subject}, {subscriptionDetails.Name}", () => $"<p>{mailBody}" + $"{this.BuildALink(actionName, queryParams, "Click here to confirm.")}</p>" + $"<br/><div> Details are {BuildTable(JObject.Parse(JsonConvert.SerializeObject(subscriptionDetails)))}</div>", cancellationToken); }
/// <inheritdoc/> public async Task ChangeQuantityAsync(WebhookPayload payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } if (payload.Status == OperationStatusEnum.Succeeded) { Microsoft.Rest.Azure.AzureOperationResponse response = await this.marketplaceClient.SubscriptionOperations.UpdateOperationStatusWithHttpMessagesAsync( payload.SubscriptionId, payload.OperationId, null, null, null, payload.Quantity, UpdateOperationStatusEnum.Success).ConfigureAwait(false); // Change request is complete if (response.Response.IsSuccessStatusCode) { await this.notificationHelper.NotifyChangeQuantityAsync(payload).ConfigureAwait(false); } } else if (payload.Status == OperationStatusEnum.Conflict || payload.Status == OperationStatusEnum.Failed) { await this.notificationHelper.ProcessOperationFailOrConflictAsync(payload).ConfigureAwait(false); } }
/// <inheritdoc/> public async Task ProcessOperationFailOrConflictAsync( WebhookPayload payload, CancellationToken cancellationToken = default) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } var notificationModel = NotificationModel.FromWebhookPayload(payload); var queryParams = new List <Tuple <string, string> > { new Tuple <string, string>( "subscriptionId", notificationModel.SubscriptionId.ToString()), }; var subscriptionDetails = await this.marketplaceClient.FulfillmentOperations.GetSubscriptionAsync( notificationModel.SubscriptionId, Guid.Empty, Guid.Empty, cancellationToken).ConfigureAwait(false); await this.SendEmailAsync( () => $"Operation failure, {subscriptionDetails.Name}", () => $"<p>Operation failure. {this.BuildALink("Operations", queryParams, "Click here to list all operations for this subscription", "Subscriptions")}</p>. " + $"<p> Details are {BuildTable(JObject.Parse(JsonConvert.SerializeObject(subscriptionDetails)))}</p>", cancellationToken).ConfigureAwait(false); }
private void PostMessages(IEnumerable <Webhook> webhooks, WebhookPayload payload) { foreach (var webhook in webhooks) { PostMessage(webhook.WebhookUrl, payload); } }
public ActionResult <WebhookPayload> InsertDataFromCalendly(WebhookPayload payload) { var client = new RestClient("https://www.bshpersona.com/personaAPI/data/LeadSubmitData"); // need to transform the requestObj var requestObj = new { userID = string.Empty, promoID = "192", sessionID = string.Empty, firstName = payload.payload.invitee.name, lastName = payload.payload.invitee.last_name, email = payload.payload.invitee.email, phone = payload.payload.questions_and_answers.Where(e => e.question.Equals("Phone", StringComparison.OrdinalIgnoreCase)).Select(y => y.answer).FirstOrDefault(), zipCode = payload.payload.questions_and_answers.Where(e => e.question.Equals("Postal Code", StringComparison.OrdinalIgnoreCase)).Select(y => y.answer).FirstOrDefault(), }; var payLoad = CommonUtils.Functions.JSONtoStringConvertMethod(requestObj); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", payLoad, ParameterType.RequestBody); IRestResponse response = client.Execute(request); return(payload); }
/// <summary> /// Unsubscribed the asynchronous. /// </summary> /// <param name="payload">The payload.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task UnsubscribedAsync(WebhookPayload payload) { var oldValue = this.subscriptionService.GetSubscriptionsBySubscriptionId(payload.SubscriptionId); this.subscriptionService.UpdateStateOfSubscription(payload.SubscriptionId, SubscriptionStatusEnumExtension.Unsubscribed.ToString(), false); this.applicationLogService.AddApplicationLog("Offer Successfully UnSubscribed."); if (oldValue != null) { SubscriptionAuditLogs auditLog = new SubscriptionAuditLogs() { Attribute = Convert.ToString(SubscriptionLogAttributes.Status), SubscriptionId = oldValue.SubscribeId, NewValue = Convert.ToString(SubscriptionStatusEnum.Unsubscribed), OldValue = Convert.ToString(oldValue.SaasSubscriptionStatus), CreateBy = null, CreateDate = DateTime.Now, }; this.subscriptionsLogRepository.Save(auditLog); } this.notificationStatusHandlers.Process(payload.SubscriptionId); await Task.CompletedTask; }
public async Task ReinstatedAsync(WebhookPayload payload) { if (payload.Status == SaaSFulfillmentClient.Models.OperationStatusEnum.Succeeded) { var reinsteateResult = await this.subscriptionManager.ReactivateSubscriptionAsync(payload.SubscriptionId); if (reinsteateResult.Succeeded) { await this.fulfillmentClient.UpdateSubscriptionOperationAsync( payload.SubscriptionId, payload.OperationId, new OperationUpdate() { PlanId = payload.PlanId, Quantity = payload.Quantity, Status = OperationUpdateStatusEnum.Success }, Guid.Empty, Guid.Empty, CancellationToken.None); this.logger.LogInformation( $"Subscription {payload.SubscriptionId} successfully reinstated."); } else { this.logger.LogError( $"Cannot reinstate subscription {payload.SubscriptionId}. Error details are {reinsteateResult}"); } } }
public async Task PostToWebhook_RapidlyTooManyTimes_RateLimitingShouldOccur() { // Arrange var request = new WebhookPayload { Repository = new Repository { Name = "test-app", FullName = "organization/test-app" } }; var header = GetSignatureHeader(request, "Webhook"); // Act for (int i = 0; i < 5; i++) { await TestClient.PostAsJsonAsync("api/release/test-app", request); } var response = await TestClient.PostAsJsonAsync("api/release/test-app", request, header); // Assert response.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); }
private string?ExtractCommentTextFromPayload(WebhookPayload payload) { var text = payload .Comment? .Body? .Trim(); var environmentNameSuffix = $" {this.hostEnvironment.EnvironmentName}"; if (text?.EndsWith(environmentNameSuffix, StringComparison.InvariantCultureIgnoreCase) == true) { text = text.Substring(0, text.LastIndexOf( environmentNameSuffix, StringComparison.InvariantCultureIgnoreCase)); } while (text?.Contains(" ", StringComparison.InvariantCulture) == true) { text = text.Replace(" ", " ", StringComparison.InvariantCulture); } text = text? .Trim()? .ToLowerInvariant(); return(text); }
private static async Task EnqueueAlertEmails(FuncContext context, WebhookPayload payload) { var e = payload.EventData.Event; var subject = $"{e.ToEmoji()} Mailgun Alert ({e})"; var bodyJson = Utils.ToJson(payload.EventData); if (context.SpamFilter.IsSpam(payload)) { context.Logger.LogInformation("Spam filter tripped."); return; } foreach (var email in context.Config.AlertEmailAddresses) { var msg = new EmailMessage { From = context.Config.FromEmailAddress, To = email, Subject = subject, Body = bodyJson }; await context.EmailQueue.AddAsync(msg); } }
public async Task <IActionResult> Index([FromBody] WebhookPayload payload) { _logger.LogInformation($"Received webhook request: {JsonSerializer.Serialize(payload)}"); await _webhookProcessor.ProcessWebhookNotificationAsync(payload); return(this.Ok()); }
public async Task <IActionResult> Index([FromBody] WebhookPayload payload) { // Options is injected as a singleton. This is not a good hack, but need to pass the host name and port this.options.BaseUrl = $"{this.Request.Scheme}://{this.Request.Host}/"; await this.webhookProcessor.ProcessWebhookNotificationAsync(payload); return(this.Ok()); }
public object HandleGenericWebhook([FromBody] WebhookPayload payload) { return(new { Action = "HandleGenericWebhook", City = payload.Request.Body.City, Foo = payload.ConfigData.Foo }); }
public void SerializePayload_ShouldWork() { Product product = _products[0]; WebhookPayload payload = new WebhookPayload(product); string json = payload.SerializePayload(); Assert.True(json.Length > 0); }
public async Task ChangeQuantityAsync(WebhookPayload payload) { if (payload.Status == SaaSFulfillmentClient.Models.OperationStatusEnum.Succeeded) { // The sample does not have seat based skus. Not implementing this for now this.logger.LogInformation("Current implementation does not include a seat based SKU."); await Task.CompletedTask; } }
private async Task SendProduct(Product product) { IConfigurationSection cfgColors = _config.GetSection("BackgroundColors"); List <Webhook> webhooks = GetWebhooks(); WebhookPayload payload = new WebhookPayload(product); Dictionary <string, int> colors = cfgColors.Get <Dictionary <string, int> >(); List <Webhook> webhooksInArchive = _archive.GetWebhooksOfProduct(product.ProductUrl); foreach (Embed embed in payload.embeds) { string[] elems = product.MachineName.Split("_"); string key = elems[elems.Length - 1]; if (colors.ContainsKey(key)) { embed.color = colors[key]; } } List <Task> tasks = new List <Task>(); List <Webhook> sentWebhooks = new List <Webhook>(); try { foreach (Webhook wh in webhooks) { if (webhooksInArchive.Any(w => w.Hash == wh.Hash) == false) { tasks.Add(SendWebhook(wh.url, payload)); sentWebhooks.Add(wh); } } await Task.WhenAll(tasks); } catch (Exception e) { Log.Logger.Error(e.Message); } finally { UrlWithWebhooks productLabel = new UrlWithWebhooks(); productLabel.Webhooks = webhooksInArchive; productLabel.Url = product.ProductUrl; for (int i = 0; i < tasks.Count; i++) { if (tasks[i].IsCompletedSuccessfully) { productLabel.Webhooks.Add(sentWebhooks[i]); } } if (productLabel.Webhooks.Count > 0) { _archive.AddUrl(productLabel); } } }
public async Task <IActionResult> Index([FromBody] WebhookPayload payload) { // Options is injected as a singleton. This is not a good hack, but need to pass the host name and port this.options.BaseUrl = $"{this.Request.Scheme}://{this.Request.Host}/"; await this.webhookProcessor.ProcessWebhookNotificationAsync(payload); this.logger.LogInformation($"Received webhook request: {JsonConvert.SerializeObject(payload)}"); return(this.Ok()); }
private async Task SendWebhookNotificationMessageAsync(WebhookPayload message, CancellationToken cancellationToken) { if (message == null) { throw new ArgumentNullException(nameof(message)); } await this.queueClient.SendMessageAsync(JsonConvert.SerializeObject(message), cancellationToken).ConfigureAwait(false); }
public async Task ProcessSuspendedAsync(WebhookPayload payload, CancellationToken cancellationToken = default) { await this.SendWebhookNotificationEmailAsync( "Suspend subscription request", "Suspend subscription request. Please take the required action, then return to this email and click the following link to confirm.", "SuspendSubscription", payload, cancellationToken); }
/// <inheritdoc/> public async Task NotifyChangeQuantityAsync(WebhookPayload payload, CancellationToken cancellationToken = default) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } await this.SendWebhookNotificationMessageAsync( payload, cancellationToken).ConfigureAwait(false); }
/// <inheritdoc/> public async Task ProcessOperationFailOrConflictAsync(WebhookPayload payload, CancellationToken cancellationToken = default) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } await this.SendWebhookNotificationMessageAsync( payload, cancellationToken); }
/// <inheritdoc/> public async Task NotifyUnsubscribedAsync(WebhookPayload payload, CancellationToken cancellationToken = default) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } await this.SendWebhookNotificationMessageAsync( payload, cancellationToken); }
/// <summary> /// Posts the specified request. /// </summary> /// <param name="request">The request.</param> public async void Post(WebhookPayload request) { this.applicationLogService.AddApplicationLog("The azure Webhook Triggered."); if (request != null) { var json = JsonSerializer.Serialize(request); this.applicationLogService.AddApplicationLog("Webhook Serialize Object " + json); await this.webhookProcessor.ProcessWebhookNotificationAsync(request).ConfigureAwait(false); } }
public WebhookPayloadContext( WebhookPayload payload, PullDogSettings settings, PullDogRepository repository, PullDogPullRequest pullRequest) { this.Payload = payload; this.Settings = settings; this.Repository = repository; this.PullRequest = pullRequest; }
public async Task ProcessChangeQuantityAsync( WebhookPayload payload, CancellationToken cancellationToken = default) { await this.SendWebhookNotificationEmailAsync( "Quantity change request", "Quantity change request. Please take the required action, then return to this email and click the following link to confirm.", "QuantityChange", payload, cancellationToken); }