Twilio Integration with F#


I decided to document some Twilio integration details for a hobby project that I’m working on.

Sms Module

Here’s the core module for sending an Sms via Twilio:

namespace CourierPayroll.DataGateway

open Twilio
open Twilio.Types
open Twilio.Rest.Api.V2010.Account
open CourierPayroll.DataTransfer

module Sms =

    let formattedNumber (toPhone:string) =
            let usaCode = "+1"
            let phoneWithPrefix =

                if toPhone.Chars 0 <> '+' && toPhone.Chars 0 <> '1'
                then sprintf "%s%s" usaCode toPhone
                elif toPhone.Chars 0 = '1'
                then sprintf "%s%s" "+" toPhone
                else toPhone

            let cleansed = 
                               .Replace(" ","")

            if cleansed.Length <> 12 then
                failwith <| sprintf "Invalid phone length: %s" toPhone


    let send (key:SmsAPIKeys) (ToPhone toPhone) (FromPhone fromPhone) (msg:string) =

        if toPhone.Length < 10 then
            failwith <| sprintf "Invalid phone length: %s" toPhone

        TwilioClient.Init(key.AccountSid, key.AuthToken)

        let source,dest = PhoneNumber(fromPhone), PhoneNumber(formattedNumber toPhone)
        MessageResource.Create(dest,null,source,null, msg) |> ignore

Notify Module

The following code is used to send an approval notification to an applicant:

namespace CourierPayroll.DataGateway

open CourierPayroll.DataTransfer

module Notify =

    let applicant (setup:SmsSetup) (account:Account) =

        let smsAPIKey = { AccountSid = setup.TwilioAccountSid
                          AuthToken  = setup.TwilioAuthToken 
        let fromPhone = FromPhone setup.TwilioPhone
        let toPhone   = ToPhone   setup.AdminPhone
        let name      = account.Holder.Name

        let message = $"Hi {name},\n\n Your courier application has been approved.";
        Sms.send smsAPIKey toPhone fromPhone message

Azure Function Client

Here’s the client code for sending an SMS notification:

        var account = result.ResultValue;

        static void SendNotification(this DataTransfer.Account account)
            var twilioPhone      = GetEnvironmentVariable("TwilioPhone");
            var twilioAccountSid = GetEnvironmentVariable("TwilioAccountSid");
            var twilioAuthToken  = GetEnvironmentVariable("TwilioAuthToken");
            var adminPhone       = GetEnvironmentVariable("AdminPhone");

            var setup = new SmsSetup(twilioPhone, twilioAccountSid, twilioAuthToken, adminPhone);
            Notify.applicant(setup, account);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: