Advertisement
Guest User

Untitled

a guest
May 10th, 2025
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.42 KB | None | 0 0
  1. using System.Net.Http.Headers;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Microsoft.AspNetCore.Mvc;
  5.  
  6. namespace whatsapp_tests.Services.Server
  7. {
  8. public class WhatsAppController
  9. {
  10. private readonly HttpClient _httpClient;
  11.  
  12. // constructor
  13. /*
  14. public WhatsAppService(HttpClient httpClient, string WhatsAppToken)
  15. {
  16. _httpClient = httpClient;
  17. _httpClient.DefaultRequestHeaders.Authorization =
  18. new AuthenticationHeaderValue(
  19. "Bearer",
  20. WhatsAppToken
  21. );
  22. }
  23.  
  24. */
  25.  
  26. // TO-DO:
  27. // figure out a way to make the whatsapp token
  28. // not expire every hour
  29. // otherwise come here and generate a new one
  30. // https://developers.facebook.com/tools/explorer/
  31. public WhatsAppController(HttpClient httpClient)
  32. {
  33. _httpClient = httpClient;
  34. _httpClient.DefaultRequestHeaders.Authorization =
  35. new AuthenticationHeaderValue(
  36. "Bearer",
  37. "PASTE WHATSAPP API TOKEN HERE"
  38. );
  39. }
  40.  
  41. /*
  42. *
  43. * ////////////////////////////////////////////////////////////////////////////////////////////////////////
  44. * //////////////////////////////////////////////////////////////////////////////////////////////////////
  45. * USER ACTIONS
  46. *
  47. * This entire section is dedicated to how the API consumes whatever info the
  48. * user sends and which sort of choices it takes
  49. *
  50. * /////////////////////////////////////////////////////////
  51. * */
  52.  
  53. // simple method that sends a reply to the user making the request
  54. public async Task SendTextMessageAsync(string sendTo, string message)
  55. {
  56. // JSON body which our API sends to the user
  57. var jsonBody = new
  58. {
  59. messaging_product = "whatsap",
  60. to = sendTo,
  61. text = new { body = message },
  62. type = "text"
  63. };
  64.  
  65. var content = new StringContent(JsonSerializer.Serialize(jsonBody), Encoding.UTF8, "application/json");
  66. var response = await _httpClient.PostAsync("PASTE WHATSAPP WEBHOOK HERE", content);
  67. response.EnsureSuccessStatusCode();
  68. }
  69.  
  70. // ################################################################
  71. // ################################################################
  72. // #################################################################
  73. // GET
  74. // simple method that gets the info being sent by the user
  75. public async Task<string> GetUserMessage(string userPhone)
  76. {
  77. try
  78. {
  79. string returnUserReply = "";
  80. HttpResponseMessage userReply = await _httpClient.GetAsync(userPhone);
  81. if (userReply.IsSuccessStatusCode)
  82. {
  83. returnUserReply = await userReply.Content.ReadAsStringAsync();
  84. return returnUserReply;
  85. }
  86. else
  87. {
  88. return "received invalid info";
  89. }
  90.  
  91. }
  92. catch(NullReferenceException ex)
  93. {
  94. Console.WriteLine("Error caught: NullReferenceException: ", ex.Message);
  95. return "error logged";
  96. }
  97. catch(ArgumentNullException ex)
  98. {
  99. Console.WriteLine("Error caught: ArgumentNullException: ", ex.Message);
  100. return "error logged";
  101. }
  102. catch(ArgumentException ex)
  103. {
  104. Console.WriteLine("Error caught: ArgumentException: ", ex.Message);
  105. return "error logged";
  106. }
  107. catch(FormatException ex)
  108. {
  109. Console.WriteLine("Error caught: FormatException: ", ex.Message);
  110. return "error logged";
  111. }
  112. catch(InvalidOperationException ex)
  113. {
  114. Console.WriteLine("Error caught: InvalidOperationException: ", ex.Message);
  115. return "error logged";
  116. }
  117.  
  118. }// end of GetUserMessage
  119.  
  120.  
  121. /*
  122. *
  123. * //////////////////////////////////////////////////////////////////////
  124. * //////////////////////////////////////////////////////////////////////
  125. * SERVER ACTIONS
  126. *
  127. * this entire section is dedicated to the info, choices, menus
  128. * etc. that the app takes whenever the user initiates a sesion,
  129. * makes a choice, etc.
  130. *
  131. */
  132.  
  133. // this method encapsulates the cURL Http request
  134. // generated by whatsapp's API
  135. // 'toPhoneNumber' is the phone # of the client
  136. // who is requesting the bot's features
  137. // -------
  138. // POST
  139. // -------
  140. public async Task SendMainMenuAsync(string toPhoneNumber)
  141. {
  142. // this entire thing is what would go inside one of those
  143. // huge JSON packages that whatsapp API generates
  144. var jsonBody = new
  145. {
  146. messaging_product = "whatsapp",
  147. recipient_type = "individual",
  148. to = toPhoneNumber,
  149. type = "interactive",
  150. // this is the JSON block
  151. // where the menu and its contents are displayed
  152. interactive = new
  153. {
  154. type = "list",
  155. // header
  156. header = new
  157. {
  158. type = "text",
  159. text = "Gracias por contactar a la CFE."
  160. },
  161. // body
  162. body = new
  163. {
  164. text = "Haga click en en menu de opciones para elegir su consulta."
  165. },
  166. // action: options the whatsapp bot displays for the user
  167. // to select with simple numerical commands
  168. action = new
  169. {
  170. button = "Menu de opciones",
  171. sections = new[]
  172. {
  173. new
  174. {
  175. title = "Menu principal",
  176. rows = new[]
  177. {
  178. new {
  179. id = "ROW_CLEAR_BAL",
  180. title = "1",
  181. description = "Para Conocer saldo a favor, responder con 1."
  182. },
  183. new {
  184. id = "ROW_OUT_BAL",
  185. title = "2",
  186. description = "Para Conocer saldo a pagar, responder con 2."
  187. },
  188. new {
  189. id = "ROW_DUE_DATE",
  190. title = "3",
  191. description = "Para conocer fecha limite; responder al bot con 3."
  192. },
  193. new {
  194. id = "ROW_SUPPORT",
  195. title = "4",
  196. description = "Si ninguna opcion satisface, contactar soporte."
  197. }
  198. }// end of rows
  199. }// end of new JSON/cURL block
  200. }//end of sections
  201. }//end of action
  202. }// end of interactive block
  203. };
  204.  
  205. // these two lines of code encapsulate the aforementioned...
  206. var content = new StringContent(JsonSerializer.Serialize(jsonBody), Encoding.UTF8, "application/json");
  207. // and then send an asyncronous request, to the graph.facebook webhook, then wait for a response
  208. var response = await _httpClient.PostAsync("PASTE WHATSAPP WEBHOOK URL HERE", content);
  209.  
  210. response.EnsureSuccessStatusCode();
  211. }
  212.  
  213. // this method encapsulates the entire JSON/cURL info that gets
  214. // retrieved from whatever database this mock bot is supposed to
  215. // get its info from, in this case
  216. // the CFE, comision fed de electricidad, from mexico
  217. // here we suppose the client can actually get his
  218. // cleared balance from the bot
  219. public async Task SendClearedBalanceAsync(string toPhoneNumber)
  220. {
  221. var jsonBody = new
  222. {
  223. messaging_product = "whatsapp",
  224. recipient_type = "individual",
  225. to = toPhoneNumber,
  226. type = "interactive",
  227. interactive = new
  228. {
  229. type = "list",
  230. header = new
  231. {
  232. type = "text",
  233. text = "Opcion 1: Mostrar saldo a favor."
  234. },
  235. body = new
  236. {
  237. text = "Usted tiene un saldo a favor de $XX.XX ."
  238. },
  239. action = new
  240. {
  241. button = "Menu de opciones: ",
  242. sections = new[]
  243. {
  244. new {
  245. title = "saldo a favor: ",
  246. // these rows showcase the only 2 options
  247. // A) return to the previous menu
  248. // B) dial costumer support
  249.  
  250. // Option A
  251. // A) return to the previous menu
  252. rows = new[]
  253. {
  254. new {
  255. id = "ROW_RETURN_MENU",
  256. title = "A",
  257. description = "Para volver al menu anterior, escriba A."
  258. },
  259. // Option B
  260. // B) dial costumer support
  261. new {
  262. id = "ROW_REQ_SUPPORT",
  263. title = "B",
  264. description = "Para comunicarse con un ejecutivo, escriba B."
  265. }
  266. }// end of options array
  267. }// end of saldo a favor menu
  268. }// end of section json array
  269. }// end of action json array
  270. }//end of interactive json array
  271. };// end of jsonbody object
  272. }// end of sendclearedbalance method
  273.  
  274.  
  275.  
  276. }// end of whatsappserviceMenuCFE class
  277. }
  278.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement