Menu

Writing Twilio service to validate Australian mobile number

Hmm. after long time I am writing a blog post. I have been busy. Family and work take up time. You know how it is.

Recently I have given the task the validate the mobile number, lets say its for two authentication. But my purpose is different, lets leave it with that. So bottom line, you send a SMS (TXT)/Voice message to given mobile number, for SMS (TXT) based  verification will receive a 4 digits number which they will enter back. and that number get validated. You can use your own database for this if you want, but you will have to use a SMS/Voice service for the rest. But  Twilio has this build in, why not use it.

You can use the Twilio client library for this if you want, But I prefer the RESTfull interface, as I don’t want to bring many 3rd party library to my project. Lets see how it looks like (hope some one has a gun to my head, when I code to do it clean as possible.)

Interface as below

public interface ITwilioMobileNumberValidationService
{
  Task<SendValidationCodeResponse> SendValidationCodeAsync(string countryCode, string mobileNumber);
  Task<TwilioBaseResponse> VerifyVerificationCodeAsync(string countryCode, string mobileNumber, string verificationCode);
}

Actual implementation

    public class TwilioMobileNumberValidationService : ITwilioMobileNumberValidationService
    {
        private const string BaseUrl = @"https://api.authy.com/protected/json/phones/verification/";
        private readonly TwilioSettings _twilioSettings;

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

        public async Task<SendValidationCodeResponse> SendValidationCodeAsync(string countryCode, string mobileNumber)
        {
            using (var client = new HttpClient())
            {
                var model = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("via", "sms"),
                    new KeyValuePair<string, string>("country_code", countryCode),
                    new KeyValuePair<string, string>("phone_number", mobileNumber),
                });

                var response = await client.PostAsync($"{BaseUrl}start?api_key={_twilioSettings.VerifyApiKey}", model);
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<SendValidationCodeResponse>(content);
            }
        }

        public async Task<TwilioBaseResponse> VerifyVerificationCodeAsync(string countryCode, string mobileNumber, string verificationCode)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync($"{BaseUrl}check?api_key={_twilioSettings.VerifyApiKey}&country_code={countryCode}&phone_number={mobileNumber}&verification_code={verificationCode}");
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<TwilioBaseResponse>(content);
            }
        }
    }

DTO objects

    public class TwilioBaseResponse
    {
        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        [JsonProperty(PropertyName = "success")]
        public bool Success { get; set; }
    }

    public class SendValidationCodeResponse : TwilioBaseResponse
    {
        [JsonProperty(PropertyName = "carrier")]
        public string Carrier { get; set; }

        [JsonProperty(PropertyName = "is_cellphone")]
        public bool IsCellphone { get; set; }

        [JsonProperty(PropertyName = "seconds_to_expire")]
        public int SecondsToExpire { get; set; }

        [JsonProperty(PropertyName = "uuid")]
        public string UUID { get; set; }
    }

Hope this helps

 

Leave a comment