Send SMS using POST request from Firebase Cloud Function

Viewed 997

I have an SMS API from textlocal which I want to use to send SMS using Cloud function when a new Document is created in Firestore Collection. Collection name: Booking SMS. It will have a document created with fields 'number', 'name' & 'service'. Now SMY API need few parameters to send SMS.

API URL: 'https://api.textlocal.in/send/'

  1. Apikey
  2. Sender
  3. Message. Message will be constructed as 'Hi, 'name' your booking of 'service' is confirmed.

Name, service & number will be from Firestone document and apikey and sender will be coded in cloudfunction code. Now I want to create cloudfunction trigger which will send sms when document is created. Below is incomplete code I tried please help me to complete it.

    const functions = require('firebase-functions');
   const admin = require("firebase-admin");
 const axios = require("axios");

 admin.initializeApp()


 exports.sendSMS = functions.firestore
.document('BookingSMS/{BookingSMSId}')
.onCreate((snap, context) => {

    const smsOptions = axios.create( {
        baseURL: "https://api.textlocal.in/",
        params: {
            apiKey: "xQ1Fvg7uv14NaAEQHl2D", //Text local api key
            sender: "ASDASD",
            test: "true",
            number: snap.data().phone,
            service: snap.data().service,
            message: `Hi, Your Booking for ${snap.data().service} is 
 Confirmed. Thank You.`
         }


    });
    smsOptions.post("/send");

});

I also want to add +91 before number. and construct message using name and service.

1 Answers

As per the documentation, there is no direct support for node.js. You should be able to use their get request though. (Hope you're familiar with async/await) Try:

async function bookSMS(user) {
        // 5. Send booking SMS to users
        const smsoption = {
                apikey: 'asasasasasasasasas',
        sender: 'DDDDDD'
                to: '${user.phone}',
                message: 'Welcome!',

        }
        // 6. Process the sending of this SMS
        await fetch(`https://api.textlocal.in/send/?apikey=${apiKey}&numbers=${user.phone}&message=Welcome!&sender=DDDDDD`)
}

You must enable billing to access external APIs in firebase

Related