I am using Ionic 2 with HTTP native module to make a post request to FCM server for push notifications. The code I am using is:
HTTP.post(
"https://fcm.googleapis.com/fcm/send",
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token",
},
{
Authorization: {
key: "AUTHORIZATION KEY HERE"
}
})
Its giving me an error:
Unimplemented console API: Unhandled Promise rejection:
Unimplemented console API: Error: Uncaught (in promise): [object Object]
I tried the post request with Postman, it works perfectly fine delivering push notifications.
The code with Postman is:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=Authorisation Key
Cache-Control: no-cache
Postman-Token: 446e253b-179a-d19b-21ea-82d9bb5d4e1c
{
"to": "Device Token",
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
}
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
}
Questions:
I am unable to add content-type to the header in the HTTP post request, but it works with postman.
If I try to add a function(response) { to get the response from the server, it gives me an error. The documentation for the same is at https://github.com/wymsee/cordova-HTTP
why are you using HTTP native module? Angular has a built in Http.
Using this one (importing HttpModule from #angular/http in your NgModule) you can just call
import { Http, Headers } from '#angular/http';
......
constructor(public http: Http) { }
sendPushNotification(deviceId: string) {
let url = 'https://fcm.googleapis.com/fcm/send';
let body =
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token"
};
let headers: Headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(headers));
this.http.post(url, body, headers).map(response => {
return response;
}).subscribe(data => {
//post doesn't fire if it doesn't get subscribed to
console.log(data);
});
}
push.on('notification', (data) => {
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'Go to',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
});
push.on('error', (e) => {
alert(e);
});
});
Related
Hi I am trying to send notification to my app using firebase post method its working fine in postman but when I try to do post method in my app its returning 403. I tried implementing another get request its working fine so no problem with axios setup.
export const postData = function (url, payload) {
return AXIOS.post(url, payload, config);
};
let config = {
headers: {
'Content-Type': 'application/json',
"Authorization" : "key= *****myKey****"
}
};
Here is my post mehtod
let body = {
"to": "******myTokeb*******",
"notification": {
"title": "Title here",
"body": "R(body)",
"mutable_content": true,
"sound": "Tri-tone"
}
};
postData("http://fcm.googleapis.com/fcm/send",body).then((d)=>{
console.log("d",d)
}).catch((e)=>{
console.log("e",e);
});
Error
Error: Request failed with status code 403
at createError (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\createError.js:16)
at settle (D:\projects\fiver\Roeyat\node_modules\axios\lib\core\settle.js:17)
at EventTarget.handleLoad (D:\projects\fiver\Roeyat\node_modules\axios\lib\adapters\xhr.js:61)
at EventTarget.dispatchEvent (D:\projects\fiver\Roeyat\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:567)
at EventTarget.__didCompleteResponse (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at D:\projects\fiver\Roeyat\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
Use HTTPS in postData
That will work!
Currently, I'm starting a PWA in Angular. I need to intercep some push notifications and redirect to this application when I click on the notification. I'm using Firebase for the push server.
Today, I can receive push notifications but when i click on one of them, I'm not redirected.
I send my request with Postman, my HTTP request is like :
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Authorization: key=XXXX
Content-Type: application/json
{
"to":"XXXX",
"content_available": true,
"notification": {
"title": "hello",
"body": "test message",
"data": {
"url": "http://myurl.com"
}
}
}
In my web application, I receive the following datas :
data:
gcm.notification.content_available: "true"
gcm.notification.data: "{"url":"http:\/\/myurl.com"}"
extra: "juice"
from: "300398521917"
notification:
title: "hello"
body: "test message"
collapse_key: "do_not_collapse"
And, when I click on the receive notification, my application intercept the event and log :
action: ""
notification:
actions: []
badge: ""
body: "test message"
data: null
dir: "auto"
icon: ""
image: ""
lang: ""
renotify: false
requireInteraction: false
silent: false
tag: ""
timestamp: 1582539931548
title: "hello"
vibrate: []
I would like to refind my url in the data part. Anybody have an idea about this ?
I have tried like below its worked for me
{
"to":"XXXX",
"content_available": true,
"notification": {
"title": "hello",
"body": "test message",
"click_action": "https://example.com"
}
}
self.registration.showNotification method takes notificationOptions as parameter. So you can pass data object (that will have url and other custom properties that you want to pass) to inside notificationOption object then in notificationclick listener, get that object event.notification.data and access all custom properties there.This way you can url to listener.
messaging.onMessage(function(payload){
var dataObj = payload.data;
dataObj.someCustomProperty = "xyz";
const notificationOptions = {
data: dataObj
};
self.registration.showNotification(payload.title,
notificationOptions);
)
self.addEventListener('notificationclick', function(event){
const nUrl = event. notification.data.customProperty;
})
We have got rw_ads permissions for an app. Through that app We have taken access_token with all given permissions.
As mentioned in the documentation, we have rw_ads permission, but If we try to create/update campaign we are getting the below error.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: POST /adCampaignsV2/sdafnk",
"status": 403 }
var request = require("request");
var options = { method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2/sdafnk',
headers:
{ 'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json' },
body:
{ patch:
{ '$set':
{ runSchedule: { end: 1548405000000, start: 1547713800000 },
status: 'ACTIVE' } } },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Code for creation of campaign is mentioned below
var request = require("request");
var options = {
method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2',
headers: {
'Authorization': 'Bearer <accessToken>',
'Content-Type': 'application/json'
},
body: {
account: 'urn:li:sponsoredAccount:<accountId>',
audienceExpansionEnabled: false,
costType: 'CPM',
creativeSelection: 'OPTIMIZED',
dailyBudget: { amount: '200', currencyCode: 'INR' },
locale: { country: 'IN', language: 'en' },
name: 'Campaign text ad test',
objectiveType: 'WEBSITE_TRAFFIC',
offsiteDeliveryEnabled: false,
runSchedule: { end: 1547708400000, start: 1547967600000 },
type: 'TEXT_AD',
unitCost: { amount: '10', currencyCode: 'INR' },
status: 'PAUSED'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When you perform a partial update, the header X-RestLi-Method must be included in the request and set to PARTIAL_UPDATE.
Also if you use implicit grant-type, check if you have defined the scope correctly at the start. if you use client-credentials grant-type check if the account has the right permissions.
Direct Sponsored Content can be created by:
Ad Account Users with a role higher than VIEWER. Organization users
with DIRECT_SPONSORED_CONTENT_POSTER or ADMINISTRATOR roles.
also the code you added in this question is for Reactivating a campaign. not for updating/creating one.
i am new to angular2 native script programming.. i need to post data to a particular url from my app. when i try to post data then get a message on console Response with status: 200 for URL: null. whats the meaning of this message.? and what should i do for successfull post request..?
//my code
let headers = new Headers({ "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let body =
{
"firstName": "boby",
"lastName": "samuels",
"Location": "UK"
};
this.http.post("http://example.com", JSON.stringify(body), options)
.subscribe(result =>
{
console.log("response : "+result);
}, error =>
{
console.dir(error);
});
please help me out.
So I am pushining notifications in a batch to multiple devices. I want to delete device GFCM tokens from my databse if they are not in firebase.
Test request:
{"registration_ids": ["fznIum-OIL0:APA91bE9n6gxqVEB3hR0On_TZqH_cOOO7rFyLE5MYbvKXUX3737IonXquZRoHeY1UJf20G4nrahz35p80X8PAPouviYvXgtekAzeDFuwaWyiPI1sFlN1d1wGp5OulXv9wUzHyegeZiih","dsasadadsasdasdasdasdefs","fjb0qTB9ACI:APA91bHvx0pSlq-NuQz-bU70DhL7BXAcd-DqT9YT0ZjYw7R_pkBmr8oe6XdNw8IPlU67d-rXMfRY3mybaO7K5GHo_NH7G-Ya1Ae2xxJP1JIbuuSYomz31y_MPQijFK8w-bZXQ26SWE09"],
"notification":{
"body":"Yoou have a new message from Alice"}}
And response:
{
"multicast_id": 7971310728176484096,
"success": 1,
"failure": 2,
"canonical_ids": 0,
"results": [
{
"error": "NotRegistered"
},
{
"error": "InvalidRegistration"
},
{
"message_id": "0:1481547993513035%4f9c20964f9c2096"
}
]
}
How to detect which registration_ids are bad/Not registered?
Thanks!
Okey, i think i figured it out.
"results": Returns responses/errors in the order you specified it in registration_ids
when you are sending push notification to any mobile,you can find in err that registartion_ids/token isbad /not registered/
var serverKey = 'sdasd';//server key
var fcm = new FCM(serverKey);
var token = "token";//token here
var message = {
to: token,
collapse_key: 'your_collapse_key',
notification: {title: 'hello', body: 'test'},
data: {my_key: 'my value', contents: "stackoverflow.com"}
};
fcm.send(message, function (err, response) {
if (err) {
console.log(err);//find here registration_ids are bad/Not registered?
} else {
console.log(response);
}
});
});