Firebase Cloud Messaging: Internal error encountered - firebase

I'm trying to send push notifications via a Firebase Cloud Function, but getting an internal error.
Error: Internal error encountered.
at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:253:16)
at Function.FirebaseMessagingError.fromServerError (/srv/node_modules/firebase-admin/lib/utils/error.js:283:16)
at Object.createFirebaseError (/srv/node_modules/firebase-admin/lib/messaging/messaging-errors.js:34:47)
at FirebaseMessagingRequestHandler.buildSendResponse (/srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:119:47)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:94:30
at Array.map (<anonymous>)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:93:30
at <anonymous> errorInfo: [Object], codePrefix: 'messaging'
My function is simple enough:
sendPushNotification.js
const admin = require('firebase-admin');
const messaging = admin.messaging();
module.exports = function(title, deepLink, deviceTokens) {
var message = {
notification: {
title: title
},
data: {
deepLink: deepLink,
},
tokens: deviceTokens
};
console.log(`Sending notification ${title} with Deep Link ${deepLink} to ${deviceTokens.length} devices`);
console.log(deviceTokens);
return messaging.sendMulticast(message).then(response => {
console.log(`Success: ${response.successCount}, failure: ${response.failureCount}`);
if (response.failureCount > 0) {
console.log(response.responses)
}
});
}
The weird thing is that sometimes it does work, but maybe one in 10? The other times I get this less-than-helpful error. The APNs Authentication Key is uploaded in the Firebase Console in the project settings. The App Bundle ID is correct. I'm at a loss for what else could be going on.
(Yes, I am giving the function an array of valid deviceTokens.)
None of the other questions on StackOverflow seem to be related to this internal error, the answers on those questions don't apply here.

Related

Why does my opentok method does not work in firebase?

