I am trying to design a chat application where I am trying to pass messages throuhh Pusher's private channels for real time delivery.
I am working with Smart Admin Theme's ajax version and I am working with the chat UI plugin that ships with the theme itself.
Basically I have Mapbox map and using Leaflet I have placed a lot of markers on the map, where each marker is a user.
So basically when the user is logged in, he can view the other users on the map and when he clicks the map, this code executes:
// Binding the marker on click event to bring up the chat
marker.on('click', function(){
var chatboxId = 'private-' + currentUser.id + '-' + user.id;
chatboxManager.addBox(chatboxId, {
first_name: user.first_name,
last_name: user.last_name,
});
// Creating a new chatbox
$('#' + chatboxId).chatbox({
messageSent: function(id, user, message){
this.boxManager.addMsg('Me', message);
splittedId = id.split('-');
$.ajax({
url: '/messages',
method: 'post',
type: 'json',
data: {
receiver_id: splittedId[2],
body: message
}
});
}
});
// Initializing pusher and authenticating the private channel
var pusher = new Pusher('082bab423e2a8be3da2a', {
authTransport: 'jsonp',
authEndpoint: '/pusher/auth'
});
// Subscribing to the channel where the name of the channel is private-senderId-receiverId
var chat = pusher.subscribe('private-' + user.id + '-' + currentUser.id);
console.log(chat);
chat.bind('message', function(response){
console.log(response);
});
});
This code generates a new chatbox for the user that was clicked on the map. At this point pusher is also initialized and it contacts '/pusher/auth' for authentication for the private channel.
The authentication is working fine. I know this because pusher returns a token as it is supposed to in JSON. Then I bind the channel variable to listen to "message" event but I cannot listen to the new messages on the channel.
Further more when I tried to console.log(chat)
(the private channel), it outputs this in the console:
Object { callbacks: Object, global_callbacks: Array[0], failThrough: b/<(), name: "private-1-1", pusher: Object, subscribed: false }
The subscribed is false for some reason. What am I doing wrong? I am sure I am missing something small somewhere and I have been at this for more that 2 hours now. Can anybody point out what am I missing?
Edit : Server side route for authentication
Route::get('/pusher/auth', function(\Illuminate\Http\Request $request, \App\User $user){
$data = $request->all();
$explodedChannel = explode('-' ,$data['channel_name']);
if($user->currentUser()->id == $explodedChannel[2]){
$pusher = new \Pusher(
getenv('PUSHER_PUBLIC'),
getenv('PUSHER_PRIVATE'),
getenv('PUSHER_APPID')
);
echo $pusher->socket_auth($data['channel_name'], $data['socket_id']);
}
else{
return response()->json('Forbidden', 403);
}
});
edit your server side code where echo auth response like this:
edit this
to