laravel对接onesignal

一 获取关键参数

ONESIGNAL_APP_ID
ONESIGNAL_REST_API_KEY

二 laravel-notification-channels/onesignal简介

安装
composer require laravel-notification-channels/onesignal
基本使用
  1. 添加配置文件config/services.php
// config/services.php
'onesignal' => [
    'app_id' => env('ONESIGNAL_APP_ID'),
    'rest_api_key' => env('ONESIGNAL_REST_API_KEY')
],
  1. 用法
use NotificationChannels\OneSignal\OneSignalChannel;
use NotificationChannels\OneSignal\OneSignalMessage;
use NotificationChannels\OneSignal\OneSignalWebButton;
use Illuminate\Notifications\Notification;

class AccountApproved extends Notification
{
    public function via($notifiable)
    {
        return [OneSignalChannel::class];
    }

    public function toOneSignal($notifiable)
    {
        return OneSignalMessage::create()
            ->setSubject("Your {$notifiable->service} account was approved!")
            ->setBody("Click here to see details.")
            ->setUrl('http://onesignal.com')
            ->webButton(
                OneSignalWebButton::create('link-1')
                    ->text('Click here')
                    ->icon('https://upload.wikimedia.org/wikipedia/commons/4/4f/Laravel_logo.png')
                    ->url('http://laravel.com')
            );
    }
}

为了让您的通知知道您的目标是哪个 OneSignal 用户,请将routeNotificationForOneSignal方法添加到您的 Notifiable 模型中。

  • 您可以返回单个玩家 ID,或者如果您想通知多个玩家 ID,只需返回包含所有 ID 的数组。
   public function routeNotificationForOneSignal()
	{
	    return 'ONE_SIGNAL_PLAYER_ID';
	}
  • 如果要基于 OneSignal“syncHashedEmail”功能发送通知,只需返回索引为“email”的数组。由于 OneSignal API 的限制,不可能在一个过滤器上使用多个电子邮件。
	public function routeNotificationForOneSignal()
	{
	    return 'ONE_SIGNAL_PLAYER_ID';
	}
  • 如果您想基于 OneSignal“标签”功能发送通知,只需返回一个索引为“标签”的数组。
	public  function  routeNotificationForOneSignal () 
	{ 
	return [ 'tags' => [ 'key' => 'device_uuid' , 'relation' => '=' , 'value' => '1234567890-abcdefgh-1234567' ]]; 
	}
  • setExternalUserId如果您想根据您使用该功能设置的外部用户 ID 发送通知。这使得根据 Laravel 用户 ID 定位用户变得非常容易。
	public function routeNotificationForOneSignal()
	{
	    return ['include_external_user_ids' => $this->id];
	}

三 使用案列

使用背景介绍:
给不同的用户(user)推送不同场景下的消息通知

  • 模型返回用户的唯一ID(此次用的是user_sn)
	public function routeNotificationForOneSignal()
    {
        return ['include_external_user_ids' => [$this->attributes['user_sn']]];
    }
  • 封装消息推送模板类
<?php

namespace App\Notifications;

use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Log;
use NotificationChannels\OneSignal\OneSignalChannel;
use NotificationChannels\OneSignal\OneSignalMessage;

class OnesignalNotify extends Notification
{
    use Queueable;


    protected $title;  // 消息标题
    protected $body;   // 消息内容
    protected $data;   // 自定义字段
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($events,$data)
    {
        try{
            $this->data = $data;
            $this->messageTemplate($events);
        }catch(Exception $e){
            Log::info('onesignal '.$events.' 错误:',[$e->getMessage()]);
        }
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [OneSignalChannel::class];
    }

    public function toOneSignal($notifiable)
    {
        return OneSignalMessage::create()
            ->subject($this->title)
            ->body($this->body);
    }
    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
 	/**
    * 自定义模板类型和内容
    *
    * @param [type] $events
    * @return void
    */
    public function messageTemplate($events)
    {
        switch ($events){
            case '自定义消息类型':
                $title = array(
                    'en'=>'标题(英文版)',
                    'zh-Hans'=>'标题(中文版)'
                );
                $body = array(
                    "en" => '内容(英文版)',
                    "zh-Hans"=>'内容(中文版)',
                );
                break;
            default : 
                break;
        }
        
        $this->title = $title;
        $this->body = $body;
    }
}

  • 封装外部调用方法
	/**
	* onesignal 消息推送
	 *
	 * @param string $events 要推送的消息类型
	 * @param string $user_sn 推送用户的唯一标识
	 * @param array $data 消息推送的参数
	 * @return void
	 */
	public function sendMessage($events,$user_sn,$data = [])
	{
	    $user = User::where('user_sn',$user_sn)->first(); //实例化用户模型
	    if($user)
	    {
	        $user->notify(new OnesignalNotify($events,$data));
	    }else{
	        Log::info('onesignal '.$events.' 外部错误: '.'推送人为空');
	    }
	}
  • 使用
	$this->sendMessage($events,$user_sn,$data);

参考文档

OneSignal文档
laravel-notification-channels/onesignal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值