I use a firebase function which executes OpenTok SDK when it is triggered. The function creates a session. I was able to create a session successfully on my local server, but when I put it in production – in firebase- following error occurs:
Error creating session: Error: Failed to createSession. Error: The request failed: Error: getaddrinfo EAI_AGAIN api.opentok.com:443
at createSessionCallback (/srv/node_modules/opentok/lib/opentok.js:1125:16)
at Request._callback (/srv/node_modules/opentok/lib/client.js:59:14)
at self.callback (/srv/node_modules/request/request.js:185:22)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at Request.onRequestError (/srv/node_modules/request/request.js:877:8)
at emitOne (events.js:121:20)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at emitOne (events.js:116:13)
Other methods of this third party SDK like token generation also works on firebase but the method createSession fails. Can you help me please?
exports.dbUpdate = functions.database.ref('/test/{pushId}/text').onUpdate((change, context) => {
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val();
if (beforeData == afterData) {
console.log("Text did not change");
return null;
}
opentok = new OpenTok("...", "...");
var sessionId;
opentok.createSession({
mediaMode: "routed"
}, function(error, session) {
if (error) {
console.log("Error creating session:", error)
token = "Failed";
} else {
sessionId = session.sessionId;
token = opentok.generateToken(sessionId);
}
});
return change.after.ref.parent.child('neuertest').set(token);
});
//The same code works on local server
The free Spark plan only allows for HTTP calls to Google services (see Cloud Functions on https://firebase.google.com/pricing/)
You’ll need to upgrade your plan to be able to run your function

Firebase functions :ApiError: Not Found at Object.parseHttpRespBod : when removing from firebase storage

I'm trying to remove an item from my firebase storage by firebase cloud functions.
But its giving me this error..
Error { ApiError: Not Found
at Object.parseHttpRespBody (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:193:30)
at Object.handleResp (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:131:18)
at /user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:496:12
at Request.onResponse [as _callback] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/node_modules/retry-request/index.js:198:7)
at Request.self.callback (/user_code/node_modules/firebase-admin/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/firebase-admin/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: 404,
errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
response: undefined,
message: 'Not Found' }
And this is my code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var db = admin.firestore();
var storage = admin.storage().bucket('visa_cop');
exports.deletingVisaCop = functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context) =>{
var data = change.after.data().checked;
if(data === true)
{
return storage.delete().then(function(data) {
return console.log("DataIs",data);
}).catch(function(error){
return console.log("Error",error);
});
} else
{
}
});
And I added for Google APIs Service Agent and App Engine default service account storage admin roles from the I am & admin page.
Thank You.
the problem is here:
functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context)
at the moment, the function listens to a document called "visa_cop" in the folder "info". you need to add the token at the end, to tell the function to listen to update of any file in this folder (or you can specify a file if needed).
Just append e.g. /{visaId} after visa_cop, like so:
functions.firestore.document('users/{user_Id}/info/visa_cop/{visaId}').onUpdate((change,context)
Ps. "visaId" can be anything, however it must match the Document Path that you define at function deploy.
in your example, the function listens to any doc in "visa_cop" folder, so if you use:
Console:
Trigger is "Cloud Firestore"
Event Type is "update"
Document Path is "students/{studentId}/visa_cop/{visaId}"
CLI:
gcloud functions deploy [FUNCTION_NAME] \
--runtime [RUNTIME] \
--trigger-event providers/cloud.firestore/eventTypes/document.update \
--trigger-resource "projects/[PROJECT_ID]/databases/(default)/documents/users/{userId}/info/visa_cop/{visaId}"

The registration token is not a valid FCM registration token

I'm trying to send a message to my device using a token I've gotten from a ticket saved in my PassWallet app in my Android device.
The device sends all the information required to update a pass using apple's wallet spec. However, I'm using FCM to send the notification and I'm getting this error: "The registration token is not a valid FCM registration token"
{
errorInfo:
{ code: 'messaging/invalid-argument',
message: 'The registration token is not a valid FCM registration token' },
codePrefix: 'messaging'
}
The code I'm using to send the message is the one from the Admin SDK sample:
var message = {
token: device.pushToken
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
I'm not sure if my message is incomplete and I need something else in
the body.
If the token expired (Where you can verify this on Firebase).
If the message needs to specify whether is Android, iOS(APNS), etc...
This is the full stack trace:
Error: The registration token is not a valid FCM registration token
at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:241:16)
at Function.FirebaseMessagingError.fromServerError (/srv/node_modules/firebase-admin/lib/utils/error.js:271:16)
at FirebaseMessagingRequestHandler.handleHttpError (/srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:125:50)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:113:23
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
errorInfo:
{ code: 'messaging/invalid-argument',
message: 'The registration token is not a valid FCM registration token' },
codePrefix: 'messaging' }
All information about the updated pass you should send to the Passwallet server.
Please find the latest instructions here: https://github.com/Kwiket/passwallet
Passwallet Team

Firebase auth().createUser - Error while making request: timeout of 10000ms exceede

