From fbb2dc5c811148f8fb60d13830d044572d8a473d Mon Sep 17 00:00:00 2001 From: Gabriel Odero Date: Thu, 2 May 2024 01:11:41 +0300 Subject: [PATCH] Added additional parameters for media download async method --- .../Controllers/HomeController.cs | 2351 +++++++++-------- .../WhatsAppBusinessCloudAPI.Web/Program.cs | 28 +- .../ViewModel/SendTextMessageViewModel.cs | 4 +- .../Views/Home/BulkSendWhatsApps.cshtml | 2 +- .../Interfaces/IWhatsAppBusinessClient.cs | 4 +- .../WhatsAppBusinessClient.cs | 21 +- .../WhatsappBusiness.CloudApi.csproj | 2 +- 7 files changed, 1232 insertions(+), 1180 deletions(-) diff --git a/Samples/WhatsAppBusinessCloudAPI.Web/Controllers/HomeController.cs b/Samples/WhatsAppBusinessCloudAPI.Web/Controllers/HomeController.cs index a73c848..157626f 100644 --- a/Samples/WhatsAppBusinessCloudAPI.Web/Controllers/HomeController.cs +++ b/Samples/WhatsAppBusinessCloudAPI.Web/Controllers/HomeController.cs @@ -1,10 +1,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using System; using System.Diagnostics; -using System.Text; using WhatsappBusiness.CloudApi; using WhatsappBusiness.CloudApi.AccountMetrics; using WhatsappBusiness.CloudApi.Configurations; @@ -25,7 +22,6 @@ public class HomeController : Controller private readonly IWhatsAppBusinessClient _whatsAppBusinessClient; private readonly WhatsAppBusinessCloudApiConfig _whatsAppConfig; private readonly IWebHostEnvironment _environment; - private readonly SendMessageController _sendMessageController; public HomeController(ILogger logger, IWhatsAppBusinessClient whatsAppBusinessClient, IOptions whatsAppConfig, IWebHostEnvironment environment) @@ -34,8 +30,6 @@ public HomeController(ILogger logger, IWhatsAppBusinessClient wh _whatsAppBusinessClient = whatsAppBusinessClient; _whatsAppConfig = whatsAppConfig.Value; _environment = environment; - - _sendMessageController = new(_logger, _whatsAppBusinessClient, _environment); } public IActionResult Index() @@ -48,60 +42,173 @@ public IActionResult SendWhatsAppTextMessage() return View(); } - public IActionResult SendWhatsAppMediaMessage() + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppTextMessage(SendTextMessageViewModel sendTextMessageViewModel) { - SendMediaMessageViewModel sendMediaMessageViewModel = new SendMediaMessageViewModel - { - MediaType = new List() - { - new SelectListItem(){ Text = "Audio", Value = enumMessageType.Audio.ToString() }, - new SelectListItem(){ Text = "Document", Value = enumMessageType.Doc.ToString() }, - new SelectListItem(){ Text = "Image", Value = enumMessageType.Image.ToString() }, - //new SelectListItem(){ Text = "Sticker", Value = enumMessageType.Sticker.ToString() }, - new SelectListItem(){ Text = "Video", Value = enumMessageType.Video.ToString() }, - } - }; - - return View(sendMediaMessageViewModel); + try + { + TextMessageRequest textMessageRequest = new TextMessageRequest(); + textMessageRequest.To = sendTextMessageViewModel.RecipientPhoneNumber; + textMessageRequest.Text = new WhatsAppText(); + textMessageRequest.Text.Body = sendTextMessageViewModel.Message; + textMessageRequest.Text.PreviewUrl = false; + + var results = await _whatsAppBusinessClient.SendTextMessageAsync(textMessageRequest); + + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent text message"); + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return View().WithDanger("Error", ex.Message); + } } - /// - /// This is now using SendMessageController - /// This will send Audio, Document, Image, Sticker, Video - /// This is NOT to send Templates with the above media - /// - /// - /// - [HttpPost] + public IActionResult SendWhatsAppMediaMessage() + { + SendMediaMessageViewModel sendMediaMessageViewModel = new SendMediaMessageViewModel(); + sendMediaMessageViewModel.MediaType = new List() + { + new SelectListItem(){ Text = "Audio", Value = "Audio" }, + new SelectListItem(){ Text = "Document", Value = "Document" }, + new SelectListItem(){ Text = "Image", Value = "Image" }, + new SelectListItem(){ Text = "Sticker", Value = "Sticker" }, + new SelectListItem(){ Text = "Video", Value = "Video" }, + }; + + return View(sendMediaMessageViewModel); + } + + [HttpPost] [ValidateAntiForgeryToken] public async Task SendWhatsAppMediaMessage(SendMediaMessageViewModel sendMediaMessage) { - try - { - SendWhatsAppPayload payload = new SendWhatsAppPayload(); - payload.SendText = new SendTextPayload() - { - ToNum = sendMediaMessage.RecipientPhoneNumber, - Message = sendMediaMessage.Message - }; - payload.MessageType = (enumMessageType)Enum.Parse(typeof(enumMessageType), sendMediaMessage.SelectedMediaType); - - //payload.MessageType = sendMediaMessage.SelectedMediaType; - payload.Media = new WhatsAppMedia() - { - Type = "", - URL = sendMediaMessage.MediaLink, - ID = sendMediaMessage.MediaId, - Caption = sendMediaMessage.Message - }; - - // Send the message and get the WAMId - string WAMIds = _sendMessageController.GetWAMId((await _sendMessageController.SendWhatsApp_MediaAsync(payload)).Value); - - - if (WAMIds != null) + try + { + WhatsAppResponse results = null; + switch (sendMediaMessage.SelectedMediaType) { - return RedirectToAction(nameof(Index)).WithSuccess("Success", $"Successfully sent media message with WAMId '{WAMIds}'"); + case "Audio": + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaId)) + { + AudioMessageByIdRequest audioMessage = new AudioMessageByIdRequest(); + audioMessage.To = sendMediaMessage.RecipientPhoneNumber; + audioMessage.Audio = new MediaAudio(); + audioMessage.Audio.Id = sendMediaMessage.MediaId; + + results = await _whatsAppBusinessClient.SendAudioAttachmentMessageByIdAsync(audioMessage); + } + + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaLink)) + { + AudioMessageByUrlRequest audioMessage = new AudioMessageByUrlRequest(); + audioMessage.To = sendMediaMessage.RecipientPhoneNumber; + audioMessage.Audio = new MediaAudioUrl(); + audioMessage.Audio.Link = sendMediaMessage.MediaLink; + + results = await _whatsAppBusinessClient.SendAudioAttachmentMessageByUrlAsync(audioMessage); + } + break; + + case "Document": + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaId)) + { + DocumentMessageByIdRequest documentMessage = new DocumentMessageByIdRequest(); + documentMessage.To = sendMediaMessage.RecipientPhoneNumber; + documentMessage.Document = new MediaDocument(); + documentMessage.Document.Id = sendMediaMessage.MediaId; + documentMessage.Document.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendDocumentAttachmentMessageByIdAsync(documentMessage); + } + + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaLink)) + { + DocumentMessageByUrlRequest documentMessage = new DocumentMessageByUrlRequest(); + documentMessage.To = sendMediaMessage.RecipientPhoneNumber; + documentMessage.Document = new MediaDocumentUrl(); + documentMessage.Document.Link = sendMediaMessage.MediaLink; + documentMessage.Document.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendDocumentAttachmentMessageByUrlAsync(documentMessage); + } + break; + + case "Image": + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaId)) + { + ImageMessageByIdRequest imageMessage = new ImageMessageByIdRequest(); + imageMessage.To = sendMediaMessage.RecipientPhoneNumber; + imageMessage.Image = new MediaImage(); + imageMessage.Image.Id = sendMediaMessage.MediaId; + imageMessage.Image.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendImageAttachmentMessageByIdAsync(imageMessage); + } + + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaLink)) + { + ImageMessageByUrlRequest imageMessage = new ImageMessageByUrlRequest(); + imageMessage.To = sendMediaMessage.RecipientPhoneNumber; + imageMessage.Image = new MediaImageUrl(); + imageMessage.Image.Link = sendMediaMessage.MediaLink; + imageMessage.Image.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendImageAttachmentMessageByUrlAsync(imageMessage); + } + break; + + case "Sticker": + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaId)) + { + StickerMessageByIdRequest stickerMessage = new StickerMessageByIdRequest(); + stickerMessage.To = sendMediaMessage.RecipientPhoneNumber; + stickerMessage.Sticker = new MediaSticker(); + stickerMessage.Sticker.Id = sendMediaMessage.MediaId; + + results = await _whatsAppBusinessClient.SendStickerMessageByIdAsync(stickerMessage); + } + + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaLink)) + { + StickerMessageByUrlRequest stickerMessage = new StickerMessageByUrlRequest(); + stickerMessage.To = sendMediaMessage.RecipientPhoneNumber; + stickerMessage.Sticker = new MediaStickerUrl(); + stickerMessage.Sticker.Link = sendMediaMessage.MediaLink; + + results = await _whatsAppBusinessClient.SendStickerMessageByUrlAsync(stickerMessage); + } + break; + + case "Video": + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaId)) + { + VideoMessageByIdRequest videoMessage = new VideoMessageByIdRequest(); + videoMessage.To = sendMediaMessage.RecipientPhoneNumber; + videoMessage.Video = new MediaVideo(); + videoMessage.Video.Id = sendMediaMessage.MediaId; + videoMessage.Video.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendVideoAttachmentMessageByIdAsync(videoMessage); + } + + if (!string.IsNullOrWhiteSpace(sendMediaMessage.MediaLink)) + { + VideoMessageByUrlRequest videoMessage = new VideoMessageByUrlRequest(); + videoMessage.To = sendMediaMessage.RecipientPhoneNumber; + videoMessage.Video = new MediaVideoUrl(); + videoMessage.Video.Link = sendMediaMessage.MediaLink; + videoMessage.Video.Caption = sendMediaMessage.Message; + + results = await _whatsAppBusinessClient.SendVideoAttachmentMessageByUrlAsync(videoMessage); + } + break; + } + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent media message"); } else { @@ -126,19 +233,15 @@ public async Task SendWhatsAppLocationMessage(SendLocationMessage { try { - LocationMessageRequest locationMessageRequest = new LocationMessageRequest - { - To = sendLocationMessageViewModel.RecipientPhoneNumber, - Location = new Location - { - Name = "Location Test", - Address = "Address Test", - Longitude = sendLocationMessageViewModel.Longitude, - Latitude = sendLocationMessageViewModel.Latitude - } - }; - - var results = await _whatsAppBusinessClient.SendLocationMessageAsync(locationMessageRequest); + LocationMessageRequest locationMessageRequest = new LocationMessageRequest(); + locationMessageRequest.To = sendLocationMessageViewModel.RecipientPhoneNumber; + locationMessageRequest.Location = new Location(); + locationMessageRequest.Location.Name = "Location Test"; + locationMessageRequest.Location.Address = "Address Test"; + locationMessageRequest.Location.Longitude = sendLocationMessageViewModel.Longitude; + locationMessageRequest.Location.Latitude = sendLocationMessageViewModel.Latitude; + + var results = await _whatsAppBusinessClient.SendLocationMessageAsync(locationMessageRequest); return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent location message"); } @@ -151,16 +254,14 @@ public async Task SendWhatsAppLocationMessage(SendLocationMessage public IActionResult SendWhatsAppInteractiveMessage() { - SendInteractiveMessageViewModel sendInteractiveMessageViewModel = new SendInteractiveMessageViewModel - { - InteractiveType = new List() - { - new SelectListItem(){ Text = "List Message", Value = "List Message" }, - new SelectListItem(){ Text = "Reply Button", Value = "Reply Button" }, - new SelectListItem(){ Text = "Location Request Message", Value = "Location Request Message" } - } - }; - return View(sendInteractiveMessageViewModel); + SendInteractiveMessageViewModel sendInteractiveMessageViewModel = new SendInteractiveMessageViewModel(); + sendInteractiveMessageViewModel.InteractiveType = new List() + { + new SelectListItem(){ Text = "List Message", Value = "List Message" }, + new SelectListItem(){ Text = "Reply Button", Value = "Reply Button" }, + new SelectListItem(){ Text = "Location Request Message", Value = "Location Request Message" } + }; + return View(sendInteractiveMessageViewModel); } [HttpPost] @@ -173,149 +274,121 @@ public async Task SendWhatsAppInteractiveMessage(SendInteractiveM if (sendInteractiveMessageViewModel.SelectedInteractiveType.Equals("List Message")) { - InteractiveListMessageRequest interactiveListMessage = new InteractiveListMessageRequest - { - To = sendInteractiveMessageViewModel.RecipientPhoneNumber, - Interactive = new InteractiveListMessage - { - Header = new Header - { - Type = "text", - Text = "List Header Sample Test" - }, - - Body = new ListBody - { - Text = sendInteractiveMessageViewModel.Message - }, - - Footer = new Footer - { - Text = "List Footer Sample Test" - }, - - Action = new ListAction - { - Button = "Send", - Sections = new List
() - { - new Section() - { - Title = "Category A", - Rows = new List() - { - new Row() - { - Id = "Item_A1", - Title = "Apples", - Description = "Enjoy fruits for free" - }, - new Row() - { - Id = "Item_A2", - Title = "Tangerines", - Description = "Enjoy fruits for free" - }, - }, - }, - new Section() - { - Title = "Category B", - Rows = new List() - { - new Row() - { - Id = "Item_B1", - Title = "2JZ", - Description = "Engine discounts" - }, - new Row() - { - Id = "Item_2", - Title = "1JZ", - Description = "Engine discounts" - }, - } - } - } - } - } - }; + InteractiveListMessageRequest interactiveListMessage = new InteractiveListMessageRequest(); + interactiveListMessage.To = sendInteractiveMessageViewModel.RecipientPhoneNumber; + interactiveListMessage.Interactive = new InteractiveListMessage(); + + interactiveListMessage.Interactive.Header = new Header(); + interactiveListMessage.Interactive.Header.Type = "text"; + interactiveListMessage.Interactive.Header.Text = "List Header Sample Test"; + + interactiveListMessage.Interactive.Body = new ListBody(); + interactiveListMessage.Interactive.Body.Text = sendInteractiveMessageViewModel.Message; + + interactiveListMessage.Interactive.Footer = new Footer(); + interactiveListMessage.Interactive.Footer.Text = "List Footer Sample Test"; + + interactiveListMessage.Interactive.Action = new ListAction(); + interactiveListMessage.Interactive.Action.Button = "Send"; + interactiveListMessage.Interactive.Action.Sections = new List
() + { + new Section() + { + Title = "Category A", + Rows = new List() + { + new Row() + { + Id = "Item_A1", + Title = "Apples", + Description = "Enjoy fruits for free" + }, + new Row() + { + Id = "Item_A2", + Title = "Tangerines", + Description = "Enjoy fruits for free" + }, + }, + }, + new Section() + { + Title = "Category B", + Rows = new List() + { + new Row() + { + Id = "Item_B1", + Title = "2JZ", + Description = "Engine discounts" + }, + new Row() + { + Id = "Item_2", + Title = "1JZ", + Description = "Engine discounts" + }, + } + } + }; - results = await _whatsAppBusinessClient.SendInteractiveListMessageAsync(interactiveListMessage); + results = await _whatsAppBusinessClient.SendInteractiveListMessageAsync(interactiveListMessage); } if (sendInteractiveMessageViewModel.SelectedInteractiveType.Equals("Reply Button")) { - InteractiveReplyButtonMessageRequest interactiveReplyButtonMessage = new InteractiveReplyButtonMessageRequest - { - To = sendInteractiveMessageViewModel.RecipientPhoneNumber, - Interactive = new InteractiveReplyButtonMessage - { - Header = new ReplyButtonHeader - { - Type = "text", - Text = "Reply Button Header Sample Test" - }, - - Body = new ReplyButtonBody - { - Text = sendInteractiveMessageViewModel.Message - }, - - Footer = new ReplyButtonFooter - { - Text = "Reply Button Footer Sample Test" - }, - - Action = new ReplyButtonAction - { - Buttons = new List() - { - new ReplyButton() - { - Type = "reply", - Reply = new Reply() - { - Id = "SAMPLE_1_CLICK", - Title = "CLICK ME!!!" - } - }, - - new ReplyButton() - { - Type = "reply", - Reply = new Reply() - { - Id = "SAMPLE_2_CLICK", - Title = "LATER" - } - } - } - } - } - }; + InteractiveReplyButtonMessageRequest interactiveReplyButtonMessage = new InteractiveReplyButtonMessageRequest(); + interactiveReplyButtonMessage.To = sendInteractiveMessageViewModel.RecipientPhoneNumber; + interactiveReplyButtonMessage.Interactive = new InteractiveReplyButtonMessage(); + + interactiveReplyButtonMessage.Interactive.Header = new ReplyButtonHeader(); + interactiveReplyButtonMessage.Interactive.Header.Type = "text"; + interactiveReplyButtonMessage.Interactive.Header.Text = "Reply Button Header Sample Test"; - results = await _whatsAppBusinessClient.SendInteractiveReplyButtonMessageAsync(interactiveReplyButtonMessage); + interactiveReplyButtonMessage.Interactive.Body = new ReplyButtonBody(); + interactiveReplyButtonMessage.Interactive.Body.Text = sendInteractiveMessageViewModel.Message; + + interactiveReplyButtonMessage.Interactive.Footer = new ReplyButtonFooter(); + interactiveReplyButtonMessage.Interactive.Footer.Text = "Reply Button Footer Sample Test"; + + interactiveReplyButtonMessage.Interactive.Action = new ReplyButtonAction(); + interactiveReplyButtonMessage.Interactive.Action.Buttons = new List() + { + new ReplyButton() + { + Type = "reply", + Reply = new Reply() + { + Id = "SAMPLE_1_CLICK", + Title = "CLICK ME!!!" + } + }, + + new ReplyButton() + { + Type = "reply", + Reply = new Reply() + { + Id = "SAMPLE_2_CLICK", + Title = "LATER" + } + } + }; + + results = await _whatsAppBusinessClient.SendInteractiveReplyButtonMessageAsync(interactiveReplyButtonMessage); } if (sendInteractiveMessageViewModel.SelectedInteractiveType.Equals("Location Request Message")) { - InteractiveLocationMessageRequest interactiveLocationMessageRequest = new InteractiveLocationMessageRequest - { - To = sendInteractiveMessageViewModel.RecipientPhoneNumber, - Interactive = new InteractiveLocationRequestMessage - { - Body = new InteractiveLocationBody - { - Text = (!string.IsNullOrWhiteSpace(sendInteractiveMessageViewModel.Message)) ? sendInteractiveMessageViewModel.Message : "Let us start with your pickup. You can either manually *enter an address* or *share your current location*." - }, - Action = new InteractiveLocationAction() - } - }; - - results = await _whatsAppBusinessClient.SendLocationRequestMessageAsync(interactiveLocationMessageRequest); - } + InteractiveLocationMessageRequest interactiveLocationMessageRequest = new InteractiveLocationMessageRequest(); + interactiveLocationMessageRequest.To = sendInteractiveMessageViewModel.RecipientPhoneNumber; + interactiveLocationMessageRequest.Interactive = new InteractiveLocationRequestMessage(); + interactiveLocationMessageRequest.Interactive.Body = new InteractiveLocationBody(); + interactiveLocationMessageRequest.Interactive.Body.Text = (!string.IsNullOrWhiteSpace(sendInteractiveMessageViewModel.Message)) ? sendInteractiveMessageViewModel.Message : "Let us start with your pickup. You can either manually *enter an address* or *share your current location*."; + interactiveLocationMessageRequest.Interactive.Action = new InteractiveLocationAction(); + + results = await _whatsAppBusinessClient.SendLocationRequestMessageAsync(interactiveLocationMessageRequest); + } if (results != null) { @@ -335,20 +408,18 @@ public async Task SendWhatsAppInteractiveMessage(SendInteractiveM public IActionResult SendWhatsAppFlowMessage() { - SendFlowMessageViewModel sendFlowMessageViewModel = new SendFlowMessageViewModel - { - FlowAction = new List() - { - new SelectListItem(){ Text = "Navigate", Value = "navigate" }, - new SelectListItem(){ Text = "Data Exchange", Value = "data_exchange" } - }, - Mode = new List() - { - new SelectListItem(){ Text = "Draft", Value = "Draft" }, - new SelectListItem(){ Text = "Published", Value = "Published" } - } - }; - return View(sendFlowMessageViewModel); + SendFlowMessageViewModel sendFlowMessageViewModel = new SendFlowMessageViewModel(); + sendFlowMessageViewModel.FlowAction = new List() + { + new SelectListItem(){ Text = "Navigate", Value = "navigate" }, + new SelectListItem(){ Text = "Data Exchange", Value = "data_exchange" } + }; + sendFlowMessageViewModel.Mode = new List() + { + new SelectListItem(){ Text = "Draft", Value = "Draft" }, + new SelectListItem(){ Text = "Published", Value = "Published" } + }; + return View(sendFlowMessageViewModel); } [HttpPost] @@ -357,141 +428,143 @@ public async Task SendWhatsAppFlowMessage(SendFlowMessageViewMode { try { - FlowMessageRequest flowMessageRequest = new FlowMessageRequest - { - To = sendFlowMessageViewModel.RecipientPhoneNumber, - Interactive = new FlowMessageInteractive - { - Header = new FlowMessageHeader - { - Type = "text", - Text = "Header flow" - }, - - Body = new FlowMessageBody - { - Text = "Body flow" - }, - - Footer = new FlowMessageFooter - { - Text = "Footer flow" - }, - - Action = new FlowMessageAction - { - Parameters = new FlowMessageParameters - { - FlowToken = sendFlowMessageViewModel.FlowToken, - FlowId = sendFlowMessageViewModel.FlowId, - FlowCta = sendFlowMessageViewModel.FlowButtonText, - FlowAction = sendFlowMessageViewModel.SelectedFlowAction, - IsInDraftMode = (sendFlowMessageViewModel.SelectedMode.Equals("Draft", StringComparison.OrdinalIgnoreCase)), - - FlowActionPayload = new FlowActionPayload - { - Screen = sendFlowMessageViewModel.ScreenId - } - } - } - } - }; + FlowMessageRequest flowMessageRequest = new FlowMessageRequest(); + flowMessageRequest.To = sendFlowMessageViewModel.RecipientPhoneNumber; + flowMessageRequest.Interactive = new FlowMessageInteractive(); - var results = await _whatsAppBusinessClient.SendFlowMessageAsync(flowMessageRequest); + flowMessageRequest.Interactive.Header = new FlowMessageHeader(); + flowMessageRequest.Interactive.Header.Type = "text"; + flowMessageRequest.Interactive.Header.Text = "Header flow"; - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent flow message"); - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppFlowMessage)).WithDanger("Error", ex.Message); - } - } + flowMessageRequest.Interactive.Body = new FlowMessageBody(); + flowMessageRequest.Interactive.Body.Text = "Body flow"; + + flowMessageRequest.Interactive.Footer = new FlowMessageFooter(); + flowMessageRequest.Interactive.Footer.Text = "Footer flow"; + + flowMessageRequest.Interactive.Action = new FlowMessageAction(); + flowMessageRequest.Interactive.Action.Parameters = new FlowMessageParameters(); + flowMessageRequest.Interactive.Action.Parameters.FlowToken = sendFlowMessageViewModel.FlowToken; + flowMessageRequest.Interactive.Action.Parameters.FlowId = sendFlowMessageViewModel.FlowId; + flowMessageRequest.Interactive.Action.Parameters.FlowCta = sendFlowMessageViewModel.FlowButtonText; + flowMessageRequest.Interactive.Action.Parameters.FlowAction = sendFlowMessageViewModel.SelectedFlowAction; + flowMessageRequest.Interactive.Action.Parameters.IsInDraftMode = (sendFlowMessageViewModel.SelectedMode.Equals("Draft", StringComparison.OrdinalIgnoreCase)); + + flowMessageRequest.Interactive.Action.Parameters.FlowActionPayload = new FlowActionPayload(); + flowMessageRequest.Interactive.Action.Parameters.FlowActionPayload.Screen = sendFlowMessageViewModel.ScreenId; + + var results = await _whatsAppBusinessClient.SendFlowMessageAsync(flowMessageRequest); + + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent flow message"); + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppFlowMessage)).WithDanger("Error", ex.Message); + } + } public IActionResult SendWhatsAppTemplateMessage() { return View(); } - /// - /// This is to handle: - /// 1. Plain Text messgaes - /// 2. Text Templates (NO params) - /// 3. Text Templates with Params - /// - /// - /// - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SendWhatsAppTextMessage(SendTemplateMessageViewModel payload) - { // Functional using SendMessageController - try - { - SendWhatsAppPayload sendPayload = new(); - sendPayload.SendText = new SendTextPayload() - { ToNum = payload.RecipientPhoneNumber }; - sendPayload.SendText.PreviewUrl = false; - - if (payload.Message != null) - { // This is a normal plain Text Message - sendPayload.SendText.Message = payload.Message; - } - else - { // This is a Template Test Message - sendPayload.Template = new WhatsappTemplate(); - sendPayload.Template.Name = payload.TemplateName; - - // CJM to add a Params Textbox on the Form - if (payload.TemplateParams != null) - { - string strParams = payload.TemplateParams; // "Cornelius#DAFP"; - List listParams = strParams.Split(new string[] { "#" }, StringSplitOptions.None).ToList(); - sendPayload.Template.Params = listParams; - } - } - - // Send the message and get the WAMId - string WAMIds = _sendMessageController.GetWAMId((await _sendMessageController.SendWhatsApp_TextAsync(sendPayload)).Value); - - - if (WAMIds != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", $"Successfully sent video template message with WAMId '{WAMIds}'"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) + { + try + { + TextTemplateMessageRequest textTemplateMessage = new TextTemplateMessageRequest(); + textTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + textTemplateMessage.Template = new TextMessageTemplate(); + textTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + textTemplateMessage.Template.Language = new TextMessageLanguage(); + textTemplateMessage.Template.Language.Code = "en_US"; - [HttpPost] + var results = await _whatsAppBusinessClient.SendTextMessageTemplateAsync(textTemplateMessage); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent template text message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppTextTemplateMessageWithParameters(SendTemplateMessageViewModel sendTemplateMessageViewModel) + { + try + { + // For Text Template message with parameters supported component type is body only + TextTemplateMessageRequest textTemplateMessage = new TextTemplateMessageRequest(); + textTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + textTemplateMessage.Template = new TextMessageTemplate(); + textTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + textTemplateMessage.Template.Language = new TextMessageLanguage(); + textTemplateMessage.Template.Language.Code = LanguageCode.English_US; + textTemplateMessage.Template.Components = new List(); + textTemplateMessage.Template.Components.Add(new TextMessageComponent() + { + Type = "body", + Parameters = new List() + { + new TextMessageParameter() + { + Type = "text", + Text = "Testing Parameter Placeholder Position 1" + }, + new TextMessageParameter() + { + Type = "text", + Text = "Testing Parameter Placeholder Position 2" + } + } + }); + + var results = await _whatsAppBusinessClient.SendTextMessageTemplateAsync(textTemplateMessage); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent template text message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } + + [HttpPost] [ValidateAntiForgeryToken] public async Task SendWhatsAppInteractiveTemplateMessageWithParameters(SendTemplateMessageViewModel sendTemplateMessageViewModel) { try { - // Tested with facebook predefined template name: sample_issue_resolution - InteractiveTemplateMessageRequest interactiveTemplateMessage = new InteractiveTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new InteractiveMessageTemplate - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new InteractiveMessageLanguage - { - Code = LanguageCode.English_US - }, - Components = new List() - } - }; - interactiveTemplateMessage.Template.Components.Add(new InteractiveMessageComponent() + // Tested with facebook predefined template name: sample_issue_resolution + InteractiveTemplateMessageRequest interactiveTemplateMessage = new InteractiveTemplateMessageRequest(); + interactiveTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + interactiveTemplateMessage.Template = new InteractiveMessageTemplate(); + interactiveTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + interactiveTemplateMessage.Template.Language = new InteractiveMessageLanguage(); + interactiveTemplateMessage.Template.Language.Code = LanguageCode.English_US; + interactiveTemplateMessage.Template.Components = new List(); + interactiveTemplateMessage.Template.Components.Add(new InteractiveMessageComponent() { Type = "body", Parameters = new List() @@ -527,91 +600,84 @@ public async Task SendWhatsAppInteractiveTemplateMessageWithParam public async Task SendWhatsAppMediaTemplateMessageWithParameters(SendTemplateMessageViewModel sendTemplateMessageViewModel) { try - { - SendWhatsAppPayload payload = new(); - payload.SendText = new SendTextPayload() - { - ToNum = sendTemplateMessageViewModel.RecipientPhoneNumber - }; - payload.Template = new WhatsappTemplate(); - payload.Template.Name = sendTemplateMessageViewModel.TemplateName; - - // CJM to add a Params Textbox on the Form if it is empty then there are no params - if (sendTemplateMessageViewModel.TemplateParams != null) - { - string strParams = sendTemplateMessageViewModel.TemplateParams; // "Cornelius#DAFP"; - List listParams = strParams.Split(new string[] { "#" }, StringSplitOptions.None).ToList(); - - payload.Template.Params = listParams; - }; - - payload.Media = new WhatsAppMedia - { - ID = !string.IsNullOrEmpty(sendTemplateMessageViewModel.MediaId) ? sendTemplateMessageViewModel.MediaId : null, - URL = string.IsNullOrEmpty(sendTemplateMessageViewModel.MediaId) ? sendTemplateMessageViewModel.LinkUrl : null, - Type = "image" //, - // Caption = "" // Caption does not work - }; - - // Send the message and get the WAMId - string WAMIds = _sendMessageController.GetWAMId((await _sendMessageController.SendWhatsApp_TemplateImage_ParameterAsync(payload)).Value); - - - if (WAMIds != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", $"Successfully sent video template message with WAMId '{WAMIds}'"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - - // Remember Other types of Parameters could be used, for now we will focus on Text only - - // new ImageMessageComponent() - // { - // Type = "body", - // Parameters = new List() - // { - // new ImageMessageParameter() - // { - // Type = "text", - // Text = "Movie Testing" - // }, - - // new ImageMessageParameter() - // { - // Type = "date_time", - // DateTime = new ImageTemplateDateTime() - // { - // FallbackValue = DateTime.Now.ToString("dddd d, yyyy"), - // DayOfWeek = (int)DateTime.Now.DayOfWeek, - // Year = DateTime.Now.Year, - // Month = DateTime.Now.Month, - // DayOfMonth = DateTime.Now.Day, - // Hour = DateTime.Now.Hour, - // Minute = DateTime.Now.Minute, - // Calendar = "GREGORIAN" - // } - // }, - - // new ImageMessageParameter() - // { - // Type = "text", - // Text = "Venue Test" - // }, - - // new ImageMessageParameter() - // { - // Type = "text", - // Text = "Seat 1A, 2A, 3A and 4A" - // } - // } - // } - // } - // } - //}; + { + // Tested with facebook predefined template name: sample_movie_ticket_confirmation + ImageTemplateMessageRequest imageTemplateMessage = new ImageTemplateMessageRequest(); + imageTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + imageTemplateMessage.Template = new ImageMessageTemplate(); + imageTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + imageTemplateMessage.Template.Language = new ImageMessageLanguage(); + imageTemplateMessage.Template.Language.Code = LanguageCode.English_US; + imageTemplateMessage.Template.Components = new List() + { + new ImageMessageComponent() + { + Type = "header", + Parameters = new List() + { + new ImageMessageParameter() + { + Type = "image", + Image = new Image() + { + //Id = sendTemplateMessageViewModel.MediaId, + Link = "https://otakukart.com/wp-content/uploads/2022/03/Upcoming-Marvel-Movies-In-2022-23.jpg" + } + } + }, + }, + new ImageMessageComponent() + { + Type = "body", + Parameters = new List() + { + new ImageMessageParameter() + { + Type = "text", + Text = "Movie Testing" + }, + + new ImageMessageParameter() + { + Type = "date_time", + DateTime = new ImageTemplateDateTime() + { + FallbackValue = DateTime.Now.ToString("dddd d, yyyy"), + DayOfWeek = (int)DateTime.Now.DayOfWeek, + Year = DateTime.Now.Year, + Month = DateTime.Now.Month, + DayOfMonth = DateTime.Now.Day, + Hour = DateTime.Now.Hour, + Minute = DateTime.Now.Minute, + Calendar = "GREGORIAN" + } + }, + + new ImageMessageParameter() + { + Type = "text", + Text = "Venue Test" + }, + + new ImageMessageParameter() + { + Type = "text", + Text = "Seat 1A, 2A, 3A and 4A" + } + } + } + }; + var results = await _whatsAppBusinessClient.SendImageAttachmentTemplateMessageAsync(imageTemplateMessage); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent image template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } } catch (WhatsappBusinessCloudAPIException ex) { @@ -626,51 +692,45 @@ public async Task SendWhatsAppDocumentTemplateMessageWithParamete { try { - DocumentTemplateMessageRequest documentTemplateMessage = new DocumentTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new DocumentMessageTemplate - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new DocumentMessageLanguage - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new DocumentMessageComponent() - { - Type = "header", - Parameters = new List() - { - new DocumentMessageParameter() - { - Type = "document", - Document = new Document() - { - //Id = payload.MediaId, - Link = "" // Link point where your document can be downloaded or retrieved by WhatsApp - } - } - }, - }, - new DocumentMessageComponent() - { - Type = "body", - Parameters = new List() - { - new DocumentMessageParameter() - { - Type = "text", - Text = "Order Invoice" - }, - } - } - } - } - }; + DocumentTemplateMessageRequest documentTemplateMessage = new DocumentTemplateMessageRequest(); + documentTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + documentTemplateMessage.Template = new DocumentMessageTemplate(); + documentTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + documentTemplateMessage.Template.Language = new DocumentMessageLanguage(); + documentTemplateMessage.Template.Language.Code = LanguageCode.English_US; + documentTemplateMessage.Template.Components = new List() + { + new DocumentMessageComponent() + { + Type = "header", + Parameters = new List() + { + new DocumentMessageParameter() + { + Type = "document", + Document = new Document() + { + //Id = sendTemplateMessageViewModel.MediaId, + Link = "" // Link point where your document can be downloaded or retrieved by WhatsApp + } + } + }, + }, + new DocumentMessageComponent() + { + Type = "body", + Parameters = new List() + { + new DocumentMessageParameter() + { + Type = "text", + Text = "Order Invoice" + }, + } + } + }; - var results = await _whatsAppBusinessClient.SendDocumentAttachmentTemplateMessageAsync(documentTemplateMessage); + var results = await _whatsAppBusinessClient.SendDocumentAttachmentTemplateMessageAsync(documentTemplateMessage); if (results != null) { @@ -688,409 +748,390 @@ public async Task SendWhatsAppDocumentTemplateMessageWithParamete } } - /// - /// Making use of SendMessageController to send a WhatsApp Video Template with or without parameters - /// - /// - /// [HttpPost] [ValidateAntiForgeryToken] public async Task SendWhatsAppVideoTemplateMessageWithParameters(SendTemplateMessageViewModel sendTemplateMessageViewModel) { try { - SendWhatsAppPayload payload = new(); - payload.SendText = new SendTextPayload() - { - ToNum = sendTemplateMessageViewModel.RecipientPhoneNumber - }; - payload.Template = new WhatsappTemplate(); - payload.Template.Name = sendTemplateMessageViewModel.TemplateName; - - // CJM to add a Params Textbox on the Form if it is empty then there are no params - if (sendTemplateMessageViewModel.TemplateParams != null) - { - string strParams = sendTemplateMessageViewModel.TemplateParams; // "Cornelius#DAFP"; - List listParams = strParams.Split(new string[] { "#" }, StringSplitOptions.None).ToList(); - - payload.Template.Params = listParams; - }; - - payload.Media = new WhatsAppMedia - { - ID = !string.IsNullOrEmpty(sendTemplateMessageViewModel.MediaId) ? sendTemplateMessageViewModel.MediaId : null, - URL = string.IsNullOrEmpty(sendTemplateMessageViewModel.MediaId) ? sendTemplateMessageViewModel.LinkUrl : null, - Type = "video" //, - // Caption = "" // Caption does not work - }; - - // Send the message and get the WAMId - string WAMIds = _sendMessageController.GetWAMId((await _sendMessageController.SendWhatsApp_TemplateVideo_ParameterAsync(payload)).Value); - - - if (WAMIds != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", $"Successfully sent video template message with WAMId '{WAMIds}'"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - - catch (WhatsappBusinessCloudAPIException ex) + VideoTemplateMessageRequest videoTemplateMessage = new(); + videoTemplateMessage.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + videoTemplateMessage.Template = new(); + videoTemplateMessage.Template.Name = sendTemplateMessageViewModel.TemplateName; + videoTemplateMessage.Template.Language = new(); + videoTemplateMessage.Template.Language.Code = LanguageCode.English_US; + videoTemplateMessage.Template.Components = new List() + { + new VideoMessageComponent() + { + Type = "header", + Parameters = new List() + { + new VideoMessageParameter() + { + Type = "video", + Video = new Video() + { + //Id = sendTemplateMessageViewModel.MediaId, + Link = sendTemplateMessageViewModel.LinkUrl // Link point where your document can be downloaded or retrieved by WhatsApp + } + } + }, + }, + new VideoMessageComponent() + { + Type = "body", + Parameters = new List() + { + new VideoMessageParameter() + { + Type = "text", + Text = "Video Information" + }, + } + } + }; + + var results = await _whatsAppBusinessClient.SendVideoAttachmentTemplateMessageAsync(videoTemplateMessage); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent video template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) { _logger.LogError(ex, ex.Message); return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); } } - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SendWhatsAppAuthenticationTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppAuthenticationTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) { try { - AuthenticationTemplateMessageRequest authenticationTemplateMessageRequest = new() - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new AuthenticationMessageComponent() - { - Type = "body", - Parameters = new List() - { - new AuthenticationMessageParameter() - { - Type = "text", - Text = "J$FpnYnP" // One time password value + AuthenticationTemplateMessageRequest authenticationTemplateMessageRequest = new(); + authenticationTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + authenticationTemplateMessageRequest.Template = new(); + authenticationTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + authenticationTemplateMessageRequest.Template.Language = new(); + authenticationTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + authenticationTemplateMessageRequest.Template.Components = new List() + { + new AuthenticationMessageComponent() + { + Type = "body", + Parameters = new List() + { + new AuthenticationMessageParameter() + { + Type = "text", + Text = "J$FpnYnP" // One time password value } - } - }, - new AuthenticationMessageComponent() - { - Type = "button", - SubType = "url", - Index = 0, - Parameters = new List() - { - new AuthenticationMessageParameter() - { - Type = "text", - Text = "J$FpnYnP" // One time password value + } + }, + new AuthenticationMessageComponent() + { + Type = "button", + SubType = "url", + Index = 0, + Parameters = new List() + { + new AuthenticationMessageParameter() + { + Type = "text", + Text = "J$FpnYnP" // One time password value } - } - } - } - } - }; - - var results = await _whatsAppBusinessClient.SendAuthenticationMessageTemplateAsync(authenticationTemplateMessageRequest); - - if (results != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent authentication template message"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + } + } + }; - [HttpPost] - [ValidateAntiForgeryToken] + var results = await _whatsAppBusinessClient.SendAuthenticationMessageTemplateAsync(authenticationTemplateMessageRequest); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent authentication template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] public async Task SendWhatsAppCatalogueTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) { try { - CatalogTemplateMessageRequest catalogTemplateMessageRequest = new CatalogTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new CatalogMessageComponent() - { - Type = "Body", - Parameters = new List() - { - new CatalogTemplateMessageParameter() - { - Type = "text", - Text = "100" - }, - new CatalogTemplateMessageParameter() - { - Type = "text", - Text = "400" - }, - new CatalogTemplateMessageParameter() - { - Type = "text", - Text = "3" - }, - } - }, - new CatalogMessageComponent() - { - Type = "button", - SubType = "CATALOG", - Index = 0, - Parameters = new List() - { - new CatalogTemplateMessageParameter() - { - Type = "action", - Action = new CatalogTemplateMessageAction() - { - ThumbnailProductRetailerId = "2lc20305pt" - } - } - } - } - } - } - }; - - var results = await _whatsAppBusinessClient.SendCatalogMessageTemplateAsync(catalogTemplateMessageRequest); - - if (results != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent catalogue template message"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + CatalogTemplateMessageRequest catalogTemplateMessageRequest = new CatalogTemplateMessageRequest(); + catalogTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + catalogTemplateMessageRequest.Template = new(); + catalogTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + catalogTemplateMessageRequest.Template.Language = new(); + catalogTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + catalogTemplateMessageRequest.Template.Components = new List() + { + new CatalogMessageComponent() + { + Type = "Body", + Parameters = new List() + { + new CatalogTemplateMessageParameter() + { + Type = "text", + Text = "100" + }, + new CatalogTemplateMessageParameter() + { + Type = "text", + Text = "400" + }, + new CatalogTemplateMessageParameter() + { + Type = "text", + Text = "3" + }, + } + }, + new CatalogMessageComponent() + { + Type = "button", + SubType = "CATALOG", + Index = 0, + Parameters = new List() + { + new CatalogTemplateMessageParameter() + { + Type = "action", + Action = new CatalogTemplateMessageAction() + { + ThumbnailProductRetailerId = "2lc20305pt" + } + } + } + } + }; - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SendWhatsAppCarouselTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) - { - try - { - CarouselTemplateMessageRequest carouselTemplateMessageRequest = new CarouselTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new CarouselMessageTemplateComponent() - { - Type = "BODY", - Parameters = new List() - { - new CarouselMessageParameter() - { - Type = "Text", - Text = "20OFF" - }, - new CarouselMessageParameter() - { - Type = "Text", - Text = "20%" - } - } - }, - new CarouselMessageTemplateComponent() - { - Type = "CAROUSEL", - Cards = new List() - { - new CarouselMessageCard() - { - CardIndex = 0, - Components = new List() - { - new CarouselCardComponent() - { - Type = "HEADER", - Parameters = new List() - { - new CardMessageParameter() - { - Type = "IMAGE", - Image = new CardImage() - { - Id = "24230790383178626" - } - } - } - }, - new CarouselCardComponent() - { - Type = "BODY", - Parameters = new List() - { - new CardMessageParameter() - { - Type = "Text", - Text = "10OFF" - }, - new CardMessageParameter() - { - Type = "Text", - Text = "10%" - } - } - }, - new CarouselCardComponent() - { - Type = "BUTTON", - SubType = "QUICK_REPLY", - Index = 0, - Parameters = new List() - { - new CardMessageParameter() - { - Type = "PAYLOAD", - Payload = "59NqSd" - } - } - }, - new CarouselCardComponent() - { - Type = "button", - SubType = "URL", - Index = 1, - Parameters = new List() - { - new CardMessageParameter() - { - Type = "PAYLOAD", - Payload = "last_chance_2023" - } - } - } - } - } - } - }, - } - } - }; - - var results = await _whatsAppBusinessClient.SendCarouselMessageTemplateAsync(carouselTemplateMessageRequest); - - if (results != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent carousel template message"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + var results = await _whatsAppBusinessClient.SendCatalogMessageTemplateAsync(catalogTemplateMessageRequest); - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SendWhatsAppCouponCodeTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) - { - try - { - CouponCodeTemplateMessageRequest couponCodeTemplateMessageRequest = new CouponCodeTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new CouponCodeMessageComponent() - { - Type = "body", - Parameters = new List() - { - new CouponCodeMessageParameter() - { - Type = "text", - Text = "25OFF" - }, - new CouponCodeMessageParameter() - { - Type = "text", - Text = "25%" - } - } - }, - new CouponCodeMessageComponent() - { - Type = "button", - SubType = "COPY_CODE", - Index = 1, - Parameters = new List() - { - new CouponCodeMessageParameter() - { - Type = "coupon_code", - Text = "25OFF" - } - } - } - } - } - }; - - var results = await _whatsAppBusinessClient.SendCouponCodeMessageTemplateAsync(couponCodeTemplateMessageRequest); - - if (results != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent coupon code template message"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent catalogue template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppCarouselTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) + { + try + { + CarouselTemplateMessageRequest carouselTemplateMessageRequest = new CarouselTemplateMessageRequest(); + carouselTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + carouselTemplateMessageRequest.Template = new(); + carouselTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + carouselTemplateMessageRequest.Template.Language = new(); + carouselTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + carouselTemplateMessageRequest.Template.Components = new List() + { + new CarouselMessageTemplateComponent() + { + Type = "BODY", + Parameters = new List() + { + new CarouselMessageParameter() + { + Type = "Text", + Text = "20OFF" + }, + new CarouselMessageParameter() + { + Type = "Text", + Text = "20%" + } + } + }, + new CarouselMessageTemplateComponent() + { + Type = "CAROUSEL", + Cards = new List() + { + new CarouselMessageCard() + { + CardIndex = 0, + Components = new List() + { + new CarouselCardComponent() + { + Type = "HEADER", + Parameters = new List() + { + new CardMessageParameter() + { + Type = "IMAGE", + Image = new CardImage() + { + Id = "24230790383178626" + } + } + } + }, + new CarouselCardComponent() + { + Type = "BODY", + Parameters = new List() + { + new CardMessageParameter() + { + Type = "Text", + Text = "10OFF" + }, + new CardMessageParameter() + { + Type = "Text", + Text = "10%" + } + } + }, + new CarouselCardComponent() + { + Type = "BUTTON", + SubType = "QUICK_REPLY", + Index = 0, + Parameters = new List() + { + new CardMessageParameter() + { + Type = "PAYLOAD", + Payload = "59NqSd" + } + } + }, + new CarouselCardComponent() + { + Type = "button", + SubType = "URL", + Index = 1, + Parameters = new List() + { + new CardMessageParameter() + { + Type = "PAYLOAD", + Payload = "last_chance_2023" + } + } + } + } + } + } + }, + }; + + var results = await _whatsAppBusinessClient.SendCarouselMessageTemplateAsync(carouselTemplateMessageRequest); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent carousel template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SendWhatsAppCouponCodeTemplateMessage(SendTemplateMessageViewModel sendTemplateMessageViewModel) + { + try + { + CouponCodeTemplateMessageRequest couponCodeTemplateMessageRequest = new CouponCodeTemplateMessageRequest(); + couponCodeTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + couponCodeTemplateMessageRequest.Template = new(); + couponCodeTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + couponCodeTemplateMessageRequest.Template.Language = new(); + couponCodeTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + couponCodeTemplateMessageRequest.Template.Components = new List() + { + new CouponCodeMessageComponent() + { + Type = "body", + Parameters = new List() + { + new CouponCodeMessageParameter() + { + Type = "text", + Text = "25OFF" + }, + new CouponCodeMessageParameter() + { + Type = "text", + Text = "25%" + } + } + }, + new CouponCodeMessageComponent() + { + Type = "button", + SubType = "COPY_CODE", + Index = 1, + Parameters = new List() + { + new CouponCodeMessageParameter() + { + Type = "coupon_code", + Text = "25OFF" + } + } + } + }; + + var results = await _whatsAppBusinessClient.SendCouponCodeMessageTemplateAsync(couponCodeTemplateMessageRequest); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent coupon code template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } [HttpPost] [ValidateAntiForgeryToken] @@ -1098,99 +1139,93 @@ public async Task SendWhatsAppLimitedTimeOfferTemplateMessage(Sen { try { - LimitedTimeOfferTemplateMessageRequest limitedTimeOfferTemplateMessageRequest = new LimitedTimeOfferTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new LimitedTimeOfferMessageComponent() - { - Type = "body", - Parameters = new List() - { - new LimitedTimeOfferMessageParameter() - { - Type = "text", - Text = "Pablo" - }, - new LimitedTimeOfferMessageParameter() - { - Type = "text", - Text = "CARIBE25" - } - } - }, - new LimitedTimeOfferMessageComponent() - { - Type = "limited_time_offer", - Parameters = new List() - { - new LimitedTimeOfferMessageParameter() - { - Type = "limited_time_offer", - LimitedTimeOffer = new LimitedTimeOffer() - { - ExpirationTimeMs = new DateTimeOffset(DateTime.UtcNow.AddHours(2)).ToUnixTimeMilliseconds() - } - } - } - }, - new LimitedTimeOfferMessageComponent() - { - Type = "button", - SubType = "copy_code", - Index = 0, - Parameters = new List() - { - new LimitedTimeOfferMessageParameter() - { - Type = "coupon_code", - CouponCode = "CARIBE25" - } - } - }, - new LimitedTimeOfferMessageComponent() - { - Type = "button", - SubType = "url", - Index = 1, - Parameters = new List() - { - new LimitedTimeOfferMessageParameter() - { - Type = "text", - Text = "https://www.google.com/maps" - } - } - } - } - } - }; - - var results = await _whatsAppBusinessClient.SendLimitedTimeOfferMessageTemplateAsync(limitedTimeOfferTemplateMessageRequest); - - if (results != null) - { - return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent limited time offer template message"); - } - else - { - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); - } - } + LimitedTimeOfferTemplateMessageRequest limitedTimeOfferTemplateMessageRequest = new LimitedTimeOfferTemplateMessageRequest(); + limitedTimeOfferTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + limitedTimeOfferTemplateMessageRequest.Template = new(); + limitedTimeOfferTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + limitedTimeOfferTemplateMessageRequest.Template.Language = new(); + limitedTimeOfferTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + limitedTimeOfferTemplateMessageRequest.Template.Components = new List() + { + new LimitedTimeOfferMessageComponent() + { + Type = "body", + Parameters = new List() + { + new LimitedTimeOfferMessageParameter() + { + Type = "text", + Text = "Pablo" + }, + new LimitedTimeOfferMessageParameter() + { + Type = "text", + Text = "CARIBE25" + } + } + }, + new LimitedTimeOfferMessageComponent() + { + Type = "limited_time_offer", + Parameters = new List() + { + new LimitedTimeOfferMessageParameter() + { + Type = "limited_time_offer", + LimitedTimeOffer = new LimitedTimeOffer() + { + ExpirationTimeMs = new DateTimeOffset(DateTime.UtcNow.AddHours(2)).ToUnixTimeMilliseconds() + } + } + } + }, + new LimitedTimeOfferMessageComponent() + { + Type = "button", + SubType = "copy_code", + Index = 0, + Parameters = new List() + { + new LimitedTimeOfferMessageParameter() + { + Type = "coupon_code", + CouponCode = "CARIBE25" + } + } + }, + new LimitedTimeOfferMessageComponent() + { + Type = "button", + SubType = "url", + Index = 1, + Parameters = new List() + { + new LimitedTimeOfferMessageParameter() + { + Type = "text", + Text = "https://www.google.com/maps" + } + } + } + }; + + var results = await _whatsAppBusinessClient.SendLimitedTimeOfferMessageTemplateAsync(limitedTimeOfferTemplateMessageRequest); + + if (results != null) + { + return RedirectToAction(nameof(Index)).WithSuccess("Success", "Successfully sent limited time offer template message"); + } + else + { + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(SendWhatsAppTemplateMessage)).WithDanger("Error", ex.Message); + } + } [HttpPost] [ValidateAntiForgeryToken] @@ -1198,40 +1233,34 @@ public async Task SendWhatsAppFlowTemplateMessage(SendTemplateMes { try { - FlowTemplateMessageRequest flowTemplateMessageRequest = new FlowTemplateMessageRequest - { - To = sendTemplateMessageViewModel.RecipientPhoneNumber, - Template = new() - { - Name = sendTemplateMessageViewModel.TemplateName, - Language = new() - { - Code = LanguageCode.English_US - }, - Components = new List() - { - new FlowMessageComponent() - { - Type = "button", - SubType = "flow", - Index = 0, - Parameters = new List() - { - new FlowTemplateMessageParameter() - { - Type = "action", - Action = new FlowTemplateMessageAction() - { - FlowToken = "", - } - } - } - } - } - } - }; + FlowTemplateMessageRequest flowTemplateMessageRequest = new FlowTemplateMessageRequest(); + flowTemplateMessageRequest.To = sendTemplateMessageViewModel.RecipientPhoneNumber; + flowTemplateMessageRequest.Template = new(); + flowTemplateMessageRequest.Template.Name = sendTemplateMessageViewModel.TemplateName; + flowTemplateMessageRequest.Template.Language = new(); + flowTemplateMessageRequest.Template.Language.Code = LanguageCode.English_US; + flowTemplateMessageRequest.Template.Components = new List() + { + new FlowMessageComponent() + { + Type = "button", + SubType = "flow", + Index = 0, + Parameters = new List() + { + new FlowTemplateMessageParameter() + { + Type = "action", + Action = new FlowTemplateMessageAction() + { + FlowToken = "", + } + } + } + } + }; - var results = await _whatsAppBusinessClient.SendFlowMessageTemplateAsync(flowTemplateMessageRequest); + var results = await _whatsAppBusinessClient.SendFlowMessageTemplateAsync(flowTemplateMessageRequest); if (results != null) { @@ -1249,7 +1278,7 @@ public async Task SendWhatsAppFlowTemplateMessage(SendTemplateMes } } - public IActionResult SendWhatsAppContactMessage() + public IActionResult SendWhatsAppContactMessage() { return View(); } @@ -1260,37 +1289,35 @@ public async Task SendWhatsAppContactMessage(SendContactMessageVi { try { - ContactMessageRequest contactMessageRequest = new ContactMessageRequest - { - To = sendContactMessageViewModel.RecipientPhoneNumber, - Contacts = new List() - { - new ContactData() - { - Addresses = new List
() - { - new Address() - { - State = "State Test", - City = "City Test", - Zip = "Zip Test", - Country = "Country Test", - CountryCode = "Country Code Test", - Type = "Home" - } - }, - Name = new Name() - { - FormattedName = "Testing name", - FirstName = "FName", - LastName = "LName", - MiddleName = "MName" - } - } - } - }; - - var results = await _whatsAppBusinessClient.SendContactAttachmentMessageAsync(contactMessageRequest); + ContactMessageRequest contactMessageRequest = new ContactMessageRequest(); + contactMessageRequest.To = sendContactMessageViewModel.RecipientPhoneNumber; + contactMessageRequest.Contacts = new List() + { + new ContactData() + { + Addresses = new List
() + { + new Address() + { + State = "State Test", + City = "City Test", + Zip = "Zip Test", + Country = "Country Test", + CountryCode = "Country Code Test", + Type = "Home" + } + }, + Name = new Name() + { + FormattedName = "Testing name", + FirstName = "FName", + LastName = "LName", + MiddleName = "MName" + } + } + }; + + var results = await _whatsAppBusinessClient.SendContactAttachmentMessageAsync(contactMessageRequest); if (results != null) { @@ -1308,103 +1335,82 @@ public async Task SendWhatsAppContactMessage(SendContactMessageVi } } - public IActionResult BulkSendWhatsApps() - { - BulkSendWhatsAppsViewModel bulkSendWhatsAppsViewModel = new BulkSendWhatsAppsViewModel(); - - return View(bulkSendWhatsAppsViewModel); - } + public IActionResult UploadMedia() + { + UploadMediaViewModel uploadMediaViewModel = new UploadMediaViewModel(); + uploadMediaViewModel.UploadType = new List() + { + new SelectListItem(){ Text = "Normal Upload", Value = "Normal Upload" }, + new SelectListItem(){ Text = "Resumable Upload", Value = "Resumable Upload" }, + }; + + return View(uploadMediaViewModel); + } - /// - /// Make use of BulkSendWhatsAppController to read a CSV file, loop through the file and send whatsApp per record - /// - /// - /// - /// - [HttpPost] - [ValidateAntiForgeryToken] - public async Task BulkSendWhatsApps(BulkSendWhatsAppsViewModel bulkSendWhatsAppsViewModel, IFormFile bulkFile) - { + [HttpPost] + [ValidateAntiForgeryToken] + public async Task UploadMedia(UploadMediaViewModel uploadMediaViewModel, IFormFile mediaFile) + { try - { // This is to call the relevant methods to run through the file and Bulk Send WhatsApps - //List WAMIds = new List(); + { + var fileName = Path.GetFileName(mediaFile.FileName).Trim('"'); - // Upload the Bulk File to the Local Server - FileInfo fileInfo = new(); - FileManagmentController fileController = new(_logger, _whatsAppBusinessClient, _environment); - fileInfo = await fileController.UploadFileToLocalServer(bulkFile); + var rootPath = Path.Combine(_environment.WebRootPath, "Application_Files\\MediaUploads\\"); - // Now go through the file and send the WhatsApps - BulkSendWhatsAppsController bulkSendWhatsAppsController = new(_logger, _whatsAppBusinessClient, _environment); - var WAMIDs = bulkSendWhatsAppsController.ReadAndTraverseCSV(fileInfo); + if (!Directory.Exists(rootPath)) + { + Directory.CreateDirectory(rootPath); + } - + // Get the path of filename + var filePath = Path.Combine(_environment.WebRootPath, "Application_Files\\MediaUploads\\", fileName); + // Upload Csv file to the browser + using (var stream = new FileStream(filePath, FileMode.Create)) + { + await mediaFile.CopyToAsync(stream); + } - + if (uploadMediaViewModel.SelectedUploadType.Equals("Normal Upload", StringComparison.OrdinalIgnoreCase)) + { + UploadMediaRequest uploadMediaRequest = new UploadMediaRequest(); + uploadMediaRequest.File = filePath; + uploadMediaRequest.Type = mediaFile.ContentType; + var uploadMediaResult = await _whatsAppBusinessClient.UploadMediaAsync(uploadMediaRequest); - return View(bulkSendWhatsAppsViewModel); - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return RedirectToAction(nameof(bulkFile)).WithDanger("Error", ex.Message); - } - } + var mediaUrlResult = await _whatsAppBusinessClient.GetMediaUrlAsync(uploadMediaResult.MediaId); - public IActionResult UploadMedia() - { - UploadMediaViewModel uploadMediaViewModel = new UploadMediaViewModel - { - UploadType = new List() - { - new SelectListItem(){ Text = "Normal Upload", Value = "Normal Upload" }, - new SelectListItem(){ Text = "Resumable Upload", Value = "Resumable Upload" }, - } - }; - - return View(uploadMediaViewModel); - } - - /// - /// This is to Upload files to WhatsApp - /// NOTE: Resumable Uploads to WhatsApp does NOT provide a MediaID. To upload to WhatsApp ONLY use Normal Uploads - /// Changed to make use of FileManagmentController - /// - /// - /// - /// - [HttpPost] - [ValidateAntiForgeryToken] - public async Task UploadMedia(UploadMediaViewModel uploadMediaViewModel, IFormFile mediaFile) - { - try - { - FileInfo fileInfo = new(); - FileManagmentController fileToUpload = new(_logger, _whatsAppBusinessClient, _environment); - - // Upload file to Local Server - fileInfo = await fileToUpload.UploadFileToLocalServer(mediaFile); - - if (uploadMediaViewModel.SelectedUploadType.Equals("Normal Upload", StringComparison.OrdinalIgnoreCase)) - { // Do a Normal Upload - fileInfo.fileUploadMethod = "Normal"; - - fileInfo = await fileToUpload.UploadFileToWhatsApp(fileInfo); - ViewBag.MediaId = fileInfo.fileWhatsAppID; - } - else - { // Do a Resumanble upload ************* BUT ************** This is not presenting a Media ID so cannot be used after - fileInfo.fileUploadMethod = "Resumable"; - //Upload file from Local Server to WhatsApp - fileInfo = await fileToUpload.UploadFileToWhatsApp(fileInfo); - ViewBag.H = fileInfo.fileResumableInfo.H; - ViewBag.StatusId = fileInfo.fileResumableInfo.StatusID; - ViewBag.FileOffset = fileInfo.fileResumableInfo.FileOffset; + var mediaBytes = await _whatsAppBusinessClient.DownloadMediaAsync(mediaUrlResult.Url); + + ViewBag.MediaId = uploadMediaResult.MediaId; } - - return View(uploadMediaViewModel).WithSuccess("Success", "Successfully upload media."); + else // Resumable upload generates header file response to be used for creating message templates + { + var resumableUploadMediaResult = await _whatsAppBusinessClient.CreateResumableUploadSessionAsync(mediaFile.Length, mediaFile.ContentType, mediaFile.FileName); + + if (resumableUploadMediaResult is not null) + { + var uploadSessionId = resumableUploadMediaResult.Id; + + var resumableUploadResponse = await _whatsAppBusinessClient.UploadFileDataAsync(uploadSessionId, filePath, mediaFile.ContentType); + + var queryResumableUploadStatus = await _whatsAppBusinessClient.QueryFileUploadStatusAsync(uploadSessionId); + + if (resumableUploadResponse is not null) + { + ViewBag.H = resumableUploadResponse.H; + } + + if (queryResumableUploadStatus is not null) + { + ViewBag.StatusId = queryResumableUploadStatus.Id; + ViewBag.FileOffset = queryResumableUploadStatus.FileOffset; + } + } + } + + return View(uploadMediaViewModel).WithSuccess("Success", "Successfully upload media."); } catch (WhatsappBusinessCloudAPIException ex) { @@ -1424,24 +1430,22 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - public IActionResult CreateQRCodeMessage() - { - QRCodeMessageViewModel qrCodeMessageViewModel = new QRCodeMessageViewModel - { - ImageFormat = new List() - { - new SelectListItem(){ Text = "SVG", Value = "SVG" }, - new SelectListItem(){ Text = "PNG", Value = "PNG" }, - } - }; + public IActionResult CreateQRCodeMessage() + { + QRCodeMessageViewModel qrCodeMessageViewModel = new QRCodeMessageViewModel(); + qrCodeMessageViewModel.ImageFormat = new List() + { + new SelectListItem(){ Text = "SVG", Value = "SVG" }, + new SelectListItem(){ Text = "PNG", Value = "PNG" }, + }; - return View(qrCodeMessageViewModel); - } + return View(qrCodeMessageViewModel); + } - [HttpPost] - [ValidateAntiForgeryToken] - public async Task CreateQRCodeMessage(QRCodeMessageViewModel qrCodeMessageViewModel) - { + [HttpPost] + [ValidateAntiForgeryToken] + public async Task CreateQRCodeMessage(QRCodeMessageViewModel qrCodeMessageViewModel) + { try { var results = await _whatsAppBusinessClient.CreateQRCodeMessageAsync(qrCodeMessageViewModel.Message, qrCodeMessageViewModel.SelectedImageFormat); @@ -1451,19 +1455,19 @@ public async Task CreateQRCodeMessage(QRCodeMessageViewModel qrCo ViewBag.QRCodeId = results.Code; ViewBag.QRCodeMessage = results.PrefilledMessage; ViewBag.QRCodeUrl = results.QrImageUrl; - return View(qrCodeMessageViewModel).WithSuccess("Success", "Successfully created QR code Message."); - } + return View(qrCodeMessageViewModel).WithSuccess("Success", "Successfully created QR code Message."); + } else { - return View(qrCodeMessageViewModel).WithDanger("Error", "QR code message is null"); - } + return View(qrCodeMessageViewModel).WithDanger("Error", "QR code message is null"); + } } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return View(qrCodeMessageViewModel).WithDanger("Error", ex.Message); - } - } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return View(qrCodeMessageViewModel).WithDanger("Error", ex.Message); + } + } public async Task QRCodeMessageList() { @@ -1487,37 +1491,37 @@ public async Task QRCodeMessageList() return View().WithDanger("Error", "QR code message list not availble"); } } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return View().WithDanger("Error", ex.Message); - } - } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return View().WithDanger("Error", ex.Message); + } + } public async Task Analytics() { try { - DateTime currentDate = DateTime.UtcNow; - var startOfMonth = new DateTime(currentDate.Year, currentDate.Month, 1); - var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1); - var results = await _whatsAppBusinessClient.GetAnalyticMetricsAsync(_whatsAppConfig.WhatsAppBusinessAccountId, startOfMonth, endOfMonth, Granularity.AnalyticsGranularity.MONTH); - - if (results is not null) - { - return View(results).WithSuccess("Success", "Analytics retrieved successfully"); - } - else - { - return View().WithDanger("Error", "Analytics not available"); - } - } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return View().WithDanger("Error", ex.Message); - } - } + DateTime currentDate = DateTime.UtcNow; + var startOfMonth = new DateTime(currentDate.Year, currentDate.Month, 1); + var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1); + var results = await _whatsAppBusinessClient.GetAnalyticMetricsAsync(_whatsAppConfig.WhatsAppBusinessAccountId, startOfMonth, endOfMonth, Granularity.AnalyticsGranularity.MONTH); + + if (results is not null) + { + return View(results).WithSuccess("Success", "Analytics retrieved successfully"); + } + else + { + return View().WithDanger("Error", "Analytics not available"); + } + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return View().WithDanger("Error", ex.Message); + } + } public async Task ConversationAnalytics() { @@ -1537,11 +1541,50 @@ public async Task ConversationAnalytics() return View().WithDanger("Error", "Conversation Analytics not available"); } } - catch (WhatsappBusinessCloudAPIException ex) - { - _logger.LogError(ex, ex.Message); - return View().WithDanger("Error", ex.Message); - } - } - } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return View().WithDanger("Error", ex.Message); + } + } + + public IActionResult BulkSendWhatsApps() + { + BulkSendWhatsAppsViewModel bulkSendWhatsAppsViewModel = new BulkSendWhatsAppsViewModel(); + + return View(bulkSendWhatsAppsViewModel); + } + + /// + /// Make use of BulkSendWhatsAppController to read a CSV file, loop through the file and send whatsApp per record + /// + /// + /// + /// + [HttpPost] + [ValidateAntiForgeryToken] + public async Task BulkSendWhatsApps(BulkSendWhatsAppsViewModel bulkSendWhatsAppsViewModel, IFormFile bulkFile) + { + try + { // This is to call the relevant methods to run through the file and Bulk Send WhatsApps + //List WAMIds = new List(); + + // Upload the Bulk File to the Local Server + FileInfo fileInfo = new(); + FileManagmentController fileController = new(_logger, _whatsAppBusinessClient, _environment); + fileInfo = await fileController.UploadFileToLocalServer(bulkFile); + + // Now go through the file and send the WhatsApps + BulkSendWhatsAppsController bulkSendWhatsAppsController = new(_logger, _whatsAppBusinessClient, _environment); + var WAMIDs = bulkSendWhatsAppsController.ReadAndTraverseCSV(fileInfo); + + return View(bulkSendWhatsAppsViewModel); + } + catch (WhatsappBusinessCloudAPIException ex) + { + _logger.LogError(ex, ex.Message); + return RedirectToAction(nameof(bulkFile)).WithDanger("Error", ex.Message); + } + } + } } \ No newline at end of file diff --git a/Samples/WhatsAppBusinessCloudAPI.Web/Program.cs b/Samples/WhatsAppBusinessCloudAPI.Web/Program.cs index cefdbba..774988e 100644 --- a/Samples/WhatsAppBusinessCloudAPI.Web/Program.cs +++ b/Samples/WhatsAppBusinessCloudAPI.Web/Program.cs @@ -7,22 +7,22 @@ // Add services to the container. builder.Services.AddControllersWithViews().AddNewtonsoftJson(options => { - options.SerializerSettings.Formatting = Formatting.Indented; - options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; + options.SerializerSettings.Formatting = Formatting.Indented; + options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); builder.Services.Configure(options => { - builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration").Bind(options); + builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration").Bind(options); }); WhatsAppBusinessCloudApiConfig whatsAppConfig = new WhatsAppBusinessCloudApiConfig(); -whatsAppConfig.WhatsAppBusinessPhoneNumberId = builder.Configuration.GetSection("WhatsApp")["WhatsAppBusinessPhoneNumberId"]; -whatsAppConfig.WhatsAppBusinessAccountId = builder.Configuration.GetSection("WhatsApp")["WhatsAppBusinessAccountId"]; -whatsAppConfig.WhatsAppBusinessId = builder.Configuration.GetSection("WhatsApp")["WhatsAppBusinessId"]; -whatsAppConfig.AccessToken = builder.Configuration.GetSection("WhatsApp")["AccessToken"]; -whatsAppConfig.AppName = builder.Configuration.GetSection("AppInfo")["AppName"]; -whatsAppConfig.Version = builder.Configuration.GetSection("AppInfo")["Version"]; +whatsAppConfig.WhatsAppBusinessPhoneNumberId = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["WhatsAppBusinessPhoneNumberId"]; +whatsAppConfig.WhatsAppBusinessAccountId = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["WhatsAppBusinessAccountId"]; +whatsAppConfig.WhatsAppBusinessId = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["WhatsAppBusinessId"]; +whatsAppConfig.AccessToken = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["AccessToken"]; +whatsAppConfig.AppName = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["AppName"]; +whatsAppConfig.Version = builder.Configuration.GetSection("WhatsAppBusinessCloudApiConfiguration")["Version"]; builder.Services.AddWhatsAppBusinessCloudApiService(whatsAppConfig); @@ -31,9 +31,9 @@ // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { - app.UseExceptionHandler("/Home/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); + app.UseExceptionHandler("/Home/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); } app.UseHttpsRedirection(); @@ -44,7 +44,7 @@ app.UseAuthorization(); app.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); \ No newline at end of file diff --git a/Samples/WhatsAppBusinessCloudAPI.Web/ViewModel/SendTextMessageViewModel.cs b/Samples/WhatsAppBusinessCloudAPI.Web/ViewModel/SendTextMessageViewModel.cs index 255322c..1ebddb4 100644 --- a/Samples/WhatsAppBusinessCloudAPI.Web/ViewModel/SendTextMessageViewModel.cs +++ b/Samples/WhatsAppBusinessCloudAPI.Web/ViewModel/SendTextMessageViewModel.cs @@ -7,7 +7,7 @@ /// public class SendTextMessageViewModel { - //public string RecipientPhoneNumber { get; set; } - //public string Message { get; set; } + public string RecipientPhoneNumber { get; set; } + public string Message { get; set; } } } diff --git a/Samples/WhatsAppBusinessCloudAPI.Web/Views/Home/BulkSendWhatsApps.cshtml b/Samples/WhatsAppBusinessCloudAPI.Web/Views/Home/BulkSendWhatsApps.cshtml index 2115519..321173c 100644 --- a/Samples/WhatsAppBusinessCloudAPI.Web/Views/Home/BulkSendWhatsApps.cshtml +++ b/Samples/WhatsAppBusinessCloudAPI.Web/Views/Home/BulkSendWhatsApps.cshtml @@ -4,7 +4,7 @@ ViewData["CurrentPage"] = "Bulk Send WhatsApps"; Layout = "~/Views/Shared/AdminLTE/_AdminLayout.cshtml"; ViewData["ControllerName"] = nameof(HomeController).Replace("Controller", ""); - ViewData["ActionName"] = nameof(HomeController.BulkSendWhatsApps); + //ViewData["ActionName"] = nameof(HomeController.BulkSendWhatsApps); }
diff --git a/WhatsappBusiness.CloudApi/Interfaces/IWhatsAppBusinessClient.cs b/WhatsappBusiness.CloudApi/Interfaces/IWhatsAppBusinessClient.cs index f158b4e..5d0bd70 100644 --- a/WhatsappBusiness.CloudApi/Interfaces/IWhatsAppBusinessClient.cs +++ b/WhatsappBusiness.CloudApi/Interfaces/IWhatsAppBusinessClient.cs @@ -190,7 +190,7 @@ public interface IWhatsAppBusinessClient /// The URL generated from whatsapp cloud api /// Cancellation token /// byte[] - Task DownloadMediaAsync(string mediaUrl, CancellationToken cancellationToken = default); + Task DownloadMediaAsync(string mediaUrl, string appName = null, string version = null, CancellationToken cancellationToken = default); /// /// To download media uploaded from whatsapp @@ -198,7 +198,7 @@ public interface IWhatsAppBusinessClient /// The URL generated from whatsapp cloud api /// Cancellation token /// byte[] - byte[] DownloadMedia(string mediaUrl, CancellationToken cancellationToken = default); + byte[] DownloadMedia(string mediaUrl, string appName = null, string version = null, CancellationToken cancellationToken = default); #endregion #region Phone Numbers functions diff --git a/WhatsappBusiness.CloudApi/WhatsAppBusinessClient.cs b/WhatsappBusiness.CloudApi/WhatsAppBusinessClient.cs index ad2a44b..62244be 100644 --- a/WhatsappBusiness.CloudApi/WhatsAppBusinessClient.cs +++ b/WhatsappBusiness.CloudApi/WhatsAppBusinessClient.cs @@ -436,11 +436,11 @@ public async Task DeRegisterWhatsAppBusinessPhoneNumberAsyn /// The URL generated from whatsapp cloud api /// Cancellation token /// byte[] - public byte[] DownloadMedia(string mediaUrl, CancellationToken cancellationToken = default) + public byte[] DownloadMedia(string mediaUrl, string appName = null, string version = null, CancellationToken cancellationToken = default) { string formattedWhatsAppEndpoint; formattedWhatsAppEndpoint = WhatsAppBusinessRequestEndpoint.DownloadMedia.Replace("{{Media-URL}}", mediaUrl); - return WhatsAppBusinessGetAsync(formattedWhatsAppEndpoint, cancellationToken).GetAwaiter().GetResult(); + return WhatsAppBusinessGetAsync(formattedWhatsAppEndpoint, appName, version, cancellationToken).GetAwaiter().GetResult(); } /// @@ -449,11 +449,11 @@ public byte[] DownloadMedia(string mediaUrl, CancellationToken cancellationToken /// The URL generated from whatsapp cloud api /// Cancellation token /// byte[] - public async Task DownloadMediaAsync(string mediaUrl, CancellationToken cancellationToken = default) + public async Task DownloadMediaAsync(string mediaUrl, string appName = null, string version = null, CancellationToken cancellationToken = default) { string formattedWhatsAppEndpoint; formattedWhatsAppEndpoint = WhatsAppBusinessRequestEndpoint.DownloadMedia.Replace("{{Media-URL}}", mediaUrl); - return await WhatsAppBusinessGetAsync(formattedWhatsAppEndpoint, cancellationToken); + return await WhatsAppBusinessGetAsync(formattedWhatsAppEndpoint, appName, version, cancellationToken); } /// @@ -2889,9 +2889,18 @@ await response.Content.ReadAsStreamAsync().ContinueWith((Task stream) => return result; } - private async Task WhatsAppBusinessGetAsync(string whatsAppBusinessEndpoint, CancellationToken cancellationToken = default) + private async Task WhatsAppBusinessGetAsync(string whatsAppBusinessEndpoint, string AppName = null, string version = null, CancellationToken cancellationToken = default) { - var productValue = new ProductInfoHeaderValue(_whatsAppConfig.AppName, _whatsAppConfig.Version); + ProductInfoHeaderValue productValue; + + if (!string.IsNullOrWhiteSpace(AppName) && !string.IsNullOrWhiteSpace(version)) + { + productValue = new ProductInfoHeaderValue(AppName, version); + } + else + { + productValue = new ProductInfoHeaderValue(_whatsAppConfig.AppName, _whatsAppConfig.Version); + } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _whatsAppConfig.AccessToken); _httpClient.DefaultRequestHeaders.UserAgent.Add(productValue); diff --git a/WhatsappBusiness.CloudApi/WhatsappBusiness.CloudApi.csproj b/WhatsappBusiness.CloudApi/WhatsappBusiness.CloudApi.csproj index 939d0c4..e28a799 100644 --- a/WhatsappBusiness.CloudApi/WhatsappBusiness.CloudApi.csproj +++ b/WhatsappBusiness.CloudApi/WhatsappBusiness.CloudApi.csproj @@ -12,7 +12,7 @@ https://github.com/gabrieldwight/Whatsapp-Business-Cloud-Api-Net enable latest - 1.0.28 + 1.0.29