2
votes

I'm following this tutorial, I got to the point to send an HTTP request to the fcm endpoint, but I'm getting the following error:

{
    error:
    {
        code: 400,
        message: 'Request contains an invalid argument.',
        status: 'INVALID_ARGUMENT'
    }
}

Instead of sending the request using curl I'm using a cloud function using node.js | express with the following code:

exports.messages = function (req, res) {
    const api = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send';
    const headers = {
        'Accept': 'application/json',
        'Content-type': 'application/json',
    };

    return getAccessToken().then((accessToken) => {
        headers.Authorization = `Bearer ${accessToken}` // <-- accessToken is OK
        const { title, body, token } = req.body;
        return fetch(api, {
            headers,
            method: 'POST',
            body: JSON.stringify(
                {
                    'message': {
                        'token': token, // <-- this is the client fcm token
                        'notification': {
                            'title': title,
                            'body': body
                        }
                    }
                }
            )
        }).then(res => res.json()).then(data => {
                console.log(data);
                res.sendStatus(200);
            }).catch((error) => {
                console.error(error);
            });

    });
}

Where the token is an OAuth 2 token for my service account

function getAccessToken() {
    return new Promise(function (resolve, reject) {
        var key = require('../keys/service-account.json');
        var jwtClient = new google.auth.JWT(
            key.client_email,
            null,
            key.private_key,
            [
                'https://www.googleapis.com/auth/firebase',
                'https://www.googleapis.com/auth/firebase.database',
                'https://www.googleapis.com/auth/firebase.messaging',
            ],
            null
        );
        jwtClient.authorize(function (err, tokens) {
            if (err) {
                reject(err);
                return;
            }
            resolve(tokens.access_token);
        });
    });
}

what am I missing here? any advice will be appreciated

1

1 Answers

2
votes

I just realized I copied the uri for the fcm endpoint from the tutorial. I changed it to:

const api = 'https://fcm.googleapis.com/v1/projects/{project-Id}/messages:send';

and it worked!