Skip to content

Instantly share code, notes, and snippets.

@nicholas0g
Created July 8, 2019 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholas0g/2b752a100fba2c2ea6cf4c4e8e825be0 to your computer and use it in GitHub Desktop.
Save nicholas0g/2b752a100fba2c2ea6cf4c4e8e825be0 to your computer and use it in GitHub Desktop.
Notifiche con Onesignal - esempio express.js
//questo ti serve solo se vuoi mandare notifiche via web
//semplicemente registra una macchina ad un id, così tu poi puoi mandare notifiche anche ai singoli client
link(rel="manifest" href="/manifest.json") //il file manifest te lo da onesignal
script(src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async)
script.
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "il-tuo-id",
autoRegister: true,
notifyButton: {
enable: false
}
}]);
OneSignal.push(function() {
OneSignal.sendTag("nome", "#{nome}"); //identificativo dei singoli client che ricevono le notifiche puoi passare quello che ti pare, io per comodità uso il nome
});
//mia funzione per invio notifica a client con nome #nome
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic "+tua_app_key
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:"); //per debug perchè ho le turbe
console.log(JSON.parse(data)); //per debug perchè ho le turbe
});
});
req.on('error', function(e) {
console.log("ERROR:"); //per debug perchè ho le turbe
console.log(e); //per debug perchè ho le turbe
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: tua_app_id,
contents: {"it": messaggio,"en":messaggio}, //messaggio contiene il testo della notifica, è sempre obbligatorio passare anche la lingua inglese o sfaciola
filters: [
{"field": "tag", "key": "nome","value": nome} //qui dico che mando il messaggio al client o ai client con id #nome
]
};
sendNotification(message); //eseguo la funzione che manda il messaggio
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment