How to hide Notification OneSignal in Unity3D - android

I'm building an application that uses Firebase and OneSignal with client written in unity3d, the problem is that I want to receive notification but do not want it to display notifications when the app is not running.
https://documentation.onesignal.com/docs/android-customizations#section-background-data-and-notification-overriding
This is the code from Firebase, everything runs fine
enter code here
var sendNotification = (data) => {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic YzA3MjYwZmMtNzUwYi00YWFiLThjNGUtYjYzMGM4NmM1ZWRl"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var req = https.request(options, (res) => {
res.on('data', (data) => {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', (e) => {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "752aef3b-5a0a-44be-8e94-f31d648cb866",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
And I want to hide the notification when the app is not running,
like this one

Related

Script for making firebase user to user notifications

(Sorry for bad English)
I'm looking for a way to make user to user notifications in Android.
The system have to catch a new child event in the Database, read the data and send the notification to destination.
The struct of the DB is this:
notificationRequests
$pushid
message: "You have a new request! Open the app"
userId: "sadbijasuobru112u4124u21b" //user destination id
By doing some researches in the web I've found the possibility to use topic messages.
So, i've added this in my LoginActivity befor calling the MainActivity:
FirebaseMessaging.getInstance().subscribeToTopic("users_topic$uid")
.addOnCompleteListener {
Log.d("LoginActivity", "User registered")
}
The code works. I can send notifications from the console
Like I said before, i need automatic messages.
I've found this code on the web, but it doesn't work.
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "Firebase Cloud Messaging Server API key"
// Fetch the service account key JSON file contents
var serviceAccount = require("./serviceAccountKey.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://appname.firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
requests.on('child_added', (requestSnapshot) => {
var request = requestSnapshot.val();
sendNotificationToUser(
request.userId,
request.message,
() => {
requestSnapshot.ref.remove();
}
);
}, (error) => {
console.error(error);
});
}
function sendNotificationToUser(userID, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/users_topic'+userID
})
}, (error, response, body) => {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I've implemented this code in the index.js for deployng. I've also write the entire file instead of requiring it, but it's always the same.
const functions = require('firebase-functions');
exports.sendNotifications = functions.https.onRequest((request, response) => {
require('./sendNotifications.js')
})
Any suggestions?
Thanks for the kelp!
EDIT
Does this need a billing account configurated? If yes, how can i make it with the free plan?
Does this need a billing account configurated? If yes, how can i make it with the free plan?
See https://firebase.google.com/support/faq#functions-runtime, but in short: from Node 10 you will need to enter billing information to use Cloud Functions.
You can use Node 8 until early next year without entering billing information.
Note that entering billing information does not necessarily mean you'll have to pay, as Cloud Functions has a pretty significant free tier.
The problem was that I was calling an external site. I solved it doing this:
const functions = require('firebase-functions');
var firebase = require('firebase-admin');
// Fetch the service account key JSON file contents
var serviceAccount = require("./serviceAccountKey.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://appname.firebaseio.com/"
});
exports.sendNotifications = functions.database.ref('/notificationRequest/{pushId}')
.onCreate( (change, context) => {
var uid = change.child('userId').val()
var notificationMessage = change.child('message').val()
var userTopic = 'users_topic'+uid
var payload = {
data: {
message: notificationMessage
}
};
var options = {
priority: 'high',
timeToLive: 60 * 60 * 24,
collapseKey: 'notification'
};
firebase.messaging().sendToTopic(userTopic, payload, options)
// eslint-disable-next-line promise/always-return
.then((response) => {
console.log('Done', response);
})
.catch((error) => {
console.log('Error: ', error);
});
return change.ref.remove();
});

Ionic: Send Push Notifications via firebase from device to device : Sending doesn't work from iOS

Sending push notifications from device to device works fine with this code, but only on Android and from a browser.
For some reason this does not work on iOS, no matter if I use the postData object or the stringified payload. Any ideas why?
import { HttpClient } from '#angular/common/http';
public sendPushNotificationToToken(token: string, pnServerKey: string, message: string, userId: number): Observable<any> {
const firebaseUrl = "https://fcm.googleapis.com/fcm/send";
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'key=' + pnServerKey
})
};
const postData = {
'to': token,
'priority':'normal',
'notification': {
'title': message,
'message': message,
'userId': userId
},
};
return this.http.post(firebaseUrl, postData, httpOptions);
The only way to solve this was to use "#ionic-native/http/ngx" instead of '#angular/common/http'. Still don't see why the google Server refused to accept my payload.

