laravel 5.4 pusher(laravel echo) 403 error with private channel - laravel

sorry for my english it is not my main language.
i use laravel 5.4 + pusher + laravel echo for broadcasting.
No problem public channels everything works very well.
but on private channel i also get 403 error.
my event(newpsignal.php) :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class newpSignal implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user_id;
public function __construct($user_id)
{
$this->user_id=$user_id;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('reload-account-'.$this->user_id);
}
}
my channels.php
Broadcast::channel('reload-account-.{user_id}', function ($account,$user_id) {
return true; //Auth::id()===$user_id;
});
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
authEndpoint: 'http://localhost/public/broadcasting/auth',
broadcaster: 'pusher',
key: '********', //its my key
cluster: 'eu',
encrypted: true,
});
other js code on blade(public listen work):
Echo.channel('<?php echo Redis::get('default_'.Auth::id());?>-market')
.listen('newSignal', function (e) {
doOrders(e.signal);
});
Echo.private('reload-account-<?php echo Auth::id();?>')
.listen('newpSignal', function (e) {
alert(e)
});
error:
Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: in file C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\Broadcaster.php on line 65
Stack trace:
1. Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException->() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\Broadcaster.php:65
2. Illuminate\Broadcasting\Broadcasters\Broadcaster->verifyUserCanAccessChannel() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php:50
3. Illuminate\Broadcasting\Broadcasters\PusherBroadcaster->auth() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastManager.php:310
4. Illuminate\Broadcasting\BroadcastManager->__call() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:221
5. Illuminate\Support\Facades\Facade->__callStatic() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastController.php:19
6. Illuminate\Broadcasting\BroadcastController->authenticate() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
7. call_user_func_array() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
8. Illuminate\Routing\Controller->callAction() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45

Related

Why notification event is not triggered in pusher?

When in Laravel 9 app logged user fill ContactUs form I need to send email to site support and show
notification in app for any logged support member. I make it with notification and pusher
In app/Notifications/ContactUsCreatedNotification.php :
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification
{
public $title;
public $content_message;
public $authorUser;
public function __construct(string $title, string $content_message, User $authorUser)
{
$this->title = $title;
$this->content_message = $content_message;
$this->authorUser = $authorUser;
}
public function via($notifiable)
{
return ['mail', 'broadcast']; // I added broadcast here
}
public function toMail($notifiable)
{
return (new MailMessage)->markdown('mail.ContactUsCreatedNotification', [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser
]);
}
public function toArray($notifiable)
{
return [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser,
];
}
}
I got email on configured mailtrap but Debug console of my pusher app has no event : https://prnt.sc/L9nXEfup_3i-
in .env :
BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
FILESYSTEM_DISK=local
SESSION_DRIVER=database
SESSION_LIFETIME=120
PUSHER_APP_ID=NNNN
PUSHER_APP_KEY=XXXXX
PUSHER_APP_SECRET=XXXXX
PUSHER_APP_CLUSTER=eu
In resources/js/bootstrap.js :
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
// alert('resources/js/bootstrap.js')
console.log('process.env.MIX_PUSHER_APP_KEY::')
console.log(process.env.MIX_PUSHER_APP_KEY)
console.log('process.env.MIX_PUSHER_APP_CLUSTER::')
console.log(process.env.MIX_PUSHER_APP_CLUSTER)
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});
In the app I have
"laravel/framework": "^v9.6.0",
"predis/predis": "^1.1",
"pusher/pusher-php-server": "^7.0",
and
"laravel-echo": "^1.11.7",
Any ideas why notification event is not triggered ?
UPDATED BLOCK # 1:
in .env file I set parameters
QUEUE_CONNECTION=redis
I do :
foreach ($supportManagers as $nextSupportManager) {
if ($nextSupportManager->user) {
$ret = Notification::sendNow($nextSupportManager->user, new ContactUsCreatedNotification(
$request->title,
$request->content_message,
auth()->user()
));
}
}
Also I tried to add Queueable definition i app/Notifications/ContactUsCreatedNotification.php file:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
public $title;
public $content_message;
public $authorUser;
But I still get email in mailtrap and not events in pusher...
Thanks!

