CHS Whats App API Setup-Old

CHS Whats App API Setup-Old

Branch Flow call whats app api from service

How the Due Reminders will work

  • We will have Button for sending reminders or we have scheduler ?
  • Do we have a System parameter for this or we will have any common System parameter for coming features ?
  • We will have a different controller or repository called RemindersManagement, or Scheduler need to discuss
  • Once the DueReminders called we have to get all members list with their dues, additional columns what all we need that will be decided on final template
  • Once we get the all members list, we have to create json format & store in variable , and send api, this process will be repeated for all members.
  • json creation from C# is more clear compare to SQL , need to discuss which we want
  • Once we get the members list or json, now we need to get member cellno, which will check it is valid cellno
  • Once we get the list json is prepared now, we can send API, once API is return we can check status, if status is failed we can have log
  • We will have two tables one for success & one for fail like einvoice or only 1 ?
  • We have to inform to user for what all members message is succeed through report or scheduler or how & in this round only ?

Discussed Doubts

  • Files name will be different ReminderManagement

Basic Model Structure

System flow

A New Class

public class DueReminder
{
    public string CustomerName { get; set; }
    public string InvoiceId { get; set; }
    public decimal Amount { get; set; }
    public DateTime DueDate { get; set; }
    public string PaymentUrl { get; set; }
}

Repository Query Structure

--Example: List of results from SQL
SELECT 'Amit Sharma' AS CustomerName, 'INV-1001' AS InvoiceId, '12500' AS Amount,'05-Oct-25' AS DueDate, 'https://pay.link' AS PaymentUrl,
'9120080001' AS memberCellNo, '000001' AS memberId

Return Value stored format


//Class store value
var reminders = new List<DueReminder>
{
    new DueReminder
    {
        CustomerName = "Amit Sharma",
        InvoiceId = "INV-1001",
        Amount = 12500,
        DueDate = new DateTime(2025, 10, 5),
        PaymentUrl = "https://pay.link",
        memberCellNo = "9120080001",
        memberId =  "000001"

    },
    //You may have more rows here...
};

appsettings.json API

{
  "WhatsApp": {
    "GraphApiVersion": "v24.0",           // keep configurable
    "PhoneNumberId": "834697629724703", // As per 3rd setup we will get
   // "BusinessAccountId": "YOUR_WABA_ID", // As per 3rd setup we will get
    "TokenKeyVaultSecretName":"EAFgXONjMZBzQBPzF1zmdf25sL9nku12oiNauGoMKJK2o4VAwq62zb2yAJoe1tEvv0VQLJ2eyy26YJgo7zKhsyBhoBbcs7X2WxNblVa2XdRoNHse3nnxZBvI73OyE5VEFLZC0EfRrfWjUxW67bED389qevCYeQtPc9f0DpiW2hBMZC60NiCaPVHJ5apy6MbBMRLMU2Ylma6LBw1NFGEa8B10ePOoLhIz9sIHIkwe3G6u5" // As per 2nd setup
  },
}

Service

public class WhatsAppService : IWhatsAppService
{
    private readonly HttpClient _http;
    private readonly string _phoneNumberId;
    private readonly string _graphVersion;

    public WhatsAppService(IHttpClientFactory httpFactory, IConfiguration cfg)
    {
        _http = httpFactory.CreateClient();

        _phoneNumberId = cfg["WhatsApp:PhoneNumberId"]; 
        _graphVersion = cfg["WhatsApp:GraphApiVersion"];
        var token = cfg["WhatsApp:TokenKeyVaultSecretName"];              

        _http.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", token);
    }

    public async Task<string> SendTemplateAsync(IList<string> reminders)
    {
        var url = $"https://graph.facebook.com/{_graphVersion}/{_phoneNumberId}/messages"; // URL

        // Template Structure
        // Hello {1},  
        // Your invoice {2} of amount {3} is due on {4}.  
        // Pay here: {5}

        var templateComponents = new List<object>();
        //Converting Each Customer Rows in a List  as per above SQL query there will be one row but after converting a columns to list it will become 5 rows for one member
        foreach (var r in reminders)
        {
            var parameters = new List<string>
            {
                r.CustomerName,                   // {1}
                r.InvoiceId,                      // {2}
                $"₹{r.Amount:N0}",                // {3} (12500 → ₹12,500)
                r.DueDate.ToString("dd-MMM-yy"),  // {4} (05-Oct-25)
                r.PaymentUrl                      // {5}
            };
            
            if (parameters?.Any() == true) //creating an array of list values
            {
                var components = new {
                    type = "body",
                    parameters = parameters.Select(p => new { type = "text", text = p }).ToArray()
                };
                templateComponents.Add(components);
            }

            var payload = new {
                messaging_product = "whatsapp",
                to = reminders.memberCellNo, //9120080001
                type = "template",
                template = new {
                    name = "payment_confirmation",
                    language = new { code = "en_US" },
                    components = templateComponents
                }
            };

            var ErrorMsg = "";
            var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
            var resp = await _http.PostAsync(url, content);
            var respBody = await resp.Content.ReadAsStringAsync();
            if (resp.IsSuccessStatusCode)
            {
                // parse id
                var doc = JObject.Parse(respBody);
                var msgId = doc["messages"]?.First?["id"]?.ToString();
                //Write a log
                ErrorMsg = "Success";
            }
            else 
            {
                //Write a Log
                ErrorMsg = "Failed"
            }
            return ErrorMsg

            //After sending if customer replies a mail we should give a static message will get back to you
        }
    }
}