OneSignal push notification on Ionic 3: All included players are not subscribed

I'm developing an Android Application using Ionic 3 and I want to use push notification with tool OneSignal. Here is the code that I use at my main component:
let iosSettings = {
kOSSettingsKeyAutoPrompt: true,
kOSSettingsKeyInAppLaunchURL: false
}
this.oneSignal
.startInit(APP_ID, GOOGLE_PROJECT_NUMBER)
.iosSettings(iosSettings);
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal
.handleNotificationReceived()
.subscribe((notification: OSNotification) => {
console.log(notification)
});
this.oneSignal.endInit();
And here is the code that I use at my node webservice:
function sendNotification(scheduling) {
const schedulingID = scheduling.email + scheduling.date;
const message = {
app_id: APP_ID,
headings: {"en": MY_APP_NAME},
contents: {"en": "Scheduling confirmed!"},
data: {"agendamento-id": schedulingID},
included_segments: ["All"]
};
const headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic " + REST_API_KEY
};
const options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
console.log("Sending notification...");
const req = https.request(options, function (res) {
res.on('data', function (data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function (e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(message));
req.end();
}
But, when I execute the Android App on my devices, I get the message error:
{id: '', recipients: 0, errors: ['All included players are not subscribed']}
This will solve your problem:
'included_segments' => array(
'Subscribed Users'
),

Cloud Function Not Working

I want to add notifications to an online android chatting app I have made. I am new to cloud functions, so I tried using the code given here https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
My index.js file
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "xyz"; // Your Firebase
Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("firebase.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
requests.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
console.log('notificationrecived, sent and removed- ' +
request.username + ' '+ request.message,);
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '
+response.statusMessage);
}
else {n
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I have successfully deployed this code to the server using node.js command line.
But this does not show up on the console and nor the logs that I added to debug
and the code doesn't seem to work. I have done everything given in the link i mentioned. I could use some help on how to fix my code
I don't know how big of a difference this makes, but in the Firebase admin set up page https://firebase.google.com/docs/admin/setup, it is mentioned that for Cloud Functions, the following line is sufficient for initialisation:-
var firebase = require('firebase-admin');
firebase.initializeApp(functions.config().firebase);
So, if you're going by the book, you may replace the initialisation line in your code with the one above and try running it again.
I didn't export my function listenForNotificationRequests() but called it only once at the end of the script.
Which is why it didn't show up on the Firebase Console.
I fixed this by simply exporting the function like this
exports.sendFollowerNotification = listenForNotificationRequests;

Ionic Push using $http not working for android (Push Error Code 101)

push: function (tokens, message) {
var privateKey = 'xxx';
var appId = 'xxx';
var auth = btoa(privateKey + ':');
var req = {
method: 'POST',
url: 'https://push.ionic.io/api/v1/push',
headers: {
'Content-Type': 'application/json',
'X-Ionic-Application-Id': appId,
'Authorization': 'basic ' + auth
},
data: {
"tokens": tokens,
"notification": {
"alert": message
}
}
};
// Make the API call
$http(req).success(function (resp) {
// Handle success
console.log(tokens);
console.log(resp);
}).error(function (error) {
// Handle error
console.log("Ionic Push: Push error...");
});
}
I am using the above code to push notifications. It gets into the
success handler and prints the token used and message id, to the console. But when i check the status with the message id, its saying Push Error Code 101.
When i use the same token using Ionic.io website for one time notification screen, it works !
How can i make this working using angular code ?
Thanks !

Categories

Resources