Get OneSignal UserID after subscribe - push-notification

I'm using OneSignal to get notifications, so according to docs I made my SDK code like this:
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "myappID",
safari_web_id: "myID",
autoRegister: false,
promptOptions: {
/* My prompt options */
},
welcomeNotification: {
//my options
},
notifyButton: {
enable: true,
showCredit: false,
prenotify: true,
position: 'bottom-left',
text: {
/*My text options */
},
colors: { // My custom colors
}
}
}]);
OneSignal.push(function(){
OneSignal.showHttpPrompt();
OneSignal.getUserId().then(function(userId){
console.log("OneSignal User ID:", userId);
});
});
</script>
It works great showing slideshow prompt message, but after subscribe I need to refresh the website to get UserID in console. How can I modify this code function to get userID in console immediately after subscribe?

You need to add a listener for the subscription change event. Otherwise the getUserId call will trigger before the user has accepted the subscription. This is working for me:
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
console.log("The user's subscription state is now:",isSubscribed);
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
console.log("OneSignal User ID:", userId);
});
});
});
});
OneSignal.push(["init", {
appId: "myappID",
safari_web_id: "myID",
autoRegister: false,
promptOptions: {
/* My prompt options */
},
welcomeNotification: {
//my options
},
notifyButton: {
enable: true,
showCredit: false,
prenotify: true,
position: 'bottom-left',
text: {
/*My text options */
},
colors: { // My custom colors
}
}
}]);

Related

web push notification - getting same notifications multiple times on chrome

I'm working on push notification. I'm facing the issue of getting same notification multiple time even I have written code for closing notification.
self.addEventListener('push', async (event) => {
if (event.data) {
const [data] = event.data.json()
const body = `Notification: ${data.timestampV} - ${data.eventType}`
const title = 'Web Notification'
const options = {
body,
icon: 'images/icon.png',
badge: 'images/badge.png',
}
event.waitUntil(self.registration.showNotification(title, options))
} else {
console.log('This push event has no data.')
}
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
// close all notifications
self.registration.getNotifications().then(function (notifications) {
notifications.forEach(function (notification) {
notification.close();
});
});
// eslint-disable-next-line no-undef
clients.openWindow('/feeds')
})
Thanks in advance.
This code works for me.
Add async function
var newEvent = new Event('push');
newEvent.waitUntil = e.waitUntil.bind(e);
newEvent.data = {
json: async function () {
var newData = e.data.json();
newData.notification = newData.data;
self.registration.showNotification(newData.data.title, {
...newData.data,
data: newData.data
});
return newData;
},
};
please check it from
https://github.com/firebase/quickstart-js/issues/71#issuecomment-396958853

Nodejs-Krakenjs: PayPal Checkout Server Integration

