Created
September 13, 2017 00:21
-
-
Save codediodeio/c473846cac226d522422c27607a0e27c to your computer and use it in GitHub Desktop.
Integrate Twilio with Firebase Cloud Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
The full article is available here https://angularfirebase.com/lessons/sms-texting-with-twilio/
This only works under Google's Flame or Blaze plan. If you have Spark it won't work
@ayoubss any reason why?
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
Thanks for revert
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what should i download or import in order to use this code ?