Get user phone number in firebase cloud functions

Viewed 1288

I've written https.onCall firebase cloud function like

exports.sampleFunction=functions.https.onCall((data,context)=>{
console.log(context.auth.token.phoneNumber+" ***** "+context.auth.token.email+" ***** "+context.auth.token.name);
  return userTransaction.sampleFunction(data,context).then(function(message){
    console.log(message);
  })
});

I'm storing the user's phone number and can fetch phone number at client using

FirebaseAuth auth=FirebaseAuth.getInstance();
        FirebaseUser user=auth.getCurrentUser();
        user.getPhoneNumber();

When I'm calling this function, I can see that email and name is getting printed at firebase cloud functions logs but phoneNumber is undefined. How to get user phone number through context in firebase cloud functions?

2 Answers

So much easier:

exports.myFunction = functions.https.onCall((data, context) => {
    const phone = context.auth.token.phone_number;
})

The following, using admin.auth().getUser(uid) should work:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
....

exports.sampleFunction = functions.https.onCall((data,context) => {

  return admin.auth().getUser(context.auth.uid)
    .then(userRecord => {
      const phoneNumber = userRecord.phoneNumber;
      console.log(phoneNumber+" ***** "+context.auth.token.email+"      ***** "+context.auth.token.name);   
      return userTransaction.sampleFunction(data,context)    //Not sure what this is doing, I just chained it with the previous and next then(s). Modify as necessary....
    })
    .then(message => {
      console.log(message);
      return { message: message };
    })

});

See the corresponding docs here and here. Note that getUser() returns a promise.

Related