There's been a lot of talk about this already, but I just found confusion.
I want to send notifications on my android app to a single user.
(I hate android studio, and I'm not that good at java)
I have my website with registration/login, and user id.
The idea is to create a mysql table with my Onesignal userId and playerId, and then send push notifications to a single user via curl.
I connected oneSignal to my app in android studio.
(I receive push notification if i send it from onesignal)
I have this code which allows me to save the playerId of OneSignal in my database, but I can only get the playerId from website, not from android app.
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "bb1bf59b-fb3b-4906-a0a8-279d5623f9d7"
});
});
OneSignal.push(function() {
//playerid salvato in mysql
OneSignal.isPushNotificationsEnabled(function(isEnabled) {
if (isEnabled) {
// user has subscribed
OneSignal.getUserId( function(userId) {
//console.log('player_id of the subscribed user is : ' + userId);
// Make a POST call to your server with the user ID
AjaxOneSignal('onesignal.php', '?uid=<? echo $user_uid; ?>&rand=<? echo time(); ?>&playerid='+userId);
});
}
});
});
</script>
How do I get it from android app?
(Sending my userId as a tag to OneSignal would also be fine for me, I just need a quick and easy way that works.
Please help me get out of this stupid nightmare...
(No, i dont want to use firebase, that thing doesn't work, it breaks with every update of a plugin, a module, an sdk, android studio, etc, etc, etc... I wasted three days of my life with that crap without getting anything.)
So...
i do this
And this
but no id from android app and i see this error in firefox
Updated:
As I see you have OneSignal SDK in your application. You can use this method to get playerId
OneSignal.addSubscriptionObserver(new OSSubscriptionObserver() {
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges osSubscriptionStateChanges) {
String playerId = osSubscriptionStateChanges.getFrom().getUserId();
}
});
Here can use JavascriptInterface, it allows to call java code from the javascript.
When you get userId from OneSignal store it in some variable.
Then create method like this. In this case I create it in Activity:
#JavascriptInterface
public String getUserId() {
return userId;
}
After that you need add JavaScriptInterface to your webview:
webView.addJavascriptInterface(this,"OneSignalBridge")
webView.setWebChromeClient(new WebChromeClient());
Here we use this, because our method with JavascriptInterface annotation located in Activity.
OneSignalBridge - is just a random name, you can use any name you want
Now you can call this method from javascript code.
<script>
function someFunc(){
var userId = OneSignalBridge.getUserId();
}
</script>
Related
In my laravel app, I want to send a notification to a specific user using Pusher.
I put this code in my method :
$pusher = App::make('pusher');
$pusher->trigger( 'notification-channel',
'notification-event',
array('text' => 'this is a notification'));
return view('home');
and put this in home.blade.php :
<script src="//js.pusher.com/3.0/pusher.min.js"></script>
<script>
var pusher = new Pusher("{{env("PUSHER_KEY")}}");
var channel = pusher.subscribe('notification-channel');
channel.bind('notification-event', function(data) {
alert(data.text);
});
but this makes notification to appear to any user.
This also has another problem that the user should be only on the home page to receive the notification!
So, what should I do to send a notification to a specific user and make the user receive it from any page ??
To make the user receive it from any page, put your Pusher code in your layout.blade.php if you have any. Or any other file that all pages will extends.
To make it go to a specific user, you can use the user id by appending it to the channel like
'notification-channel:' . $user->id
So in your layout file you listen to that channel
var user = <?php echo $user ; ?>;
var channel = pusher.subscribe('notification-channel:' + user.id);
Although only user with that easy might receive the notification, your notification remains public. Meaning anyone can manipulate their id and receive someone else notifications. If you want private notifications, you can follow instructions here: https://laravel.com/docs/5.4/broadcasting#authorizing-channels
I have developed an app in PHP which
1. process some data on friends of the user (extracted using taggable_friends) and then generates an image and save it on the app server.
2. Shows the image to the user and offers option to share the image on their timeline.
3. Now I need to tag some friends also in that timeline post [as I should use taggable_friends for tagging also not just for getting friends of the user as per Fb guidelines].
I'm using this code to get list of friends
$friends = $fb->get('/me/taggable_friends?fields=name,first_name,id,picture.width(80).height(80)&limit=500')->getGraphEdge()->asArray();
But I don't know how to tag the friends [using PHP] on the timeline while sharing using Javascript. Please help. I can't find an answer to do this job which still works in 2016.
Javascript code to share
function shareOnFacebook() {
var response = '';
FB.ui(
{
method: 'share',
href: linkToShare,
},
function(response) {
if (response && response.post_id) { } else {
alert('Something went wrong !');
}
}
);
};
I would like to implement a real time notification like facebook on my website using angular, php and mysql. Is there any reference links or tutorials anyone can help me out with?
Also, is there any other tools by which I can implement the same on my website?
Try to use Socket.io, it will help you to implement notification , chat or any real time application.
You can use these things to make such functionalities.
PHP JSON Based API
PHP Socket Based JSON API
Socket IO based API
All these API can easily be parsed by AngularJS or jQuery
For PHP, How to make an API
<?php
//Set header for Javascript to recognize it as the JSON output
header('Content-Type:application/json;');
//I am using GET parameters, but POST can also be used and can make amazing APIs
switch($_GET['action']){
case "addlike":
//SQL Query passed to add a like as facebook
//Set the output array to provide json Output, here's the example
$output['status'] = 200;
$output['message'] = 'Like Added';
break;
case "addcomment":
break;
}
echo json_encode($output);
To use above code, the URL would be:
http://yourserve/youfile.php/?action=addlike
And the Output would be
{
"status":200,
"message":"Like Added"
}
How to use it in jQuery
/** For Example you have like button with class="btnlike" **/
$('.btnlike').on('click',function(){
$.get('http://yourserve/youfile.php',{action:'addlike'},function(data){
if(data['status'] == 200){ alert('You Liked the Post'); }
});
});
How to use in AngularJS
app.controller('myCtrl',function($scope,$http){
$scope.message = '';
$scope.addlike = function(){
$http.get('http://yourserve/youfile.php',{action:"addlike"}).success(function(data){
if(data['status']==200){ $scope.messages = 'You liked the post'; }
});
};
});
I'm using Pusher to broadcast my Laravel Events, however I'm facing a doubt:
If I have a channel, let's name it global_updates which I would like to use to send global updates like news or site status so I just do:
var pusher = new Pusher('#################', {
encrypted: true
});
var channel = pusher.subscribe('global_updates');
channel.bind('global_event', function(data) {
// stuff
});
So, until here everything goes fine, but what if I would like to consume several events for the same channel? How can I manage it? Should I do:
var pusher = new Pusher('#################', {
encrypted: true
});
var channel = pusher.subscribe('global_updates');
channel.bind('global_event', function(data) {
// stuff
});
channel.bind('global_event2', function(data) {
// stuff for other event
});
channel.bind('global_event3', function(data) {
// stuff for the 3rd event
});
Is that a good approach? Now, what if I would like to send peruser messages along with the global, let's say there is a channel per user named user_(user_id) but I still want to consume the global events. Should I subscribe to both at the same time?
var pusher = new Pusher('#################', {
encrypted: true
});
var channel = pusher.subscribe('global_updates');
var UserChannel = pusher.subscribe('user_(user_id)');
channel.bind('global_event', function(data) {
// stuff
});
UserChannel.bind('per_user_event', function(data) {
// stuff
});
The thing is I could then have like 100s of subscribed users but not unique users, since each one could be subscribed to several channels, even when they are not consuming messages.
What should I do?
tl;dr: your approach is sound.
A client can subscribe to as many channels as they like - there are no restrictions. The only time there is any significant overheard would be when subscribing to 100s of channels or subscribing to many private channels where each subscription will result in an authentication call (however this can be batched).
From a "good practice" point of view I would recommend having one channel for global events received by all users and each user should have their own channel upon which events are sent that should only be received by that user. For security purposes I'd recommend the user channel to be a private channel. If you are using Event Broadcasting within Laravel you'll need to implement an authentication endpoint and that will require setting up the Pusher Laravel Bridge.
I'd recommend the Building Real-Time Laravel Apps with Pusher (which I wrote - I work for Pusher).
I'm building a chat room web application using Pusher for the first time. I read a lot in the documentation of Pusher to learn how it works. My question is more about mechanism and not about code.
So what I want to do is, when a user connects and joins the presence-channel which allows me to display who is online. I want to display a status sign (Green = online, yellow = away) for the user (like Skype) and all the logged users can see the change between status in real time.
I have seen this question and if I understand, each user must join a private-channel to manage better its client-event. So how can I manage the changing status event for the private-channel and show it in the presence-channel or how can I make a communication between the two channels?
You don't need a separate channel in order to build user status.
The best way to achieve this right now would be to detect user status using something like idle.js and then trigger an event on the presence channel (maybe client-status-updated) with information about the user status (e.g. {"user_id":SOME_ID, "status":"away"}).
Note: for client events the client- prefix is required on the event name
You can do this using client events and this can be done on the existing existing presence channels. However, you should be aware that by using client events it means any authenticated user could potentially trigger a status event and suggest it is for another user altogether. So, it would be more secure to do this via the server that can set the even it coming from the user who's status is being set.
However, I don't really see the benefit of the "hack" to set another user's status.
Here's an example using the presence channel and client events.
<script src="libs/idle.js"></script>
<script src="//js.pusher.com/2.2/pusher.min.js"></script>
<script>
var pusher = new Pusher(APP_KEY);
var presence = pusher.subscribe('presence-online');
// Basic online/offline
presence.bind('pusher:subscription_succeeded', function(members) {
members.each(addUser);
});
presence.bind('pusher:member_added', addUser);
presence.bind('pusher:member_removed' removeUser);
function addUser(member) {
// Online - add to UI
}
function removeUser(member) {
// Offline - remove from UI
// Consider doing this in a setTimeout
// in case the user comes back online again
}
// User state
var idle = new Idle({
onHidden: function() { sendUserStatus('hidden'); },
onVisible: function() { sendUserStatus('visible'); },
onAway: function() { sendUserStatus('away'); },
onAwayBack: function() { sendUserStatus('hidden'); },
awayTimeout: 30000 //away with 30 seconds of inactivity
}).start();
function sendUserStatus(status) {
var userStatusUpdate = {
"user_id": presence.members.me.id, // current user unique ID
"status": status
};
presence.trigger('client-status-updated', userStatusUpdate);
}
presence.bind('client-status-updated', function(update) {
var userId = update.user_id;
var status = user.status;
// Update UI to reflect user status
});
</script>