dimanche 26 septembre 2021

Firebase cloud messaging http send message request

when I run the code below (in a vue project) that get the access token for auth purpose for firebase cloud messaging HTTP request and then get user permission for notifications and subscribe it to push service API then when I want to send the notification to the subscribe user (...continue below the code):

        function getAccessToken() {
        return new Promise(function(resolve, reject) {
            const key = require('../service-account.json');
            const {JWT} = require('google-auth-library');
            const SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
            const jwtClient = new JWT(
                key.client_email,
                null,
                key.private_key,
                SCOPES,
                null
            );
            jwtClient.authorize(function(err, tokens) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(tokens.access_token);
            });
        });
    }
    var subscribtion = null;
    Notification.requestPermission().then((res) => {
        navigator.serviceWorker.getRegistration().then(reg => {
            reg.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: //Firebase cloud messaging key pair
            }).then(sub => {
                subscribtion = sub.toJSON();
                subscribtion.endpoint = 'https://calm-reef-09931.herokuapp.com/' + subscribtion.endpoint;
                // console.log(subscribtion);
                getAccessToken().then(accessToken => {
                    const webPush = require('web-push');
                    const payload = "hi this is payload";
                    const options = {
                        TTL: 60,
                        headers: {
                            'Authorization': 'Bearer ' + accessToken,
                        }
                    }
                    webPush.sendNotification(subscribtion, payload, options)
                })
            })
        })
    })

I got a 403 (Forbidden) error that tell me

Missing required request header. Must specify one of: origin,x-requested-with

any help? thanks a lot :);




Aucun commentaire:

Enregistrer un commentaire