Cloud Function Not Working - android

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;

Related

Why request working on android simulator but not working on google play store app?

I have basic user login system datas come from http://www.birdpx.com/mobile/m_login (web site belongs to me) adress. But on similator requset working properly but it comes to app that downloaded google play store. Request not working Here is my login codes? By the way everything works on app store correctly .
When submiting the codes (function) below work
_handleSubmit=async (values)=>{
this.setState({
loading: true
})
const datam = { name: values.username, password: values.password };
const rest = await fetch('http://www.birdpx.com/mobile/m_login', {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-type': 'application/json' },
body: JSON.stringify(datam)
});
const gelenVeri = await rest.text();
let convertedVeri=JSON.parse(gelenVeri);
if (convertedVeri.status == 1) {
await this.setState({
userToken: 1
})
let giris = { token: this.state.userToken,user:convertedVeri.kullanici }
await AsyncStorage.setItem('isLoggedIn', JSON.stringify(giris));
const atama = await AsyncStorage.getItem('isLoggedIn');
const atamaVerisi = JSON.parse(atama);
if (atamaVerisi.token === 1) {
setTimeout(() => {
this.props.navigation.navigate('Home');
}, 2000)
} else {
this.setState({
loading: false
});
alert("Beklenmedik Bir Hata Oluştu");
}
} else {
this.setState({
loading: false
});
alert("Giriş Başarısız");
}
}
What do you think about that is that a problem about http/https issue and if it is how can , solve it?
From Android 9 Pie now, requests without encryption(https) will never work. To enable requests to all types of connections HTTP and HTTPS in Android 9 Pie and above, use this attribute to your AndroidManifest.xml where you allow all http for all requests:
<application android:usesCleartextTraffic="true">
</application>
Source: https://developer.android.com/about/versions/pie/android-9.0-changes-28#tls-enabled

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();
});

How to hide Notification OneSignal in Unity3D

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

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 !

Phonegap/Pushwoosh Android retrieving Device id / Token

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. :)

Categories

Resources