快捷地集成极光推送(JPush)到 Laravel 项目中
需求概述#
我们在开发 Laravel 应用项目地时候,经常会用到 “推送”,Laravel 自带了 Pusher 进行推送,但是国内环境大家都懂!所以这里以集成极光推送为例。
依赖极光 SDK#
我们进入 Laravel 项目执行 composer require jpush/jpush
进行依赖。
创建配置文件#
现在进入 Laravel 项目地 config/
目录,创建一个 jpush.php
配置文件:
<?php
return [
'production' => env('JPUSH_PRODUCTION', false), // 是否是正式环境
'key' => env('JPUSH_APP_KEY', ''), // key
'secret' => env('JPUSH_MASTER_SECRET', ''), // master secret
'log' => env('JPUSH_LOG_PATH', storage_path('logs/jpush.log')), // 日志文件路径
];
创建 JPush 单例到容器#
为了方便之后在驱动中获取 JPush 实例,我们打开 app/Providers/AppServiceProvider.php
文件,在 register
方法中进行注册单例:
use JPush\Client as JPushClient;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
// 注册 JPush 客户端单例
$this->app->singleton(JPushClient::class, function ($app) {
$options = [
$app->config->get('jpush.key'),
$app->config->get('jpush.secret'),
$app->config->get('jpush.log'),
];
return new JPushClient(...$options);
});
}
}
创建驱动#
我们在 Laravel 应用的 app/Notifications/
目录下创建一个 Channels/
目录,然后在其目录下创建一个 JPushChannel.php
文件 app/Notifications/Channels/JPushChannel.php
:
<?php
namespace App\Notifications\Channels;
use JPush\Client as JPushClient;
use Illuminate\Notifications\Notification;
class JPushChannel
{
protected $client;
/**
* Create the notification channel instance.
*
* @param \JPush\Client $client
*/
public function __construct(JPushClient $client)
{
$this->client = $client;
}
/**
* Send the given notification.
*
* @param mixed $notifiable
* @param \Illuminate\Notifications\Notification $notification
*/
public function send($notifiable, Notification $notification)
{
$push = $notification->toJPush($notifiable, $this->client->push());
// 这里是为了屏蔽极光服务器没有找到设备等情况报错,
try {
$push->send();
} catch (\Throwable $th) {
//throw $th;
}
}
}
注册驱动#
创建完成驱动后,我们需要注册驱动。所以我们打开 app/Providers/AppServiceProvider.php
文件在 register
添加注册代码:
use App\Notifications\Channels\JPushChannel;
use Illuminate\Notifications\ChannelManager;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
// 添加 JPush 驱动
$this->app->extend(ChannelManager::class, function ($manager) {
$manager->extend('jpush', function ($app) {
return $app->make(JPushChannel::class);
});
});
}
}
场景使用#
我们打开 app/Notifications/
目录下需要走极光推送的文件,录入我这里以「评论为例」:
use JPush\PushPayload;
class CommentByMeow extends Notification
{
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['database', 'jpush']; // 表示除了保存到数据库外,进行极光推送,`jpush` 就是注册驱动的时候的 key。
}
// 只需要按需设置好 JPush 的 payload 并返回回去就好了了
public function toJPush($notifiable, PushPayload $payload): PushPayload
{
return $payload
->setPlatform('all')
// ... 参考 https://github.com/jpush/jpush-api-php-client/blob/master/doc/api.md#push-api
;
}
}
以我自己使用的为例:
其他#
声明:我不是在做 JPush 广告,只是因为自己产品在使用,特意分享给大家!本人和极光推送没有任何关系。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: