laravel-websockets connect to channles without laravel-echo - laravel

I have a websocket server implemented with laravel-websockets package which broadcasts data on some private channels. At the moment server does not support two-way communication. I want to make this public for anyone to be able to connect to this websocket by using an auth token. But I can't find anything helpful regarding this.
Currently I am using laravel-echo and pusher-js to connect from a separate app which works fine. But what if someone does not want to use these packages i.e. what would be the nodejs implementation to connect to this socket.
For reference here is my laravel-echo implementation to connect to this socket.
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: '{appkey}',
wsHost: '{sockethosturl}',
wsPort: 6001,
forceTLS: false,
authEndpoint: '{auth endpoint on socket server}',
disableStats: true,
auth: {
headers: {
'Auth-Token': '{ random auth token }',
}
}
});
And then I subscribe to channels using this
Echo.private('private-channel-1')
.listen('.update', (event) => {
console.log("Found event");
console.log(event);
});
Looking for a way to translate this into a socket-io or any other websocket client side library.

Related

Laravel/Vuejs and Pusher Not Connecting to Private Channel on Heroku

I have a laravel/vuejs realtime application, works on my local environment but when I deploy to heroku /auth/broadcast shows unsual response,
bootstrap.js
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': window.csrf_token
};
const JWTtoken = `Bearer ${localStorage.getItem('access_token')}`
import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
window.Pusher = require('pusher-js');
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true,
encrypted: true,
auth: {
headers: {
'Authorization' : JWTtoken,
}
}
});
In vue.js component
Echo.private(`App.User.${this.user.id}`)
.notification((notification) => {
console.log(notification.type)
});
Response from my local environment (Successful)
Pusher : : ["Event sent",{"event":"pusher:subscribe","data":{"auth":"0d5290e189b56045e99d:e2156d7e13673a1e06f0c2b8974655247a55055de1f7eb31022a1a171615cb8c","channel":"private-App.User.4"}}]
broadcasting/auth response from local environment
Error from broadcasting/auth on heroku
Pusher : : ["Error: JSON returned from auth endpoint was invalid, yet status code was 200. Data was: "]
Error pusher broadcasting/auth
Any help or suggestions. Thanks
The auth endpoint response should be a JSON string with an auth property of a value composed from the application key and the authentication signature, separated by a colon : as follows:
{
"auth": "278d425bdf160c739803:58df8b0c36d6982b82c3ecf6b4662e34fe8c25bba48f5369f135bf843651c3a4"
}
You should check what the auth endpoint is returning.
Source

Flutter + Laravel Websocket + Pusher Replacement (Valet Secure)

I'm using Beyondco Larevel Websockets on my Laravel Backend, and using pusher_client and laravel_echo on my Flutter frontend.
I've been trying to connect from my ios simulator into my Laravel Backend host, which is using valet secure, but failing.
My Flutter connections:
PusherClient getPusherClient(String token) {
PusherOptions options = PusherOptions(
host: 'my-local-server.test',
wsPort: 6001,
wssPort: 6001,
cluster: DotEnv.env['PUSHER_APP_CLUSTER'],
encrypted: true,
auth: PusherAuth('https://my-local-server.test/api/broadcasting/auth',
headers: {'Authorization': 'Bearer $token'})
);
return PusherClient(DotEnv.env['PUSHER_APP_KEY'], options,
enableLogging: true, autoConnect: false);
}
pusherClient = getPusherClient(token);
pusherClient.connect();
pusherClient.onConnectionStateChange((state) {
print(
"previousState: ${state.previousState}, currentState: ${state.currentState}");
});
pusherClient.onConnectionError((error) {
print(error.message);
});
From https://my-local-server.test/laravel-websockets I never see the requests from Flutter, but if I fire an event from my Laravel backend, it gets logged.
Please help me with what's wrong in my setup, why I can't connect to my SSL valet server running laravel-websocket from my Flutter application.

Use Laravel echo with Laravel mix

I am new to the Laravel Mix frontend framework All I want to know is how can we use Laravel Echo with Laravel Mix. I am using Laravel database notifications and I want to show them in real-time to the user.
Notifications are working fine and I am also able to list it to the users. For showing them in real-time I am using Pusher and it integrated well. I have tested by sending some events through debug console. In my project I am unable to find bootstrap.js file to place below code:
let token = document.head.querySelector('meta[name="csrf-token"]');
import Echo from "laravel-echo"
window.pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
In app.js file I want to place below code to listen notification real time:
let userId = document.head.querySelector('meta[name="user-id"]').content();
Echo.private('App.User.'+userId)
.notification((notification) => {
console.log(notification.data);
});
I am using Laravel 7.30.0 version. In my project, I don't have an assets folder. The structure is like below:
resources
-> Js
-> app.js
In app.js I have tried to write above code but it throws me below error:
Uncaught SyntaxError: Cannot use import statement outside a module
How can I use Laravel Echo with Laravel Mix? I have no prior experience in Laravel Mix.
First, install Laravel Echo and Pusher.
npm install --save-dev laravel-echo pusher-js
In a fresh install of Laravel 7.x there are two files in /resources/js/.
Those are: app.js and bootstrap.js. In bootstrap.js you will see a commented out section for Echo.
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
Remove the comments and go ahead and run npm run dev.
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
);
Make sure you have the latest version of Mix and that your webpack.mix.js is properly configured.
npm i laravel-mix#latest --save-dev

Laravel private channel authorization not working

I am learning pusher to use it with Laravel, I am trying to subscribe to private channel using Laravel-echo as follow:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
Pusher.logToConsole = true; //update: added this
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
var channel = window.Echo.private('roomr');
and per Laravel documentations I have to set authorization in channel.php file so in I wrote in it:
Broadcast::channel('roomr', function ($user) {
logger('hit authorize roomr');
return true;
});
please note that I used logger('hit authorize roomr'); to know if my function is being called, but, when I check the log file it is empty which means that this function is not being called.
using developer tools in google chrome I see there is a post request sent to http://127.0.0.1:8000/broadcasting/auth which return response 200, so, I do not think the authentication is the problem.
Update:
after I added Pusher.logToConsole = true; to my javascript now in chrome console I get:
Pusher : : ["JSON returned from auth endpoint was invalid, yet status
code was 200. Data was: "]
what else I can do? please help me to solve this probem
The problem was in the .env file and I solved it by setting BROADCAST_DRIVER=pusher

Laravel Echo error handling (with Pusher)

Is there any guide about this topic? I have read the pusher documentation and it seems fairly easy to manage a disconnect with a code similar to the following:
pusher.connection.bind('disconnected', function() {
// Do Something
})
I'm not sure how to integrate it with Echo, since my code is as follows:
window.EchoConnection = new Echo({
broadcaster: 'pusher',
key: window.EchoKey,
cluster: 'eu',
encrypted: true
});
EDIT: in order to check a disconnect event, run window.EchoConnection.connector.pusher.connection.disconnect() in your console
I haven't tried it yet, but according to the github repo this should work for pusher:
window.EchoConnection is an Echo Object. When you create a new pusher instance with echo, the connector variable will be a PusherConnector:
if (this.options.broadcaster == 'pusher') {
this.connector = new PusherConnector(this.options);
}
Over this variable you can find the Pusher instance that is created:
connect(): void {
this.pusher = new Pusher(this.options.key, this.options);
}
The theoretical solution for binding events to the pusher would be:
window.EchoConnection.connector.pusher.connection.bind('disconnected', function() {
// Do Something
})

Resources