-
-
Save Dubemtopsite/0369f7d44f7dc06fe090e48dbfd9acc5 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment