Laravel中怎么利用pusher推送消息,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
一.注册pusher
1.注册
https://pusher.com/
2.获取key,密匙,app_id等
二.配置pusher
1.安装pusher
composer require pusher/pusher-php-server
2.配置config/broadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
....
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true
],
],
.....
三.建立事件
1.代码如下:
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PusherEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $info;
/**
* PusherEvent constructor.
*/
public function __construct($info)
{
$this->info = $info;
}
/**
* 指定广播频道(对应前端的频道)
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return ['my-channel'];
}
/**
* 指定广播事件(对应前端的事件)
* @return string
*/
public function broadcastAs()
{
return 'my-event';
}
/**
* 获取广播数据,默认是广播的public属性的数据
*/
public function broadcastWith()
{
return ['info' => $this->info];
}
}
2.广播事件,并不需要监听器;广播事件需要继承接口ShouldBroadcast
四.广播
1.触发事件
event(new \App\Events\PusherEvent('测试'));
2.前端代码
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('XXX', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(data.info);
});
</script>
</head>
ps:
1.pusher使用curl向https://pusher.com
提交数据,所以你需要配置证书;否则提交会失败
2.如果不配置证书,则需要设置curl的CURLOPT_SSL_VERIFYPEER
和CURLOPT_SSL_VERIFYHOST
在vender/pusher/pusher-php-server/lib/Pusher.php
中的trigger的
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_value);
下面增加:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3278236.html