I use Firebase Cloud Messaging to deliver notifications to my Android client apps, each notification should be sent to a single device according to its registration token.
Each time I send a notification via https://fcm.googleapis.com/fcm/send, I receive a JSON response like this one:
{
"multicast_id": 108,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{ "message_id": "1:08" }
]
}
I find success and failure redundant - don't they mean the same thing? Should I check both of them to be sure everything is fine? Is it always true that success != failure?
As described here :
success - Required, number of messages that were processed
without an error.
failure - Required, number of messages that
could not be processed.
You get :
"success": 1, which means 1 message was processed successfully and
"failure": 0, which means no error
total number of requests to FCM server = success + failure
Sum of success and failure makes up the total number of requests. In your case, when you're sending to one user only, it doesn't matter. But when you're sending to multiple users, you can get success and failure and sum them up to know how many requests were sent to FCM server.
Ref: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
As described above in response I got:
{{
success: true,
messageId: someid,
},
{
success: false,
error: [yourerror],
},
successCount: 1,
failureCount:1,
}
In my case, 1 fcmtoken expired, so 1 failure.
successCount means how many of the notifications were sent and failureCount are the tokens that caused the error.
Add the notification parameter along with data and registration_ids.
{"notification":{"title":"","body":""},"data":{},"registration_ids":["acaxdYt5464262hghdsd*****"]
}
Related
I am using the google app engine URL:'https://android.googleapis.com/gcm/send' and I receive the success key to be 1 as the response. But my app never receives the notification. What could be the reason for this?
My response body:
{
u'failure': 0,
u'canonical_ids': 1,
u'success': 1,
u'multicast_id': 4739141336251800642,
u'results':
[
{
u'registration_id': u'<reg-id>',
u'message_id': u'0:1506410197124608%1e7d6f91f9fd7ecd'
}
]
}
with Parse.com I used to be able to send push notifications via simple https post requests, something like:
{
"registration_ids": ["some_device_token_from_the_dashboard"],
"data": { "title": "How are you", "message": "Ok?" }
}
I added a json content type and set Authorization to key=server_key.
Another tool that could be used is: http://www.androidbegin.com/tutorial/gcm.html
Anyway, I'm working with the android SDK v4.13.1 and Parse-server v2.2.16, when I use the dashboard to send push notification to everyone I get the notification, but when I try the post request that used to work with parse.com, the response is:
{
"multicast_id": 8851650859439498656,
"success": 1, "failure": 0,
"canonical_ids": 0,
"results":[ { "message_id": "0:1470077514727128%33b2cdf9f9fd7ecd" } ]
}
It looks like all is find but I don't get the notification at all, btw at the google console I didn't set the IP field so it accepts requests from 0.0.0.0(all interfaces), I assume there something I'm missing here, should the post request be different, what am I doing wrong?, is that a bug or?...
Edit:
Just to clerify, I implement my on PushReceiver that extends ParsePushBroadcastReceiver, and as before when I try to send push via simple post request(using my server-key and registration id) it won't work(the onPushReceive method never called).
POST request details:
My endpoint is https://android.googleapis.com/gcm/send(I did try gcm-http.googleapis.com/gcm/send as well)(https://developers.google.com/cloud-messaging/http for more details), Content-Type set to application/json and Authorization set to key=server_key, the content is given at the beginning of the question.
I am writing app server side of FCM implementation where it will send a particular message to Multiple devices.
I am using registration_ids as key and JsonArray with multiple recipients, however the response returned is showing only for one recipient as follows
{"multicast_id":7185150746202793615,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I am not sure whether to set any property in firebase console to enable multiple registration ids acceptance.
Following is the request json :
{
"registration_ids":[
[
"eU6HKx7QRMc:APA91bEIoJtHmTFz_MzUgbMkoZvwdlXzrMDbCB1via_fV16MRF_Xc0C0KkkVA1diR8QgzRdQtkCy-6JDd5it_NSaiIbIlBDDi0g2GFkmrE4ESMi43dBODBePQrzFLqiKeDmX26DkXB8i",
"FERTeU6HKx7QRMc:APA91bEIoJtHmTFz_MzUgbMkoZvwdlXzrMDbCB1via_fV16MRF_Xc0C0KkkVA1diR8QgzRdQtkCy-6JDd5it_NSaiIbIlBDDi0g2GFkmrE4ESMi43dBODBePQrzFLqiKeDmX26DkXB8i"
]
],
"notification":{
"title":"Hello FCM",
"text":"Notification details"
},
"time_to_live":3600,
"priority":"HIGH"
}
And the response for this request is
{
"multicast_id":7697036511101523125,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[
{
"error":"InvalidRegistration"
}
]
}
The Problem was with this Json formation for request. It has to be
{
"registration_ids"[ "eU6HKx7QRMc:APA91bEIoJtHmTFz_MzUgbMkoZvwdlXzrMDbCB1via_fV16MRF_Xc0C0KkkVA1diR8QgzRdQtkCy-6JDd5it_NSaiIbIlBDDi0g2GFkmrE4ESMi43dBODBePQrzFLqiKeDmX26DkXB8i",
"FERTeU6HKx7QRMc:APA91bEIoJtHmTFz_MzUgbMkoZvwdlXzrMDbCB1via_fV16MRF_Xc0C0KkkVA1diR8QgzRdQtkCy-6JDd5it_NSaiIbIlBDDi0g2GFkmrE4ESMi43dBODBePQrzFLqiKeDmX26DkXB8i" ],
"notification":{
"title":"Hello FCM",
"text":"Notification details"
},
"time_to_live":3600,
"priority":"HIGH"
}
The extra square brackets ([ ]) is causing the issue.
xamarian Android project not always receives the push message triggered from push.gcm.send(). Broadcast receiver calls only onregister() first time, but not calls onmessage(). my php server script works well with https://android.googleapis.com, and it calls onmessage() of broadcast reciver. Also Native android project with azure mobile service use push sharp client behaves same, it doesn't call onmessage() when push.gcm.send() executed in azure server. let me know what iam doing wrong, i use the perfect Applicationkey,server key,project number,........Below is the log details.I am getting status code 201.
Log entry details:
INFORMATION
Test Push notification sent: APA91bELUme4gM35eHBH4dmxo7AVBkmVu6Gsown_8zrROb5SsKzHn7MgpypBirmmDDuyPlr8hRjBDRX2lBc_j9voAPYv2RotXiVTHMaXFRRADu0xNfrPk-g-bCkfsCO7Uv-OnPMW8bgmTHIX8u8exKpGxfSrFZvN8dEDAoC5iw { isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
'content-type': 'application/xml; charset=utf-8',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Tue, 27 May 2014 19:40:00 GMT' },
md5: undefined }
Input Script:
function insert(item, user, request) {
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
push.gcm.send(item.channel, item.text, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
}
Please double-check your test is correct by ensuring your client code matches the completed example with appropriate fields replaced from here: http://go.microsoft.com/fwlink/p/?linkid=331303&clcid=0x409
The full instructions are found at: http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-mobile-services-android-get-started-push/
If you still encounter issues after double-checking these, send me email at toddreif#microsoft.com with your Mobile Service account name.
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});
Can anyone please help me with the sample code for google push notifications. I am getting an error in json message.
Here is the code:
local googleApiKey = "**********************"
local googleRegistrationId = nil
-- Called when a sent notification has succeeded or failed.
local function onSendNotification(event)
local errorMessage = nil
-- Determine if we have successfully sent the notification to Google's server.
if event.isError then
-- Failed to connect to the server.
-- This typically happens due to lack of Internet access.
errorMessage = "Failed to connect to the server."
elseif event.status == 200 then
-- A status code of 200 means that the notification was sent succcessfully.
print("Notification was sent successfully.")
elseif event.status == 400 then
-- There was an error in the sent notification's JSON data.
errorMessage = event.response
elseif event.status == 401 then
-- There was a user authentication error.
errorMessage = "Failed to authenticate the sender's Google Play account."
elseif (event.status >= 500) and (event.status <= 599) then
-- The Google Cloud Messaging server failed to process the given notification.
-- This indicates an internal error on the server side or the server is temporarily unavailable.
-- In this case, we are supposed to silently fail and try again later.
errorMessage = "Server failed to process the request. Please try again later."
end
-- Display an error message if there was a failure.
if errorMessage then
native.showAlert("Notification Error", errorMessage, { "OK" })
end
end
-- Sends the given JSON message to the Google Cloud Messaging server to be pushed to Android devices.
local function sendNotification(jsonMessage)
-- Do not continue if a Google API Key was not provided.
if not googleApiKey then
return
end
-- Print the JSON message to the log.
print("--- Sending Notification ----")
print(jsonMessage)
-- Send the push notification to this app.
local url = "**************************"
local parameters =
{
headers =
{
["Authorization"] = "key=" .. googleApiKey,
["Content-Type"] = "application/json",
},
body = jsonMessage,
}
network.request(url, "POST", onSendNotification, parameters)
end
-- Sends a push notification when the screen has been tapped.
local function onTap(event)
-- Do not continue if this app has not been registered for push notifications yet.
if not googleRegistrationId then
return
end
-- Set up a JSON message to send a push notification to this app.
-- The "registration_ids" tells Google to whom this push notification should be delivered to.
-- The "alert" field sets the message to be displayed when the notification has been received.
-- The "sound" field is optional and will play a sound file in the app's ResourceDirectory.
-- The "custom" field is optional and will be delivered by the notification event's "event.custom" property.
local jsonMessage =
[[
{
"registration_ids": ["]] .. tostring(googleRegistrationId) .. [["],
"data":
{
"alert": "Hello World!",
"sound": "notification.wav",
"custom":
{
"boolean": true,
"number": 123.456,
"string": "Custom data test.",
"array": [ true, false, 0, 1, "", "This is a test." ],
"table": { "x": 1, "y": 2 }
}
}
}
]]
sendNotification(jsonMessage)
end
Runtime:addEventListener("tap", onTap)
-- Prints all contents of a Lua table to the log.
local function printTable(table, stringPrefix)
if not stringPrefix then
stringPrefix = "### "
end
if type(table) == "table" then
for key, value in pairs(table) do
if type(value) == "table" then
print(stringPrefix .. tostring(key))
print(stringPrefix .. "{")
printTable(value, stringPrefix .. " ")
print(stringPrefix .. "}")
else
print(stringPrefix .. tostring(key) .. ": " .. tostring(value))
end
end
end
end
-- Called when a notification event has been received.
local function onNotification(event)
if event.type == "remoteRegistration" then
-- This device has just been registered for Google Cloud Messaging (GCM) push notifications.
-- Store the Registration ID that was assigned to this application by Google.
googleRegistrationId = event.token
-- Display a message indicating that registration was successful.
local message = "This app has successfully registered for Google push notifications."
native.showAlert("Information", message, { "OK" })
-- Print the registration event to the log.
print("### --- Registration Event ---")
printTable(event)
else
-- A push notification has just been received. Print it to the log.
print("### --- Notification Event ---")
printTable(event)
end
end
-- Set up a notification listener.
Runtime:addEventListener("notification", onNotification)
-- Print this app's launch arguments to the log.
-- This allows you to view what these arguments provide when this app is started by tapping a notification.
local launchArgs = ...
print("### --- Launch Arguments ---")
printTable(launchArgs)
Whenever this code is called and Error 400 notification appears. Is there a way to send custom push notifications to android device using corona?
Json is completely fine. There might be the problem of url you set up and for triangle notification problem you can go through the following link:
http://jsonlint.com/#