Sending Push Notification using javaScript in Parse - javascript

Actually we are done with sending push notification from mobile to mobile & parse to mobile using parse quires. Now we are trying to send push notification from web application to mobile device using Javascript.
function authentication() {
Parse.$ = jQuery;
// Initialize Parse with your Parse application javascript keys
Parse.initialize("app key",
"javascript key");
Parse.Push.send({
//where: pushQuery,
channels: [ "Demo","Done" ],
data: {
alert : "Hello word"
}}, { success: function() {
// Push was successful
alert : "Push was successful"
// debugger;
},
error: function(error) {
}}).then (function(error) {
//Marks this promise as fulfilled,
//firing any callbacks waiting on it.
});
}
Plz Guide us,we are new to javascript.
we getting error like this
POST https://api.parse.com/1/push 400 (Bad Request)

Did you activate Client Push Enabled in the Push Notifications settings of your Parse app ?
However, if you decide to send notifications from the JavaScript SDK outside of Cloud Code or any of the other client SDKs, you will need to set Client Push Enabled in the Push Notifications settings of your Parse app.
From: https://parse.com/docs/js/guide#push-notifications-sending-pushes
Note that you shouldn't send notification from any clients, instead trigger the notifications from cloud code
However, be sure you understand that enabling Client Push can lead to a security vulnerability in your app, as outlined on our blog. We recommend that you enable Client Push for testing purposes only, and move your push notification logic into Cloud Code when your app is ready to go into production.

I am also sending the notification from javascript to Mobile using parse.
My code is almost similar to you except one thing,
Instead of this
Parse.initialize("app key",
"javascript key");
I am using
Parse.initialize("APP_ID", "API_KEY", "JAVASCRIPT KEY");
My complete code is.. though I am using node.js you can relate to corresponding code.
var query = new Parse.Query(Parse.Installation);
query.equalTo('installationId', parseInstallationId);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Willie Hayes injured by own pop fly."
}
}, {
success: function() {
// Push was successful
console.log('successful');
},
error: function(error) {
// Handle error
console.log('error');
}
});

Related

PouchDB and React-Native not replicating .to() but .from() is working

For some reason documents created on my app are not showing up on my remote couchdb database.
I am using the following
import PouchDB from 'pouchdb-react-native'
let company_id = await AsyncStorage.getItem('company_id');
let device_db = new PouchDB(company_id, {auto_compaction: true});
let remote_db = new PouchDB('https://'+API_KEY+'#'+SERVER+'/'+company_id, {ajax: {timeout: 180000}});
device_db.replicate.to(remote_db).then((resp) => {
console.log(JSON.stringify(resp));
console.log("Device to Remote Server - Success");
return resp;
}, (error) => {
console.log("Device to Remote Server - Error");
return false;
});
I get a successful response the response:
{
"ok":true,
"start_time":"2018-05-17T15:19:05.179Z",
"docs_read":0,
"docs_written":0,
"doc_write_failures":0,
"errors":[
],
"last_seq":355,
"status":"complete",
"end_time":"2018-05-17T15:19:05.555Z"
}
When I go to my remote database, document_id's that am able to search and grab on the application do not show up.
Is there something I am not taking into account?
Is there anything I can do to check why this might be happening?
This worked when I used the same scripting method in Ionic and when I switched to React-Native I noticed this is the case.
NOTE: When I do .from() and get data from remote to the device, I get the data. For some reason it just isn't pushing data out
"Is there anything I can do to check why this might be happening?"
I would try switching on debugging as outlined here.
PouchDB.debug.enable('*');
This should allow you to view debug messages in your browser's JavaScript console.

Firebase FCM error: 'InvalidRegistration'

I am currently trying to send a PushNotification to a Device Group using FCM with the help of Firebase Cloud Functions but once the notification is sent, it returns with code 200 but with failure :
SUCCESS response= {
multicast_id: 8834986220110966000,
success: 0,
failure: 1,
canonical_ids: 0,
results: [ { error: 'InvalidRegistration' } ]
}
Here is the code I am using to send this notification... what am I missing?
const options = {
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=' + serverKey,
},
body: {
to: groupId,
data: {
subject: message
},
notification: {
title: title,
body: body,
badge: 1,
},
content_available: true
},
json: true
};
return rqstProm(options)
.then((parsedBody) => {
console.log('SUCCESS response=', parsedBody);
})
.catch((err) => {
console.log('FAILED err=', err);
});
Where JSON values title, body, subject, message are String
In my case, I was sending notifications to topic ("topics/my-topic"). I was missing prepending / in the starting of topic so I was getting the same issue. SO topic should be /topics/my-topic.
May be this helps!!
There is an easier way to send a message to a device group from a Cloud Function. Use admin.messaging().sendToDeviceGroup(). Sample code and instructions are in this guide.
I think your current method is failing because there is something wrong with the group notification key provided in groupId. It should be the string key value that was returned when you created the device group. The error codes are listed in this table. For 200/InvalidRegistration it says:
Check the format of the registration token you pass to the server.
Make sure it matches the registration token the client app receives
from registering with Firebase Notifications. Do not truncate or add
additional characters.
I was losing my mind with this InvalidRegistration error.
Eventually the problem was that I was subscribing my device to "example" but sending the notification json to: "example".
But we actually need to send to "/topics/example"
2 hours of my life wasted..
A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app.
Al you need to do is add a http header 'project_id' with your sender id.
I was getting InvalidRegistration:
Basic meaning: you are using the wrong token. Why? This may happen when you a new registrationToken is given to you in onNewToken (docs), but for some reason you are using the old token. That could happen when:
You're using a different push notification library which remembers token (stores it somewhere locally) and you didn't update that library with the new token.
Your application (or other library dependencies) implements another FirebaseMessagingService, and they conflict. Only one service can accept (react to) to the action sent by the FirebaseMessaging Android library's when a new token is given to it. You can double check this by opening the AndroidManifest.xml in Android Studio and selecting the Merged Manifest tab at the bottom of the tab. You can also place debuggers in each Service from each library you use. You'll see that only one service's onNewToken gets called.
When they conflict, one doesn't get the correct token, and the FCM registration token that gets registered would be wrong. Sending a message to a wrong registration, gets you InvalidRegistration.
for me, it was a mistake that I was passing an Id from my models instead of the tokens of the users
InvalidRegistration simply means that the token is either invalid or expired. You can uninstall the app and then reinstall and get a new token and then try with that token. This will definitely solve your problem.
You can read more here.

