How to retrieve device id/ token at device registration? I am using Phonegap Pushwoosh example and it works fine. But I could not figure out how to retrieve the token at device registration initPushwoosh.
I am not a professional programmer. Any help will be appreciated.
I have an index.html that initialize
<body onload="init();">
In main.js
function init() {
document.addEventListener("deviceready", deviceInfo, true);
document.addEventListener("deviceready", initPushwoosh, true);
}
In PushNotification.js
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxxx", appid : "xxxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The first section is the .registerDevice and the token is probably pushToken, but I just cannot figure out how to retrieve it from this function!
The best is to send it to a MySQL database lets call it smartphonedb.tokentable
I modified the initPushwoosh() to send me the token to MySQL using Ajax (see below) I am receiving nothing on MySQL. Am I sending the right Token param (pushToken)?
function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
// CHANGE projectid & appid
pushNotification.registerDevice({ projectid: "xxxxxx", appid : "xxxxxxx" },
function(status) {
var pushToken = status;
console.warn('push token: ' + pushToken);
// start my ajax to insert token to mysql
var param ={Token: pushToken};
$.ajax({
url: 'http://luxurylebanon.com/offeratlive/apitoken.php', data: param, dataType: 'json', success: function(result)
{
if(result.success == false)
{
alert(failed)
}
else {
alert(success)
}
}
});
// end ajax
},
function(status) {
console.warn(JSON.stringify(['failed to register ', status]));
});
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
navigator.notification.alert(title);
});
}
The PHP apitoken.php
<?php
$username="xxxxxxx";
$password="xxxxxxxxxxxx";
$database="offeratdb";
$server="offeratdb.db.xxxxxxxxx.com";
$connect = mysql_connect($server,$username,$password)or die('Could not connect: ' . mysql_error());
#mysql_select_db($database) or die('Could not select database ('.$database.') because of : '.mysql_error());
$vtoken= $_POST['Token'];
// Performing SQL query
$query = "INSERT INTO `tokentable` (`thetoken`) VALUES ('$vtoken')";
$result = mysql_query($query)or die('Query failed: ' . mysql_error());
echo $vtoken;
// We will free the resultset...
mysql_free_result($result);
// Now we close the connection...
mysql_close($connect);
?>
any help will be appreciated
After looking through your code I think it contains some mistakes.
So, lets try to fix them:
First of all. Do you have jquery js script included before PushNotification.js? If not, "$.ajax" will not be executed.
The other thing. The ajax default type is GET, and you use POST in your php code.
And you don't use json at all. So your code should be transformed into something like this
$.ajax({
type: "POST",
async: true,
url: url,
data: params,
success: function (result) {
// todo
},
error: function (result) {
// todo
}
});
And the last thing. The param var should be initialized like this:
var param = "Token="+pushToken;
Hope this would be helpful.
I was having the same problem, I updated the Pushwoosh.jar and it worked for me. :)
Related
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'
),
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;
I try to create Cordova mobile app based on angularjs following this tutorial: https://mobilefirstplatform.ibmcloud.com/blog/2016/08/11/best-practices-for-building-angularjs-apps-with-mobilefirst-foundation-8.0/
and LTPA Based Security Check login flow (in Mobilefirst 8.0) based on sample from: https://github.com/mfpdev/ldap-and-ltpa-sample
Mobile app is using angular. Authorisation implementation:
app.factory('Auth', function ($rootScope) {
var securityCheckName = 'LTPA',
_$scope = null,
challengeHandler = null,
URL = '',
challengeHandler = WL.Client.createSecurityCheckChallengeHandler(securityCheckName);
challengeHandler.securityCheckName = securityCheckName;
WLAuthorizationManager.login(securityCheckName, {'username': '', 'password': ''});
challengeHandler.handleChallenge = function (challenge) {
if (challenge && challenge.loginURL) {
URL = challenge.loginURL;
}
};
challengeHandler.handleSuccess = function (data) {
// code
};
challengeHandler.handleFailure = function (error) {
// code
};
return {
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
challengeHandler.submitChallengeAnswer({});
},
function(error) {
// on error
});
}
};
});
This seems to work only on iOS. On Android handleSuccess function is not invoked.
As in the past, there was a problem with sending cookies on Android devices (with older MF versions) so I tried workaround in login function, that the hidden InAppBrowser was opened with logon form, then a user login process was made and once token was received, it was set via cordova-cookie-master-plugin and submitChallengeAnswer was invoked:
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
if (device.platform == "iOS") {
challengeHandler.submitChallengeAnswer({});
} else {
iab = cordova.InAppBrowser.open(URL, "_blank", "hidden=yes");
iab.addEventListener('loadstop', function(event){
iab.executeScript({code:
'var field1 = document.getElementsByTagName("input")[0];' +
'var field2 = document.getElementsByTagName("input")[1];' +
'field1.setAttribute("value", "' + username + '");' +
'field2.setAttribute("value", "' + password + '");' +
'document.forms[0].submit();'
}, function(){
// on error
});
try {
cookieMaster.getCookieValue(URL, 'LtpaToken2', function(data) {
WL.Client.setCookie({
"name" : "LtpaToken2",
"value" : data.cookieValue,
"domain" : ".example.com",
"path" : "/",
"expires" : "Thu, 18 Dec 2999 12:00:00 UTC"
}).then(function() {
challengeHandler.submitChallengeAnswer({});
}).fail(function(err) {
// on error
});
}, function(error) {
// on error
});
} catch(err) {
// on error
}
});
iab.addEventListener('exit', function(){
iab.removeEventListener('loadstop', function() { /* on success */ });
});
}
},
function(error) {
// on error
});
}
This solution also not working for me. I've expect that after challengeHandler.submitChallengeAnswer() was fired, the handleSuccess will be invoked, but it is not happened. handleChallenge is invoked instead.
I'm building an APK for the blood bank of my local city and i need to get the stock of blood by groups, i have some JSON that i test with Postman that woks but i need to add them to my Intel XDK project. I have follow some examples with AJAX and HTTP but with no result.
ionic.Platform.ready(function(){
$("#ajax").click(function(){
$.ajax({
method: 'GET',
url: 'http://192.168.1.100/api/hospital/17659861-1',
dataType: 'json',
success: function (data) {
alert('Data RecibidaAPI: ' + data);
console.log(data.data[0].us_rut);
console.log(data.data[0].us_nombre);
console.log(data.data[0].us_telefono);
console.log(data.data[0].us_id_dispositivo);
console.log(data.data[0].us_grupo_sangre);
}
}).then(function (data) {
console.log('Data RecibidaAPI: ' + data);
});
});
}
and also try
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, function myError(response) {
$scope.content = "Something went wrong";
});
});
</script>
</div>
where i could't even get the scope.satuscode to work.
I'm using Ionic as framework with AngularJS, if someone need extra info to helpmeet just ask and thanks for any idea.
See this FAQ on the Intel XDK web site > https://software.intel.com/en-us/xdk/faqs/app-designer#ajax-jquery-one-fail
If the call is being made successful but you're not getting your $scope to update try wrapping the values you need to update in $timeout .. you can use $scope.apply() but i believe $timeout to be the safer method
<div id="campa_de_sangre" class="upage-content vertical-col left hidden" ng-app="myApp2" ng-controller="myCtrl2">
<p>hola</p>
<h1>{{myWelcome}}</h1>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p
<p>{{content}}</p>
<script>
var app2 = angular.module('myApp2', []);
app2.controller('myCtrl2', function ($scope, $http, $timeout) {
$http({
method: "GET",
url: "welcome.htm"
}).then(function mySucces(response) {
$timeout(function () {
$scope.myWelcome = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, 0)
}, function myError(response) {
$timeout(function () {
$scope.content = "Something went wrong";
}, 0)
});
});
</script>
</div>
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 !