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)
}
@mubasshir
Copy link

Thanks for revert

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