在响应中出现以下错误
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
以下是根据文章使用的代码:
var rp = require('request-promise');
var fs = require('fs');
var google = require('googleapis');
var request = require("request");
var SCOPES = ['https://www.googleapis.com/auth/firebase.messaging'];
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./test-firebase-2-firebase-adminsdk-9n4rb-6a33f8d856.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
getAccessToken().then(function(accessToken) {
console.log("AT : "+accessToken);
bodyObj = {"endpoint":"https://fcm.googleapis.com/fcm/send/eLdk3sJBXwk:APA91bEUbGhrzMrO09NkvAp_zKHP5oUYTKRhdWvkVUBNmLRPb6HHgtNyOfD_WEKqxXzqXBlqJEt1HHD_XE1sN2YecLnehEQPHfXHFX16WxXo4DzxUyEW6LNNaGconHYrNAJ7kPOsNCyt","keys":{"p256dh":"BGhtJDtRDUGUnt3hR5TFIGH35TGsa_XPz7uKG7yos6xWNxngRha1Hz7uHqms6E4XuhsuSqk1tJzhLdfpkmElJaA","auth":"p_Euf4uiM8hOakFPsZIR5g"}};
var options = {
method: 'POST',
url: 'https://iid.googleapis.com/v1/web/iid',
headers:
{
'Authorization' : 'Bearer '+accessToken,
'Crypto-Key': 'p256ecdsa=<Public Key>',
'Content-Type': 'application/json'
},
body: bodyObj,
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log('Request end');
console.log(body);
});
});