当前位置:首页 > PHP > 正文内容

laravel集成极光推送实战

陈杰3年前 (2020-11-26)PHP2594

公司项目需要用到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


扫描二维码至手机访问

扫描二维码推送至手机访问。

版权声明:本文由何烦过虎溪发布,如需转载请注明出处。

转载请注明出处:http://95shouyou.com/?id=12

分享给朋友:

相关文章

php对接七牛云短信验证码实战

短信验证码登录的用处非常的大,登录,注册,修改密码,安全相关的啥都可以干。选定的七牛云短信是因为存储也是用的七牛云,七牛的sdk都加载进来了,也懒得去换其他的厂家了。下面上代码:Controller层...

laravel跨库多态关联实战

laravel跨库多态关联实战

点赞记录表做了分库分表,位于副库里面表结构该点赞表关联了8个不同的表,因为业务原因,评论回复表有四个板块,所以做了4个评论记录表,4个回复记录表,且结构有细微不同。目标是用户获得被点赞记录,根据不同的...

mysql查找附近的人,经纬度查询

经纬度排序mysql函数CREATE DEFINER=`root`@`localhost` FUNCTION `get_distance`(`lon1` float,`lat1` float,`lon...

php对接支付宝转账到第三方接口实战

公司项目有一个用户钱包系统,用户创作的内容可以收到游客的打赏,当然就需要提现的接口了。最终选定的是支付宝转账接口,公司代收账户直接打款给用户绑定的支付宝账号,再也不用人工手动打款了。上代码准备好工具,...

通过代码创建多个同样的mysql表

在分库分表中可能要同时创建多个结构相同但后缀不同的表,通过代码实现for ($i = 3; $i <= 20; $i++) {    DB::connection('...

利用workerman实现webrtc实时音视频通话

利用workerman实现webrtc实时音视频通话

实现原理利用workerman的websocket实现实时消息传递。webrtc自带p2p功能,利用STUN中继服务器实现webrtc实时音视频看看我们的前端文件,只是一个单页面<html>...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。