firebase / codelab-friendlychat-web

The source for the Firebase codelab for building a cross-platform chat app
https://firebase.google.com
Apache License 2.0
1.75k stars 1.77k forks source link

Error CodeLab Firebase Cloud Functions, cannot send notification by FCM. #661

Open jatu-studiobox opened 2 years ago

jatu-studiobox commented 2 years ago

[REQUIRED] Codelab info

CodeLab Firebase Cloud Functions [10. New Message Notifications](https://firebase.google.com/codelabs/firebase-cloud-function

[REQUIRED] Project setup

I clone project from here.

First I follow CodeLab Firebase Hosting FriendlyChat, and I can complete it.

After that, I started to learn CodeLab Firebase Cloud Functions from 6. The Functions Directory by copy folder "codelab-friendlychat-web-main\cloud-functions-start\functions" into my existed CodeLab Firebase Hosting FriendlyChat.

I can follow instuction then success to 8. Welcome New Users

Then, I skip 9. Images moderation, because I think I do not need to know.

[REQUIRED] Describe the problem

Then at 10. New Message Notifications, I follow instruction and coding. But when I test FriendlyChat web, it did not have notification message to display.

I went to my FriendlyChat project on Firebase Console. Goto Functions and found there error.

Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "<HTML>

It cannot send notification by FCM.

Belows are more detail

image

image

image

I am not sure, why there is security error problem. Because I follow instruction.

below is my cloud function code.

// TODO(DEVELOPER): Import the Cloud Functions for Firebase and the Firebase Admin modules here.
// Import the Firebase SDK for Google Cloud Functions.
const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp();

// TODO(DEVELOPER): Write the addWelcomeMessages Function here.
// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(async (user) => {
    functions.logger.log('A new user signed in for the first time.');
    const fullName = user.displayName || 'Anonymous';

    // Saves the new welcome message into the database
    // which then displays it in the FriendlyChat clients.
    await admin.firestore().collection('messages').add({
        name: 'Firebase Bot',
        profilePicUrl: '/images/firebase-logo.png', // Firebase logo
        text: `${fullName} signed in for the first time! Welcome!`,
        timestamp: admin.firestore.FieldValue.serverTimestamp(),
    });
    functions.logger.log('Welcome message written to database.');
});

// TODO(DEVELOPER): Write the blurOffensiveImages Function here.

// TODO(DEVELOPER): Write the sendNotifications Function here.
// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(async (snapshot) => {
    // Notification details.
    const text = snapshot.data().text;
    const payload = {
        notification: {
            title: `${snapshot.data().name} posted ${text ? 'a message' : 'an image'}`,
            body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
            icon: snapshot.data().profilePicUrl || '/images/profile_placeholder.png',
            click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
        }
    };

    // Get the list of device tokens.
    const allTokens = await admin.firestore().collection('fcmTokens').get();
    const tokens = [];
    allTokens.forEach((tokenDoc) => {
        tokens.push(tokenDoc.id);
    });

    if (tokens.length > 0) {
        // Send notifications to all tokens.
        const response = await admin.messaging().sendToDevice(tokens, payload);
        await cleanupTokens(response, tokens);
        functions.logger.log('Notifications have been sent and tokens cleaned up.');
    }
});

below are firebase packages version in package.json

"dependencies": { "@google-cloud/vision": "^2.4.0", "firebase-admin": "^9.9.0", "firebase-functions": "^3.14.1" }

Please advise me, how can I fix this proble?

Thank you very much

nickf2k commented 2 years ago

same issue with me

jatu-studiobox commented 2 years ago

same issue with me

Hi nickf2k,

Can you solve this solution by yourself? Because I has remain stuck this problem.

nickf2k commented 2 years ago

same issue with me

Hi nickf2k,

Can you solve this solution by yourself? Because I has remain stuck this problem.

Try it:

 admin.initializeApp({
    credential: applicationDefault()
});

instead of admin.initializeApp()

jatu-studiobox commented 2 years ago

Hi nickf2k,

I try to use your solution but it has error when deploy functions to firebase.

Error: Failed to load function definition from source: Failed to generate manifest from function source: ReferenceError: applicationDefault is not defined

I am not sure about your firebase-admin version and firebase-functions version. Please advise me about package.json.

Below is my package.json

{
  "name": "friendlychat-codelab",
  "description": "Firebase SDK for Cloud Functions codelab",
  "dependencies": {
    "@google-cloud/vision": "^2.4.0",
    "firebase-admin": "^10.2.0",
    "firebase-functions": "^3.21.2"
  },
  "devDependencies": {
    "eslint": "^4.12.0",
    "eslint-plugin-promise": "^3.6.0"
  },
  "engines": {
    "node": "12"
  },
  "private": true
}
jatu-studiobox commented 2 years ago

same issue with me

Hi nickf2k, Can you solve this solution by yourself? Because I has remain stuck this problem.

Try it:

 admin.initializeApp({
    credential: applicationDefault()
});

instead of admin.initializeApp()

Hi nickf2k,

Thank you for your help again. I just solve about this problem.

I set Enabled at Cloud Messaging API (Legacy) in Project Settings.

image

Now my FriendlyChat project can use FCM.

But, I notice, why Firebase Cloud Messaging use FCM "Legacy"?

If you or anyone in here know, please describe me.

Thank you very much.

saleem-15 commented 1 year ago

Thanx! this solved my issue !!