sending OneSignal notification with QML - qt

I am integrating OneSignal into my app built with Felgo, when building my app for test purposes I am able to manually send notifications from my OneSignal dashboard, but obviously I want these to be automatic when an event happens in app.
I am truly struggling to understand how to get this working, I have read through both:
Felgo OneSignal Plugin and
Felgo HttpRequest
and I think combining these would be how I would go about it? Something along the lines of:
AppButton {
id: button
onClicked: {
//other onClicked actions,
HttpRequest
.post("https://onesignal.com/api/v1/notifications")
.set('Content-Type', 'application/json')
.send({ title: "post title", body: "post body" })
.then(function(res) {
console.log(res.status);
console.log(JSON.stringify(res.header, null, 4));
console.log(JSON.stringify(res.body, null, 4));
})
.catch(function(err) {
console.log(err.message)
console.log(err.response)
});
}
}
But how on earth would I go about sending to specific tags for targeted notifications?
In the Felgo OneSignal link above, they show that I can test push notifications with curl in the following way:
curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Basic <ONESIGNAL-REST-API-KEY>" \
--data-binary '{
"app_id": "<ONESIGNAL-APP-ID>",
"contents": { "en": "Message" },
"tags": [{"key": "userId", "relation": "=", "value": "1"}]
}' \
https://onesignal.com/api/v1/notifications
But outside of test purposes, how would I go assigning the specific tags and trigger a notification on a button press (or other event) within my app?
I understand all the information I should need to implement the notifications is there - but I cannot begin to make sense of it! :(
Any help would be massively appreciated as even when reading through documentation I am struggling.

I have got this working using the code below, what is shown is the end result of a signal sent when an AppButton is pressed elsewhere in my app.
I do not have my own web service to host this my notifications through, but for security reasons my REST key should not be in my code.
To combat this I have added my One Signal Rest API Key to a branch in my firebase database (which I am using in my app also), which can only be accessed by authorised users, this is then downloaded on the instance the request is made, and changed to a different string after.
property var osKey
firebaseDb.getValue("keys/OSkey", {
}, function(success, key, value) {
if(success){
osKey = value;
HttpRequest
.post("https://onesignal.com/api/v1/notifications")
.set('Content-Type', 'application/json')
.set("Authorization", "Basic " + osKey)
.send({
"app_id": "<MY_APP_ID>",
"contents": { "en": "MESSAGE" },
"tags": [
// the specific tags I want to send too
{"key": "groupAdmin", "relation": "=", "value": "1"},
{"key": "group", "relation": "=", "value": groupName}
]
})
.then(function(res) {
console.log(res.status);
console.log(JSON.stringify(res.header, null, 4));
console.log(JSON.stringify(res.body, null, 4));
})
.catch(function(err) {
console.log(err.message)
console.log(err.response)
});
}
})
osKey = "Nothing to see here"
I understand for securities sake, this still may not be the most secure, and again - if anyone can tell me how to improve this it would be a massive help!
Thanks

Related

How to achieve time-sensitive flag in APNS JSON output via FCM?

iOS distinguishes between messages by UNNotificationInterruptionLevel. I would like to achieve that messages sent via FCM have the time-sensitive interruption-level.
Is this equivalent to just sending messages in FCM with high priority? Unfortunately it's not super clear to me from looking at the docs.
The interruption level is automatically handled by system, not by FCM. That's different than the high priority.
You should be able to use it as it is by following Apple's documentation. FCM supports passing down the interruption-level in the payload.
I achieved this by having this payload in my firebase console file:
var message = {
notification: {
title: "Notification Title",
body: `${initiatedUsername} sent you message`,
},
"data": {
"target_exec":"messaging"
},
"apns": {
"payload": {
"aps": {
"alert": {
"title": "Notification Title",
"body": `${initiatedUsername} sent you a message`
},
"badge": 1,
"sound": "default",
"interruption-level": "time-sensitive"
}
}
},
token: fcmToken,
};
You can change the token attribute to topic aswell, if you'd rather like to send a message to a topic.
Hope this might help somebody out here!

Flutter web app receives push notification but broswer doesn't show it

I am being able to receive and display the notification on the console but it doesn't show up in the browser (chrome).
The steps I am following are:
I start the app and get notification token with the function
FirebaseMessaging.instance.getToken().then((String token) {
debugPrint('Token: $token');
});
The token from step 1. is inserted in the script below (the 'to' field) and the request is sent to Firebase servers
#!/bin/bash
DATA='{"notification": {"body": "This is a message","title": "Marcelo"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "eMkcLmwSSBeWXS_YEB-b_R:APA91bG2pyrDVr0BBoya0rQET0vfwTVE3aTeQsoqsxVMK70ypm6aaa-pNdX9uQ5BgEsoQGuVoe-EpeePJB8Q7XUfTvrTlgtRW8HSZ3qOaxotFUSaq8JqrgRtummIOnMFYUGqtg-sMP8Y"}'
curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=AAAAKavk7EY:APA91bEtq36uuNhvGSHu8hEE-EKNr3hsgso7IvDOWCHIZ6h_8LXPLz45EC3gxHUPxKxf3254TBM1bNxBby_8xP4U0pnsRh4JjV4uo4tbdBe2sSNrzZWoqTgcCTqmk3fIn3ltiJp3HKx2"
A success response is received back
{"multicast_id":5695802004264337317,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1615137996888514%2fd9afcdf9fd7ecd"}]}
The notification is received in the app in the form
FirebaseMessaging.onMessage.listen((RemoteMessage message)
{
RemoteNotification notification = message.notification;
if (notification != null) {
print('Title ${notification.title}');
print('Body ${notification.body}');
}
});
The browser however doesn't show the notification. What am I missing?
static onMessageWebNotification(NotificationData notificationData, String payloadData) {
html.window.navigator.serviceWorker.ready.then((registration) {
var notificationTitle = notificationData.title;
var notificationOptions = {
'body': notificationData.body,
'data': notificationData
};
registration.showNotification(
notificationTitle,
notificationOptions,
);
});
}

Firebase - notificationclick event not receiving payload

I'm struggling with this problem for more than a week... We have implemented push message in Chrome by using Firebase and a Service Worker. Everything works just fine, the messages are being sent and received correctly with the payload. On the service worker, we handle the push message to display a notification and the notificationclick event to send the user to a specific URL when clicking on it, then close the notification.
The problem is with 'old' notifications: if a user receives a message but doesn't clicks on it right away, it keeps there for a while then after some time (not sure how much) he clicks the notification - he gets redirected to https://[domain]/firebase-messaging-sw.js
We have traced the entire process: the notification gets received with all the info properly (the url is also correct, actually if he clicks right when the message is received it works just fine). But if the notification lives there for a while it gets 'emptied'.
The message being sent is pretty simple (just for showing there are no TTLs, nor expiration parameters being used). The curl command looks like that:
curl -X POST
-H "Authorization: key=[SERVER API KEY]"
-H "Content-Type: application/json"
-d '{
"notification":{
"click_action":"[URL to be redirected]",
"icon":"[A custom image]",
"title":"[News title]"},
"to":"/topics/[A topic]"
}'
"https://fcm.googleapis.com/fcm/send"
This is the code for processing the push message on the service worker:
self.addEventListener('push', function(event) {
console.log('Push message received', event);
var data = {};
if (event.data) {
data = event.data.json();
}
event.stopImmediatePropagation();
showNotification(data.notification);
});
function showNotification(notification) {
var click_action = notification.click_action; //<-- This is correct!
var options = {
body: notification.body,
icon: notification.icon,
subtitle: notification.subtitle,
data: {
url: click_action
}
};
if (self.registration.showNotification) {
return self.registration.showNotification(notification.title, options);
}
}
And the code for managing notificationclick event is pretty straightforward:
self.addEventListener('notificationclick', function(event) {
var url = '';
try {
url = event.notification.data.url; // <-- event.notification is null randomly!!
} catch (err) {}
event.waitUntil(self.clients.openWindow(url));
});
Is there any reason for loosing the payload after a certain time on the service worker context? Is this time specified on any documentation somewhere?
Thanks in advance for your help!
//payload of push message
{
"notification": {
"title": data.title,
"body": data.text,
"click_action": url,
"tag": "",
"icon": ""
},
"to": token
}
//in service woker
self.addEventListener("notificationclick", (event) => {
event.waitUntil(async function () {
const allClients = await clients.matchAll({
includeUncontrolled: true
});
let chatClient;
for (const client of allClients) {
if (client['url'].indexOf(event.notification.data.FCM_MSG.notification.click_action) >= 0) {
client.focus();
chatClient = client;
break;
}
}
if (!chatClient) {
chatClient = await clients.openWindow(event.notification.data.FCM_MSG.notification.click_action);
}
}());
});
so in this basically, on click of notification you are redirected to application ,and if the application is not open you are opening the application in new tab , as you are concerned that in event you are not able to get the click_action, could you try event.notification.data.FCM_MSG.notification.click_action by using this and see if you are getting the url, and add the event listener in beginning of service worker https://github.com/firebase/quickstart-js/issues/102

Bulk Send Message not working in MobileFirst Platform

I am trying to use the Bulk Send Message API in IBM MobileFirst Platform Foundation 7.0. Unfortunately, the example JSON from the docs does not work and gets an error about the object structure being sent.
This is the JSON Object I'm sending:
{
"//ArrayOfMessageBody": [
{
"messages": {
"alert": "Test message"
},
"settings": {
"apns": {
"actionKey": "Ok"
}
},
"target": {
"consumerIds": [
"MyConsumerId1"
],
"deviceIds": [
"MyDeviceId1"
],
"platforms": [
"A"
]
}
}
]
}
And Here is the server's response error:
com.ibm.json.java.JSONObject cannot be cast to com.ibm.json.java.JSONArray
I am having success sending to devices via the single Send Message API, so I know messaging works. However, Bulk Send Message is failing.
It turns out that the documentation was what hung me up. If you send an array of messages to the bulk send message endpoint it will work.
[{message1}, {message2}, ...]
I'm still not sure what the whole //ArrayOfMessageBody thing is.

Send push notification via REST API in Parse.com {"code":115,"error":"Missing the push data."}

When i am trying to test the REST API provided by Parse.com with Fiddler, it return an error. please find the enclosed screen capture. I can send the push notification on parse.com. but not from REST API.
Screenshot here:
http://s24.postimg.org/stwspcyir/image.jpg
http://s9.postimg.org/5r3guagh9/image.jpg
=== Follow Up ===
found the correct syntax of the JSON for push notification:
{"data": { "alert": "test message", "sound": "", "badge": "Increment" },"channel":"abc"}
but i found that if the channel is empty, the notification will not work, all i have to do is create channels for the device..... is it true ??
Found the answer finally:
if you have channels, provide the channel name:
{"data": { "alert": "321213", "sound": "", "badge": "Increment" },"channel":"channel name"}
if there is no channels (default no channel), send to all devices:
{"data": { "alert": "321213", "sound": "", "badge": "Increment" },"where": { "deviceType": "ios" }}

Resources