Laravel livewire not handle listener from broadcast

I tried to listen event emited from broadcast in laravel livewire but nothing happen;
on my bootstrap.js i have:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKey',
wsHost: window.location.hostname,
wsPort: 6001,
disableStat: true,
forceTLS: false,
});
my event laravel
class TaskFinished implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
//
}
public function broadcastAs(){
return 'task-finish';
}
public function broadcastOn()
{
return new Channel('TaskTricolor');
}
}
my listener
class SendTaskNotif
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param TaskFinished $event
* #return void
*/
public function handle(TaskFinished $event)
{
}
}
and my livewire component
protected $listeners = ['echo:TaskTricolor,TaskFinished' => 'eventlisten'];
// public function getListeners(){
// return [
// 'echo:TaskTricolor,TaskFinished' => 'eventlisten'
// ];
// }
public function start(){
$this->start = true;
$tricolors = new TricolorController();
$this->tricolor = $tricolors->start();
}
public function stop(){
$this->start = false;
$tricolors = new TricolorController();
$this->tricolor = $tricolors->stop();
}
public function emet(){
event(new TaskFinished());
}
public function eventlisten(){
$vars = "test";
dd($vars);
}
on my listener i put dd('test') and when the emet function is called, the dd value is showed;
So when i test with livewire listener handler, nothing happen, my dd not appear, and no error;
I tried to console log Echo from blade to test if i can handle listener, but it show that Echo is not defined, but when i console.log window, i see Echo inside
On my websocket dashboard i have this:
I don't know if it can help to solve, i use beyondcode/laravel-websockets package as driver
When I first started to use Livewire (version 1.0) we listened the messages using vanilla javascript and then called the Livewire.
document.addEventListener("DOMContentLoaded", function () {
window.Echo.private('TaskTricolor')
.listen('.task-finish', (response) => {
window.Livewire.emit('task-finish', response));
}
});
You can try this. It's not a clean solution as your approach, but I think is easier to debug.
I found the issue; on my event class i should use ShouldBroadCastNow instead ShouldBroadCast
class TaskFinished implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
//
}
public function broadcastAs(){
return 'task-finish';
}
public function broadcastOn()
{
return new Channel('TaskTricolor');
}
}
the ShouldBroadCast put the event in queue, so it's not activated on event called, but ShouldBroadCastNow listen the event immediately, here link i found the explanation
add metadata in your template
<meta name="csrf-token" content="{{ csrf_token() }}">
declare token in your boostrap.js
let token = document.head.querySelector('meta[name="csrf-token"]');
window.Echo = new Echo({
broadcaster: 'push',
.....
...
auth: {
headers: {
Authorization: 'Bearer' + token,
},
},
and call event with
document. addEventListener("DOMContentLoaded", function () {
window.Echo.private('TaskTricolor')
.listen('.task-finish', (response) => {
window.Livewire.emit('task-finish'));
}
});

Undefined eager-loaded relationship when using Echo event broadcasting

I am using Laravel Echo in my project to broadcast events to the client-side. Everything is working correctly, however, I am having a problem in eager-loading the relationships of the model for the Event.
My Controller
$chat = new Chat;
$chat->user_id = $request->user_id;
$chat->message = $request->message;
$chat->save();
event( new GetMessages( $chat ));
My Event class:
class GetMessages implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $chats;
public function __construct($chats)
{
$this->chats = $chats;
}
public function broadcastOn()
{
return ['get-messages'];
}
public function broadcastAs()
{
return 'get-messages';
}
}
Here is my Laravel Echo
Echo.channel('get-messages')
.listen('.get-messages', (data) => {
console.log(data)
})
Everything is working fine as I expected, except getting the attachments from the Chat.
console.log(data.chats); // Undefined
Is there something I missed? Because as I tested the eager-loaded from the Event class itself, I can access the attachments in there.
public $chats;
public function __construct($chats)
{
$this->chats = $chats;
echo $chats->attachments // It's working in here, I can get the attachments
}
Hope I explain it well, Thank you in advance
Cheers!
Here is the console.log
Here is use, it's the default when I created the Event
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class GetMessages implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
...

WebSocketChannelException: HandshakeException - Flutter app with Laravel Websockets on custom server Cerificated with Cpanel

I have Laravel web application includes live chat relying on Laravel Websockets https://docs.beyondco.de/laravel-websockets/
For now i am making Flutter app for same service and i am facing problem Connecting to websocket i already made on wss (I have this code)
var channel = IOWebSocketChannel.connect("wss://site.com:6001/app/123456789");
channel.sink.add(json.encode({
"event": "pusher:subscribe",
"data": {"channel": "channel-name"}
}));
channel.stream.listen((_data) {
print(_data.toString());
}, onError: (error) {
print("Socket: error => " + error.toString());
}, onDone: () {
print("Socket: done");
});
I am getting this problem : CERTIFICATE_VERIFY_FAILED which i searched about it a lot and nothing helped - one of the things i tried is to make a SecureSocket
SecureSocket secureSocket = await SecureSocket.connect(
'www.site.com', 6001,
onBadCertificate : (X509Certificate cert) => true).then((SecureSocket secureSocket) {
secureSocket.listen((List<int> event) {
print(utf8.decode(event));
});
}).catchError((error) {
print(error);
});
This code returns no error but it didn't connecting at all.
Note: same code working on ios simualtors but not on android
Also i tested my ssl certificate and it shows this result :
https://ibb.co/chyFPtX
Please can anyone help me fixing this problem?
The laravel websockets connection support a pusher driver, try using a pusher client instead that already has the protocol built-in.
For anyone who is new to the issue
Laravel Websocket here
Flutter
import 'package:web_socket_channel/io.dart';
final _channel = IOWebSocketChannel.connect(
Uri.parse(
'ws://127.0.0.1:6001/app/aap-key'),
);
#override
void initState() {
_channel.sink.add(json.encode({
"event": "pusher:subscribe",
"data": {"channel": "test-channel1"}
}));
_channel.stream.listen((_data) {
print(_data.toString());
}, onError: (error) {
print("Socket: error => " + error.toString());
}, onDone: () {
print("Socket: done");
});
super.initState();
}
#override
void dispose() {
_channel.sink.close();
}
Laravel Event
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class TestEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-channel1');
}
public function broadcastWith()
{
return ['data' => 'testing channel, testing message'];
}
}

Why broadcasting channel public not working? Laravel

I use laravel 5.3
I make routes/channels.php like this :
<?php
Broadcast::channel('messages', function() {
return true;
});
If I input the data cart and click submit, it will run this :
this.$http.post(window.BaseUrl + '/guest/add-notification', {cart_data: JSON.stringify(data)});
It will call function on the controller
The function like this :
public function addNotification(Request $request){
$input = $request->only('cart_data');
$data = json_decode($input['cart_data'], true);
event(new CartNotificationEvent($data));
}
Then it will call event
The event like this :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CartNotificationEvent
{
use InteractsWithSockets, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function broadcastWith()
{
return [
'message' => $this->data,
];
}
public function broadcastAs()
{
return 'newMessage';
}
public function broadcastOn()
{
return new Channel('messages');
}
}
On the client, I do like this :
Echo.channel('messages')
.listen('.newMessage', (message) => {
console.log('test')
console.log(message);
});
When all the code is executed, I check on the console, the console.log not display
Why is it not working?
If I see the whole code that I make, it seems the process is correct
class CartNotificationEvent implements ShouldBroadcast is missing.

Resources