Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Created September 13, 2017 00:21
Show Gist options
  • Save codediodeio/c473846cac226d522422c27607a0e27c to your computer and use it in GitHub Desktop.
Save codediodeio/c473846cac226d522422c27607a0e27c to your computer and use it in GitHub Desktop.
Integrate Twilio with Firebase Cloud Functions
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const twilio = require('twilio');
const accountSid = functions.config().twilio.sid
const authToken = functions.config().twilio.token
const client = new twilio(accountSid, authToken);
const twilioNumber = '+19168274107' // your twilio phone number
exports.textStatus = functions.database
.ref('/orders/{orderKey}/status')
.onUpdate(event => {
const orderKey = event.params.orderKey
console.log(event)
return admin.database()
.ref(`/orders/${orderKey}`)
.once('value')
.then(snapshot => snapshot.val())
.then(order => {
const status = order.status
const phoneNumber = order.phoneNumber
if ( !validE164(phoneNumber) ) {
throw new Error('number must be E164 format!')
}
const textMessage = {
body: `Current order status: ${status}`,
to: phoneNumber, // Text to this number
from: twilioNumber // From a valid Twilio number
}
return client.messages.create(textMessage)
})
.then(message => console.log(message.sid, 'success'))
.catch(err => console.log(err))
});
/// Validate E164 format
function validE164(num) {
return /^\+?[1-9]\d{1,14}$/.test(num)
}
@mjohnr
Copy link

mjohnr commented Feb 23, 2018

what should i download or import in order to use this code ?

@atereshkov
Copy link

@Ayoubsss
Copy link

This only works under Google's Flame or Blaze plan. If you have Spark it won't work

@mubasshir
Copy link

@ayoubss any reason why?

@YonathanMeguira
Copy link

it wont work without billing set up, so yes you need either Flame or Blaze plan. the reason is that cloud functions in their free usage has lots of latency and is very restricted. if you try this with a free version, look in the functions call logs and you will see this explanation

@mubasshir
Copy link

Thanks for revert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment