laravel集成极光推送实战
公司项目需要用到app推送消息通知,市面上很多推送渠道商,选来选去最终选定了极光推送,因为项目使用laravel写的,laravel自身又有模型事件,所以研究了一下,在不改动原有代码的情况下,给项目加了异步队列消息通知。
首先引入极光sdk
composer require "jpush/jpush"
新建Notifications驱动 JPshuChannel.php
<?php
namespace App\Notifications\Channels;
use JPush\Client;
use Illuminate\Notifications\Notification;
class JPushChannel
{
protected $client;
/**
* Create the notification channel instance.
*
* @param \JPush\Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* Send the given notification.
*
* @param mixed $notifiable
* @param \Illuminate\Notifications\Notification $notification
*/
public function send($notifiable, Notification $notification)
{
$params = $notification->toJPush($notifiable, $this->client->push());
// 这里是为了屏蔽极光服务器没有找到设备等情况报错,
try {
$push = $this->client->push();
$push->setPlatform($params['platform'])
->addAlias($params['alias'])
->iosNotification([
'title' => $params['title'],
'body' => $params['content'],
], [
'sound' => 'sonud',
'extras' => $params['data']
])
->androidNotification($params['content'], [
'title' => $params['title'],
'extras' => $params['data']
])->options(['apns_production' => env('JPUSH_DEBUG')]);
$push->send();
} catch (\Exception $exception) {
return;
}
}
}
然后创建课程购买通知类
<?php
namespace App\Notifications;
use App\Model\Course\CourseBuyModel;
use App\Model\Course\CourseModel;
use App\Model\Member\MemberModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class CourseBuyNotify extends Notification implements ShouldQueue
{
use Queueable;
public function via($notifiable)
{
return ['jpush'];
}
public function ToJPush(CourseBuyModel $model)
{
$alias = [(string)$model->seller_id];
$course = CourseModel::query()->select('id', 'title')->find($model->course_id);
$member = MemberModel::query()->select('id', 'name')->find($model->member_id);
$params = [
'platform' => 'all',
'title' => "有人购买了您的课程",
"content" => "{$member->name}购买了您的课程{$course->title}",
"data" => [
"type" => 3, //进入课程
"data" => [
"id" => $model->course_id
]
],
'type' => ['alias'],
'alias' => $alias
];
return $params;
}
}
注意这里use Queueable;引入了一个laravel自带的异步模型。可以把消息通知通过redis的方式进行异步推送。
代码写好了,怎么使用这个驱动了,当然是要去AppServiceProvider.php注册一下极光驱动
public function register()
{
Notification::extend('jpush', function ($app) {
return new JPushChannel(new Client(
$app['config']['jpush']['app_key'],
$app['config']['jpush']['master_secret'],
$app['config']['jpush']['log'],
intval($app['config']['jpush']['retry_times']) ?: 3
));
});
}
在register方法中注册一下。
config配置文件当然要有
在config目录下新建jpush.php
<?php
return [
'apns_production' => env('JPUSH_PRODUCTION', false), // 是否是正式环境
'app_key' => env('JPUSH_APP_KEY', ''), // key
'master_secret' => env('JPUSH_MASTER_SECRET', ''), // master secret
'log' => env('JPUSH_LOG_PATH', storage_path('logs/jpush.log')), // 日志文件路径 空为不写日志
'retry_times' => 3,
];
自此我们的极光推送驱动就注册好了,同时我们的课程购买消息通知也弄好了,但是怎么去使用还在后面
在AppServiceProvider.php的boot方法中注册一个观察者,观察课程被购买的模型事件
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
CourseBuyModel::observe(CourseBuyObserver::class);
}
然后CourseBuyObserver.php代码如下
<?php
namespace App\Observers\Course;
use App\Model\Course\CourseBuyModel;
use App\Notifications\CourseBuyNotify;
use Illuminate\Support\Facades\Cache;
class CourseBuyObserver
{
/**
* 有人购买了课程
*/
public function created(CourseBuyModel $model)
{
Cache::forget("course_id_{$model->course_id}");
$model->notify(new CourseBuyNotify());
}
}
注意一下该模型是CourserBuyModel.php的观察者,laravel模型中默认是不支持notify的所以需要use一下
<?php
/**
* 陈杰 18323491246
*/
namespace App\Model\Course;
use App\Model\BaseModel;
use App\Model\Member\MemberModel;
use Illuminate\Notifications\Notifiable;
class CourseBuyModel extends BaseModel
{
use Notifiable; //引入Notifiable消息通知方法
public $table = 'course_buy';
public function course()
{
return $this->hasOne(CourseModel::class, 'id', 'course_id');
}
public function seller()
{
return $this->hasOne(MemberModel::class, 'id', 'seller_id');
}
public function member()
{
return $this->hasOne(MemberModel::class, 'id', 'member_id');
}
}
自此我们的laravel集成极光推送异步通知就完成了。
最后运行一下
php artisan queue:work redis --tries=3 --delay=3
通过redis异步队列执行,当然可以用supervisor工具把他放到后台自动维护。
.env中需要配置
QUEUE_CONNECTION=redis
