Follow @endyourif rss Facebook LinkedIn

Integrating with Twilio using C# Integrating with Twilio using C#

Published on Feb 7, 2020

I like when integrations like Twilio are simple and straightforward. I recently had the privilege of implementing it for my company. For my implementation I have a couple of special requirements that I think makes my solution better than just referencing a NuGet package and calling MessageResource.Create.

My requirements require creating user controlled text messaging templates and customer controlled enabling/disabling of one or more text messages. Let's get started.

Integrating with Twilio using C#

Using Twilio with C# and MVC

I'm going to begin by describing the code hierarchy I plan to implement. The pattern follows how I implemented and described in my book ASP.NET MVC with Bootstrap and Knockout.js where I describe a project flow of Controller -> Orchestration -> Service -> Repository. From services there is also a flow to what I call Behaviors.

The controller - TextMessageController.cs - will be the starting point. It will accept information about the customer and what message should be sent. In this example it will be a "welcome message". This controller will use a customer ID and fetch the customer's phone number.

The controller will then call the TextMessageOrchestration that accepts the message type and the customer's phone number. The message type will be an enum. The orchestration will be responsible for 3 things:

  1. Fetching the text message template from the database
  2. Calling a behavior to confirm that the account and customer are configured and wish to receive text messages
  3. Call my Twilio service to send the templated message

In my code I've setup automatic dependency injection with using Ninject which is why you'll see interfaces being auto instantiated by constructor variables.


using System.Linq;
using Behaviours.Handlers;
using ExternalApiClients.Twilio;
using Model;
using Services;
namespace Orchestrations.Implementation
{
public class TxtMessageOrchestration : ITxtMessageOrchestration
{
private readonly IAccountService _accountService;
private readonly ITwilioApiClient _twilioApiClient;
private readonly ITxtEnabledHandler _txtEnabledHandler;
public TxtMessageOrchestration(IAccountService accountService, ITwilioApiClient twilioApiClient, ITxtEnabledHandler txtEnabledHandler)
{
_accountService = accountService;
_twilioApiClient = twilioApiClient;
_txtEnabledHandler = txtEnabledHandler;
}
public void Send(TxtType txtType, string phoneNumber)
{
var txtTemplate = _accountService.GetTextTemplate(txtType);
if (_txtEnabledHandler.Enabled(txtTemplate))
{
_twilioApiClient.Send(txtTemplate.TwilioSid, phoneNumber,
txtTemplate.TxtBody);
}
}
}
public enum TxtType {
WelcomeMessage,
AnyOtherType
}
}

The TxtEnabledHandler is quite simple where it checks that the txtTemplate.Enabled is true. For my requirements I have a lot more other settings that I've split this into a behavior where I wrote over 40 unit tests for the 5 or 6 different combinations of settings that identify whether to send or not. You can also explore leveraging the JavaScript Fetch API if you're not able to use C#.

And finally, let's look at the TwilioApiClient:


using System;
using System.Configuration;
using System.Web;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
namespace ExternalApiClients.Twilio.Implementation
{
public class TwilioApiClient : ITwilioApiClient
{
public TwilioApiClient()
{
TwilioClient.Init(ConfigurationManager.AppSettings["Twilio.ApplicationKey"], ConfigurationManager.AppSettings["Twilio.ApplicationSecret"]);
}
public void Send(string twilioSid, string phoneNumber, string txtBody)
{
var url = new Uri(string.Format("https://{0}/v1/TwilioListener", HttpContext.Current.Request.Url.Host));
MessageResource.Create(
body: txtBody,
to: phoneNumber,
messagingServiceSid: twilioSid,
statusCallback: url
);
}
}
}

I've setup a webhook listener for a controller called TwilioListener that I've set as the callback URL so I can read responses from Twilio. This code requires the Twilio NuGet package.

That's it, I now have an excellent structure to add many different text message templates with only a single dependent class on Twilio which in a worse-case scenario would be easy to swap out.

Tags: ASP.NET MVC and Web API Tutorial | twilio

About Jamie Munro

Welcome to my blog. I have been compiling articles since 2009! Below is a list of every post I've ever created. Some of my major focuses have been compiling the best source of jQuery tutorials on the Internet today. A recent focus of mine is now focusing on creating the best SQL Tutorials for Beginners, Intermediate and Advanced Users. This is a compiliation of all my experience about how to do common SQL commands to optimize for performance. As you might see from the links around here, I've also written and published 5 books. My first and last book are focused around ASP.NET MVC and Web API tutorials. The last book has a big focus on integrating Knockout.js as the MVVM for the front-end code. O'Reilly Media was so interested in Knockout.js that they actually commissioned me to write that book first as it is one of the only books dedicated entirely to this MVVM library. So if you're looking for the best Knockout.js tutorials, I've compiled the best list. My first book, even though it was self published, was on the PHP framework: CakePHP. I used this framework for years and many of my first ever exampes were all focused on CakePHP tutorials that provide so many fantastic PHP examples. There are so many Javascript tutorials out there, but I noticed that one of the things I work on most with Javascript is arrays. With this I've worked hard on compiling a big list of really advanced Javascript array examples. These array examples are amazing including how to group by, get distinct array elements and so many more. I've also dabbled a little bit with Node.js and during those experiments I definitely ran into some common errors like Can't set headers after they are sent, Solving No Access-Control-Allow-Origin with Node js and Express, and Uncaught ReferenceError: require is not defined. With these common errors I've compiled a list of Node.js tutorials that help solve these problems, but more importantly getting you started with the basics.