Parse Cloud: Send a notifications to a specific user

I'm currently implementing push notifications to follow user. Apparently, I managed to get push notifications done and responsive well.Hence, The notifications were sent to everyone.I would like to create push notifications and received the notification only by one respective user each time when other users have followed their user account.
I haven't create a pointer that should associate with User. Even If I create, is there any amendments that I should amends on my Cloudcode?
I would like to send push notifications to a specific user whenever other user has followed that user.
eg: Test 1 followed you.
Parse.Cloud.define("FollowersAndFollowing", function(request,result){
var query = new Parse.Query(Parse.User);
var message = request.params.message;
var pushQuery = new Parse.Query(Parse.Installation);
query.equalTo('userLink',request.params.User);
Parse.Push.send({
where: pushQuery,
data : {
alert: message,
badge: "Increment",
sound: "",
}
}, {
success: function(result) {
console.log(JSON.stringify(result));
response.success(result);
},
error: function(error) {
console.error(JSON.stringify(error));
response.error(error)
}
});
});
Above this ^ is my cloud code in .JS
if (status == false) {
// Create the push notification message.s
let pushMessage = "\(PFUser.currentUser()!.username!) has followed you."
// Submit the push notification.
PFCloud.callFunctionInBackground("FollowersAndFollowing", withParameters: ["message" : pushMessage, "User" : "\(userData.username!)"])
}
and above this is in swift code for frontend.
enter image description here
and the second the url is my class and subclasses of how I setting up
enter image description here
Use a cloud code beforeSave trigger on the Installation class to keep User pointers up to date.
// Make sure all installations point to the current user
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
if (request.user) {
request.object.set("user", request.user);
} else {
request.object.unset("user");
}
response.success();
});
You may also want to use an afterSave trigger on your Follow class to send out the push notification instead of calling a cloud function. Without knowing the structure of that class or how you have implemented a follower/following scheme it's hard to give any further information.

How to send push notification from web application to android device using Parse?

Acually we are done with sending push notion with mobile to mobile.now we are trying to send push notification from web application to mobile devices using javascript.
we tried like this
function authentication() {
Parse.$ = jQuery;
// Initialize Parse with your Parse application javascript keys
Parse.initialize("app key",
"script key");
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("channels","Demo");
var promise = new Parse.Promise();
debugger;
Parse.Push.send({
where: pushQuery,
data: {
alert : "Hello word"
}}, { success: function() {
// Push was successful
alert : "Push was successful"
},
error: function(error) {
promise.reject(error);
}}).then (function(error) {
//Marks this promise as fulfilled,
//firing any callbacks waiting on it.
});
return promise;
}
we getting error like this
Failed to load resource: the server responded with a status of 400 (Bad Request)
code: 115
message: "Client-initiated push isn't enabled.
We enabled Client Push also
We are new to Push notification.plz guide us
Thanks in advance
com
step 1 :
1.create your project in parse.com
2.Add parse push notification id in your project.
3.from parse.com your will have send push button to send push notification click and send your message.
fallow this links
http://www.androidbegin.com/tutorial/android-parse-com-push-notification-tutorial/
www.parse.com

How to implement push notification support in Cordova app using Quickblox?

Apologies for such a basic question, but I really can't find any information on the subject.
The Quickblox Javascript SDK has some classes related to push notifications, and I have enabled them using chat_history and the alerting tab in chat. However what I don't understand is how to receive these notifications on the front end UI?
I don't have any code to share as I don't know where to start!
Any help would be truly appreciated, thank you.
There are modules to work with pushes:
QB.messages.tokens
QB.messages.subscriptions
QB.messages.events
To subscribe for pushes you have to do 2 things:
Create a push token using QB.messages.tokens
Create a subscription using QB.messages.subscriptions
Additional info can be found in REST API page http://quickblox.com/developers/Messages#Typical_use_.D1.81ases
Also you have to upload APNS and Google API key to QuickBlox admin panel.
This all needs if you are going to build Cordova app for iOS/Android
You need encode the message.
You need to make sure your mobile app would know to understand the decoded message.
For example,
sending push notification to android qb_user_id: 20290
(and from me - my qb_user_id: 12121):
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function send_push() {
var params = {
notification_type: 'push',
push_type: 'gcm',
user: {ids: [20290]},
environment: "production",
message: b64EncodeUnicode('{"message":"HELLO WORLD","user_id":12121,"device_type":"WEB","message_qb_id":"563a55a44cedaa83885724cf","message_type":"Text","send_status":"BeingProcessed","send_time":1446663588607}')
};
QB.messages.events.create(params, function(err, response) {
if (err) {
console.log("QB.messages.events.create::error:" +err);
} else {
console.log("QB.messages.events.create::response:" + response);
}
});
}
In this example, the mobile app is looking for a message in this format:
{"message","user_id","device_type","message_qb_id","message_type","send_status","send_time"}

Categories

Resources