I try to follow instruction here: https://developer.paypal.com/docs/checkout/how-to/server-integration/# to integrate paypal checkout into my website (developed by Nodejs-krakenjs, Angularjs)
// FOR PAYPAL PAYMENT
function renderPaypalButton() {
paypal.Button.render({
env: 'sandbox', // Or 'production'
// Set up the payment:
// 1. Add a payment callback
payment: function (data, actions) {
// 2. Make a request to your server
console.log('Make a request to your server');
return actions.request.post('/file/createPayment', {
//_token: csrf_token()
}).then(function (res) {
console.log('return res id');
// 3. Return res.id from the response
return res.id;
});
},
// Execute the payment:
// 1. Add an onAuthorize callback
onAuthorize: function (data, actions) {
// 2. Make a request to your server
return actions.request.post('/file/executePayment', {
paymentID: data.paymentID,
payerID: data.payerID
})
.then(function (res) {
// 3. Show the buyer a confirmation message.
alert(res);
console.log(res);
});
}
}, '#paypal-button');
}
Server side:
// Set up the payment:
// 1. Set up a URL to handle requests from the PayPal button
router.post('/createPayment', function (req, res) {
console.log('aa');
// 2. Call /v1/payments/payment to set up the payment
request.post(PAYPAL_API + '/v1/payments/payment',
{
auth:
{
user: CLIENT,
pass: SECRET
},
body:
{
intent: 'sale',
payer:
{
payment_method: 'paypal'
},
transactions: [
{
amount:
{
total: '5.99',
currency: 'USD'
}
}],
redirect_urls:
{
return_url: 'http://localhost:1272',
cancel_url: 'http://localhost:1272'
}
},
json: true
}, function (err, response) {
if (err) {
console.error(err);
return res.sendStatus(500);
}
// 3. Return the payment ID to the client
res.json(
{
id: response.body.id
});
});
});
// Execute the payment:
// 1. Set up a URL to handle requests from the PayPal button.
router.post('/executePayment', function (req, res) {
// 2. Get the payment ID and the payer ID from the request body.
var paymentID = req.body.paymentID;
var payerID = req.body.payerID;
// 3. Call /v1/payments/payment/PAY-XXX/execute to finalize the payment.
request.post(PAYPAL_API + '/v1/payments/payment/' + paymentID + '/execute',
{
auth:
{
user: CLIENT,
pass: SECRET
},
body:
{
payer_id: payerID,
transactions: [
{
amount:
{
total: '10.99',
currency: 'USD'
}
}]
},
json: true
},
function (err, response) {
if (err) {
console.error(err);
return res.sendStatus(500);
}
// 4. Return a success response to the client
res.json(
{
status: 'success'
});
});
});
}
The paypal library were loaded in index.html:
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
And in a Modal form that the paypal checkout button is integrated:
<div id="paypal-button"></div>
<script>
setTimeout(renderPaypalButton(), 3000);
</script>
The Paypal-checkout button is rendered and displayed on the modal,but after click the button, the Palpay Login modal appears a few seconds then disappears, the "Error: CSRF token missing" appears:
POST http://localhost:1272/file/createPayment 500 (Internal Server Error) Uncaught Error: Error: Request to post /file/createPayment failed with 500 error. Correlation id: unknown
HomeInternal server errorThe URL /file/createPayment had the following error Error: CSRF token missing.
at XMLHttpRequest.<anonymous> (https://www.paypalobjects.com/api/checkout.js:14010:39)
at Object._RECEIVE_MESSAGE_TYPE.(anonymous function) [as postrobot_message_response] (https://www.paypalobjects.com/api/checkout.js:2569:31)
at receiveMessage (https://www.paypalobjects.com/api/checkout.js:2614:60)
at messageListener (https://www.paypalobjects.com/api/checkout.js:2635:13)
at XMLHttpRequest.<anonymous> (https://www.paypalobjects.com/api/checkout.js:14010:39)
at Object._RECEIVE_MESSAGE_TYPE.(anonymous function) [as postrobot_message_response] (https://www.paypalobjects.com/api/checkout.js:2569:31)
at receiveMessage (https://www.paypalobjects.com/api/checkout.js:2614:60)
at messageListener (https://www.paypalobjects.com/api/checkout.js:2635:13)
at deserializeError (https://www.paypalobjects.com/api/checkout.js:3302:23)
at https://www.paypalobjects.com/api/checkout.js:3323:270
at https://www.paypalobjects.com/api/checkout.js:3052:30
at eachArray (https://www.paypalobjects.com/api/checkout.js:3035:51)
at each (https://www.paypalobjects.com/api/checkout.js:3041:35)
at replaceObject (https://www.paypalobjects.com/api/checkout.js:3051:13)
at https://www.paypalobjects.com/api/checkout.js:3053:169
at eachObject (https://www.paypalobjects.com/api/checkout.js:3038:65)
at each (https://www.paypalobjects.com/api/checkout.js:3041:144)
at replaceObject (https://www.paypalobjects.com/api/checkout.js:3051:13)
You all could please help me. I don't understand what makes Csrf here. Thanks for all !!
The example code shown in the PayPal documentation does not work. You
have to pass it an QAuth access token not a CLIENT/SECRET. I got the code
to work but had to change it quite a bit.
Here's the node.js server code:
var express = require('express');
var request = require('request');
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
var PAYPAL_API = 'https://api.sandbox.paypal.com';
app.post('/my-api/create-payment/', function(req, res)
{
// Set up the payment:
// 1. Set up a URL to handle requests from the PayPal button
// 2. Allow cross-domain
res.setHeader('access-control-allow-origin', '*');
request.post(PAYPAL_API + '/v1/payments/payment',
{
headers: {
Authorization: 'Bearer <your access token>'
},
body:
{
intent: 'sale',
payer:
{
payment_method: 'paypal'
},
transactions: [
{
amount:
{
total: '5.99',
currency: 'USD'
}
}],
redirect_urls:
{
return_url: 'https://www.yourwebsite.com',
cancel_url: 'https://www.yourwebsite.com'
}
},
json: true
}, function(err, response)
{
if (err)
{
console.error(err);
return res.sendStatus(500);
}
// 3. Return the payment ID to the client
res.json(
{
id: response.body.id
});
});
})
// Execute the payment:
// 1. Set up a URL to handle requests from the PayPal button.
app.post('/my-api/execute-payment/', function(req, res)
{
// 2. Get the payment ID and the payer ID from the request body.
var paymentID = req.body.paymentID;
var payerID = req.body.payerID;
res.setHeader('access-control-allow-origin', '*');
// 3. Call /v1/payments/payment/PAY-XXX/execute to finalize the payment.
request.post(PAYPAL_API + '/v1/payments/payment/' + paymentID +
'/execute',
{
headers: {
Authorization: 'Bearer <your access token>'
},
body:
{
payer_id: payerID
},
json: true
},
function(err, response)
{
if (err)
{
console.error(err);
return res.sendStatus(500);
}
// 4. Return a success response to the client
res.json(
{
status: 'success'
});
});
}).listen(3000, function()
{
console.log('Server listening at http://localhost:3000/');
});
Here's the HTML:
<!DOCTYPE html>
<html>
<title>PayPal Client Test</title>
<body>
<p>This is the PayPal button for my client sandbox test</p>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<div id="paypal-button"></div>
<script>
paypal.Button.render({
env: 'sandbox', // Or 'production'
// Set up the payment:
// 1. Add a payment callback
payment: function(data, actions) {
// 2. Make a request to your server
return actions.request.post('http://localhost:3000/my-api/create-payment/')
.then(function(res) {
// 3. Return res.id from the response
//alert("Res ID="+res.id);
return res.id;
});
},
// Execute the payment:
// 1. Add an onAuthorize callback
onAuthorize: function(data, actions) {
return actions.request.post('http://localhost:3000/my-api/execute-payment/', {
paymentID: data.paymentID,
payerID: data.payerID
})
.then(function(res) {
alert("Payment made!");
});
},
onError: function (err) {
alert("err="+err);
}
}, '#paypal-button');
</script>
</body>
</html>

OneSignal does not work on mobile

I have a problem getting "OneSignal" web push notifications to work on mobile-chrome browser, it works as expected on PC however, here is the code:
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "xxxxxxxxxx",
autoRegister: false,
notifyButton: {
enable: false,
},
});
});
</script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.on('subscriptionChange',function (isSubscribed) {
// if subscribed sends tags
if (isSubscribed) {
window.userPushed = true;
OneSignal.sendTag("table", "wasadds_22",function(tagsSent) {
console.log(tagsSent);
});
}
});
var isPushSupported = OneSignal.isPushNotificationsSupported();
if (isPushSupported) {
//if supported checks if enabled and shows propmpt if is not enabled
OneSignal.isPushNotificationsEnabled().then(function(isEabled) {
if (isEabled) {
console.log('push notifications are enabled');
window.userPushed = true;
}else{
swal({
title: 'Subscribe and get benefits!',
text: "Press allow ",
type: 'success',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Lets Do it!'
}).then((result) => {
if (result.value) {
// if user agrees the push prompt shows up
OneSignal.registerForPushNotifications();
OneSignal.setSubscription(true);
}
});
}
})
};
});
</script>
So the problem on mobile-chrome browser that it does not react in any way when I try to trigger push notification subscribe prompt it wouldn't show it, and no errros , also autoRegister does not work either , pls help

How to use web push notifications with Meteor?

I am just hoping to find some good examples, but I haven't found anything. Pushjs is working on localhost, but how do I use the service worker correctly? I have linked the file, but this:
self.addEventListener('push', function (event) {
console.log('Received a push message', event);
// var notificationOptions = {
// body: 'The highlights of Google I/O 2015',
// icon: 'images/icon#192.png',
// tag: 'highlights-google-io-2015',
// data: null
// };
var notificationOptions = {
body: "Martin matches 89% with you!",
icon: '/images/LogoStore.jpg',
timeout: 4000,
link: "/",
onClick: function () {
window.focus();
this.close();
}
}
if (self.registration.showNotification) {
self.registration.showNotification('Timely News', notificationOptions);
return;
} else {
new Notification('Timely News', notificationOptions);
}
});
does not work.

upload with meteor and dropbox

I'm trying to do an upload using dropbox, but something is going wrong and I don't know what it is. I've done some searches on the Internet and I couldn't find anything.
Here it's my code:
if (Meteor.isClient) {
Template.hello.helpers({
uploads:function(){
return Avatars.find();
},
images:function(){
return Images.find();
}
});
var avatarStoreLarge = new FS.Store.Dropbox("avatarsLarge");
var avatarStoreSmall = new FS.Store.Dropbox("avatarsSmall");
Avatars = new FS.Collection("avatars", {
stores: [avatarStoreSmall, avatarStoreLarge],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Template.hello.events({
'change .fileInput':function(event,template){
FS.Utility.eachFile(event,function(file){
var fileObj = new FS.File(file);
Avatars.insert(fileObj,function(err){
console.log(err);
})
})
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
var avatarStoreLarge = new FS.Store.Dropbox("avatarsLarge", {
key: "xxxxxxxxxxxxxxx",
secret: "xxxxxxxxxxxxxxx",
token: "xxxxxxxxxxxxxxx",
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name()).resize('250', '250').stream().pipe(writeStream)
}
})
var avatarStoreSmall = new FS.Store.Dropbox("avatarsSmall", {
key: "xxxxxxxxxxxxxxx",
secret: "xxxxxxxxxxxxxxx",
token: "xxxxxxxxxxxxxxx",
beforeWrite: function(fileObj) {
fileObj.size(20, {store: "avatarStoreSmall", save: false});
},
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name()).resize('20', '20').stream().pipe(writeStream)
}
})
Avatars = new FS.Collection("avatars", {
stores: [avatarStoreSmall, avatarStoreLarge],
filter: {
allow: {
contentTypes: ['image/*']
}
}
})
});
}
I did this example following this documentation.
First, check installed meteor packages: meteor list, to get code to work you have to install:
cfs:standard-packages
cfs:dropbox
Second, simplify your code to reduce error precursors (Example in docs required Image Manipulation packages), for example:
CLIENT-SIDE
var dataStorage = new FS.Store.Dropbox("imageData");
Images = new FS.Collection("imageData", {
stores: [dataStorage],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Template.helpers block
'imageToShow': function(){
return Images.find()
},
Template.events block
'click #imageToUpload': function(event, template) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function (err, fileObj) {});
});
},
SERVER-SIDE
var dataStorage = new FS.Store.Dropbox("imageData", {
key: "...",
secret: "...",
token: "..."
});
Images = new FS.Collection("imageData", {
stores: [dataStorage],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Third, handle errors to figure out what's going wrong.
Fourth, it takes time to upload and download back images from dropbox, to test your app use light weighted files. Use console.log in client and server sides to see apps' flow.
First check if you have installed the following packages:
cfs:standard-packages
cfs:dropbox
cfs:gridfs
Install them:
meteor add cfs:standard-packages
meteor add cfs:dropbox
meteor add cfs:gridfs
Make sure your file "client/collections_client/avatar.js" looks like this:
Template.hello.helpers({
'imageToShow': function(){
return Images.find()
},
});
var dataStorage = new FS.Store.Dropbox("imageData");
Images = new FS.Collection("imageData", {
stores: [dataStorage],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Template.hello.events({
'click #imageToUpload': function(event, template) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function (err, fileObj) {});
});
},
});
"client/collections_client/hello.html"
<template name="hello">
<input type="file" name="teste" id="imageToUpload">
</template>
<body>
{{> hello}}
</body>
Assuming you have created your app:
"server/collections_server/avatar.js"
var dataStorage = new FS.Store.Dropbox("imageData", {
key: "yourAppKey",
secret: "yourAppSecret",
token: "youroAuth2Token"
});
Images = new FS.Collection("imageData", {
stores: [dataStorage]
});

Resources