I'm trying to include a list of users (more than 50) through a specific function in Firebase. Here's my code:
Object.keys(newUsers).forEach((key) => {
console.log(newUsers[key]['name']);
admin.auth().createUser({
uid: key,
email: newUsers[key]['email']
password: newUsers[key]['InitialPwd'],
disabled: false,
emailVerified: false,
displayName: newUsers[key]['name'],
}).then((userRecord) => {
return console.log('Success');
}).catch(function(error) {
console.log("Error:", error);
});
});
And the error is (for each record):
{ Error: Error while making request: timeout of 10000ms exceeded.
at FirebaseAppError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseAppError (/srv/node_modules/firebase-admin/lib/utils/error.js:119:28)
at /srv/node_modules/firebase-admin/lib/utils/api-request.js:117:23
at
at process._tickDomainCallback (internal/process/next_tick.js:228:7) errorInfo: { code:
'app/network-timeout',
message: 'Error while making request: timeout of 10000ms exceeded.' }, codePrefix: 'app' }
How can I solve this?
Cloud Functions are set to run for a short period of time. If you are doing lots of work in a Cloud Function, it may time out before it is complete. There are a few solutions to this that I would suggest:
1.Change your Cloud Functions timeout. In the Cloud console, check at the top to make sure your current project is selected, and then in the middle you'll find your list of functions. Click on your function. You should be in function details now. Click "Edit". Right above the "save" button is "more". Select "more" and you'll see an option for upping the timeout. This can modify how long the function stays alive.
2.Change the batch size so you're creating fewer users at a time.
3.Make sure your promises are working as expected. If you don't return the call to createUser, the resulting UserRecord won't be accessible.
Object.keys(newUsers).forEach((key) => {
console.log(newUsers[key]['name']);
return admin.auth().createUser({
uid: key,
email: newUsers[key]['email']
password: newUsers[key]['InitialPwd'],
disabled: false,
emailVerified: false,
displayName: newUsers[key]['name'],
}).then((userRecord) => {
return console.log('Success');
}).catch(function(error) {
console.log("Error:", error);
});
});
4.I may be incorrect about this point, but it appears that the users are created one after another rather than concurrently. This could be a good case to look into using Promise.all so that all of the users can be created simultaneously, rather than waiting for one to complete before starting the next.

paypal integration with firebase functions has errors in logs

I am trying for 3 days to solve this problem but I couldn't.
what I am doing is integrating paypal payment with my android application using firebase cloud functions.
I integrated paypal successfully on my android app. but when i shifted to the second step which is making http triggered function to complete integration I used this code on index.js on cloud functions.
const functions = require('firebase-functions');
const paypal=require('paypal-rest-sdk');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
paypal.configure({
mode:"sandbox",
client_id:functions.config().paypal.client_id,
client_secret:functions.config().paypal.client_secret
});
//Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.payout = functions.https.onRequest((request, response) => {
const sender_batch_id = Math.random().toString(36).substring(9);
const sync_mode ='true';
const payReq = JSON.stringify({
sender_batch_header: {
sender_batch_id: sender_batch_id,
email_subject: "You have a payment"
},
items: [
{
recipient_type: "EMAIL",
amount: {
value: 0.1,
currency: "USD"
},
receiver: "ammah6600#crowns.com",
note: "Thank you.",
sender_item_id: "item_3"
}
]
});
paypal.payout.create(payReq,sync_mode,(error,payout) =>{
if(error){
console.warn(error.response);
response.status('500').end();
throw error;
}else{
console.info("payout created");
console.info(payout);
response.status('200').end();
}
});
});
****but**
I found these problems in Logs of firebase functions**
1-
`
{ name: 'SYNC_MODE_NOT_APPLICABLE',
message: 'Synchronous mode will soon be deprecated and is no longer available for new integrations. You can use the asynchronous mode by specifying sync_mode= false in the request.',
debug_id: '393880ab5b7a9',
information_link: 'https://developer.paypal.com/docs/api/payments.payouts-batch/#errors',
httpStatusCode: 403 }`
2
-Error: Response Status : 403
at IncomingMessage.<anonymous> (/user_code/node_modules/paypal-rest-sdk/lib/client.js:130:23)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
Then I changed sunc_mode to false but i found these problems appeared to me:
1-
{ name: 'INSUFFICIENT_FUNDS',
debug_id: 'b2a6e96353ee7',
message: 'Sender does not have sufficient funds. Please add funds and retry.',
information_link: 'https://developer.paypal.com/docs/api/payments.payouts-batch/#errors',
httpStatusCode: 422 }
2-
Error: Response Status : 422
at IncomingMessage.<anonymous> (/user_code/node_modules/paypal-rest-sdk/lib/client.js:130:23)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
Please help me in reviewing my codes or credentials
regarding that my country is egypt
my merchant account is us also receiver account

Resources