Menu

Writing Twilio service to send SMS (TXT) Australian mobile number

In one of my previous blog post I have put together a service to verify valid Australian mobile number, in this post I will share the service I use to send SMS (TXT) messages to mobile numbers.

Just like my previous integration, I will use the RESTful interface rather than the Twilio C# client library.

You will need to set up an account and you receive around $20 credit, but you can send SMS (TXT) only to your sign up number only, during the trail period. You will need to set up the “AccountSid” and “AuthToken” from the portal.

Below is the interface.

public interface ITwilioSMSService
{
  Task<bool> SendSMSAsync(string countryCode, string mobileNumber, string message);
}

Below is the implementation

public class TwilioSMSService : ITwilioSMSService
    {
        private const string BaseUrl = @"https://api.twilio.com/2010-04-01/Accounts/";
        private readonly TwilioSettings _twilioSettings;

        public TwilioSMSService(IOptions<TwilioSettings> twilioSettings)
        {
            _twilioSettings = twilioSettings.Value;
        }

        public async Task<bool> SendSMSAsync(string countryCode, string mobileNumber, string message)
        {
            using (var client = new HttpClient())
            {
                var model = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("To", $"{countryCode}{mobileNumber}"),
                    new KeyValuePair<string, string>("From", _twilioSettings.SMSFrom),
                    new KeyValuePair<string, string>("Body", message),
                });

                var basicHeader = Encoding.ASCII.GetBytes($"{_twilioSettings.SMSAccountSid}:{_twilioSettings.SMSAuthToken}");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(basicHeader));
                var response = await client.PostAsync($"{BaseUrl}{_twilioSettings.SMSAccountSid}/Messages.json", model);
                response.EnsureSuccessStatusCode();

                if (response.StatusCode == System.Net.HttpStatusCode.Created)
                    return true;

                return false;
            }
        }
    }

Hope this will help to fast track your development.

Leave a comment