uspex/laravel-fcm-set-image

Laravel / Lumen 包用于 Firebase Cloud Messaging

1.3.1 2019-11-26 16:14 UTC

README

Build Status Coverage Status Latest Stable Version Total Downloads License

简介

*** 增加了图片支持 ->setImage('url image')

简介

Laravel-FCM 是一个易于使用的包,可以与 Laravel 和 Lumen 一起使用,通过 Firebase Cloud Messaging (FCM) 发送推送通知。

它目前 仅支持 HTTP 协议,用于

  • 向一个或多个设备发送下行消息
  • 管理群组并发送消息到群组
  • 发送主题消息

注意:当前不支持 XMPP 协议。

安装

要将 Laravel-FCM 的最新版本添加到您的项目中,请从 "composer" 中要求它

$ composer require uspex/laravel-fcm-set-image:dev-master

或者,您可以直接在 composer.json 文件中添加它

{
    "require": {
        "brozot/laravel-fcm": "1.3.*"
    }
}

Laravel

直接在您的 app 配置文件 config/app.php 中注册提供者 config/app.php

Laravel >= 5.5 提供了包自动发现,归功于 rasmuscnielsen 和 luiztessadri,他们帮助在 Laravel-FCM 中实现了此功能,因此提供者和外观的注册可能不再必要。

'providers' => [
	// ...

	LaravelFCM\FCMServiceProvider::class,
]

在同一文件中添加外观别名

'aliases' => [
	...
	'FCM'      => LaravelFCM\Facades\FCM::class,
	'FCMGroup' => LaravelFCM\Facades\FCMGroup::class, // Optional
]

注意:只有在您想管理应用中的群组消息时,才需要 FCMGroup 外观。

使用以下命令发布包配置文件

$ php artisan vendor:publish --provider="LaravelFCM\FCMServiceProvider"

Lumen

在您的 bootstrap/app.php 应用文件中注册提供者

在文件的 "注册服务提供者" 部分底部添加以下行。

$app->register(LaravelFCM\FCMServiceProvider::class);

对于外观,在 "创建应用" 部分添加以下行。FCMGroup 外观仅在您想使用群组消息时才需要。

class_alias(\LaravelFCM\Facades\FCM::class, 'FCM');
class_alias(\LaravelFCM\Facades\FCMGroup::class, 'FCMGroup');

将配置文件 fcm.php 从目录 /vendor/uspex/laravel-fcm-set-image/config 手动复制到目录 /config (您可能需要创建此目录)。

包配置

在您的 .env 文件中,添加 Firebase Cloud Messaging 的服务器密钥和密钥

FCM_SERVER_KEY=my_secret_server_key
FCM_SENDER_ID=my_secret_sender_id

要获取这些密钥,您必须在 Firebase Cloud Messaging 控制台 上创建一个新的应用。

在 Firebase 上创建您的应用后,您可以在 项目设置 -> 云消息 中找到密钥。

基本用法

使用 Laravel-FCM 可以发送两种类型的消息

  • 通知消息,有时被称为 "显示消息"
  • 数据消息,由客户端应用处理

有关更多信息,请参阅 官方文档

下行消息

下行消息是指您使用其 registration_Ids 向目标设备或多个目标设备发送的通知消息、数据消息或两者都有的消息。

以下示例需要以下使用声明

use LaravelFCM\Message\OptionsBuilder;
use LaravelFCM\Message\PayloadDataBuilder;
use LaravelFCM\Message\PayloadNotificationBuilder;
use FCM;

向设备发送下行消息

$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);

$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')    
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
				    ->setSound('default');

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);

$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();

$token = "a_registration_from_your_database";

$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);

$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();

// return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();

// return Array (key : oldToken, value : new token - you must change the token in your database)
$downstreamResponse->tokensToModify();

// return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();

// return Array (key:token, value:error) - in production you should remove from your database the tokens
$downstreamResponse->tokensWithError();

向多个设备发送下行消息

$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);

$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
				    ->setSound('default');

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);

$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();

// You must change it to get your tokens
$tokens = MYDATABASE::pluck('fcm_token')->toArray();

$downstreamResponse = FCM::sendTo($tokens, $option, $notification, $data);

$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();

// return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();

// return Array (key : oldToken, value : new token - you must change the token in your database)
$downstreamResponse->tokensToModify();

// return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();

// return Array (key:token, value:error) - in production you should remove from your database the tokens present in this array
$downstreamResponse->tokensWithError();

请参阅 下行消息错误响应代码 文档以获取更多信息。

主题消息

主题消息是指您发送到注册到此主题的所有设备的通知消息、数据消息或两者都有的消息。

注意:主题名称必须由您的应用管理并由您的服务器知道。Laravel-FCM 包或 fcm 不提供一种简单的方式来执行此操作。

以下示例需要以下使用声明

use LaravelFCM\Message\Topics;

向主题发送消息

$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
				    ->setSound('default');

$notification = $notificationBuilder->build();

$topic = new Topics();
$topic->topic('news');

$topicResponse = FCM::sendToTopic($topic, null, $notification, null);

$topicResponse->isSuccess();
$topicResponse->shouldRetry();
$topicResponse->error();

向多个主题发送消息

它向以下主题注册的设备发送通知

  • 新闻和经济
  • 新闻和文化

注意:主题支持每个表达式两个运算符

$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
				    ->setSound('default');

$notification = $notificationBuilder->build();

$topic = new Topics();
$topic->topic('news')->andTopic(function($condition) {

	$condition->topic('economic')->orTopic('cultural');

});

$topicResponse = FCM::sendToTopic($topic, null, $notification, null);

$topicResponse->isSuccess();
$topicResponse->shouldRetry();
$topicResponse->error());

群组消息

向群组发送通知

$notificationKey = ['a_notification_key'];


$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
                        ->setSound('default');

$notification = $notificationBuilder->build();


$groupResponse = FCM::sendToGroup($notificationKey, null, $notification, null);

$groupResponse->numberSuccess();
$groupResponse->numberFailure();
$groupResponse->tokensFailed();

创建群组

$tokens = ['a_registration_id_at_add_to_group'];
$groupName = "a_group";
$notificationKey

// Save notification key in your database you must use it to send messages or for managing this group
$notification_key = FCMGroup::createGroup($groupName, $tokens);

将设备添加到群组

$tokens = ['a_registration_id_at_add_to_the_new_group'];
$groupName = "a_group";
$notificationKey = "notification_key_received_when_group_was_created";

$key = FCMGroup::addToGroup($groupName, $notificationKey, $tokens);

从群组中删除设备

注意:如果从群组中删除所有设备,该群组将自动在“fcm”中删除。

$tokens = ['a_registration_id_at_remove_from_the_group'];
$groupName = "a_group";
$notificationKey = "notification_key_received_when_group_was_created";

$key = FCMGroup::removeFromGroup($groupName, $notificationKey, $tokens);

选项

Laravel-FCM支持基于Firebase Cloud Messaging选项的选项。这些选项可以帮助您定义通知的特定性。

您可以根据以下方式构建一个选项

$optionsBuilder = new OptionsBuilder();

$optionsBuilder->setTimeToLive(42*60)
                ->setCollapseKey('a_collapse_key');

$options = $optionsBuilder->build();

通知消息

通知负载用于发送通知,其行为由接收设备的App状态和操作系统定义。

当应用处于后台时,通知消息被发送到通知托盘。对于前台应用,消息由以下回调处理

  • didReceiveRemoteNotification:在iOS上
  • onMessageReceived() 在Android上。数据包中的通知键包含通知。

请参阅官方文档

$notificationBuilder = new PayloadNotificationBuilder();
$notificationBuilder->setTitle('title')
            		->setBody('body')
            		->setSound('sound')
                    ->setImage('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png')
            		->setBadge('badge');

$notification = $notificationBuilder->build();

数据消息

使用您自定义的键值对设置数据键,向客户端应用发送数据负载。数据消息可以有4KB的最大负载。

  • iOS,FCM存储消息,仅在应用处于前台并建立FCM连接时才交付。
  • Android,客户端应用在onMessageReceived()中接收数据消息,并可以相应地处理键值对。

请参阅官方文档

$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData([
	'data_1' => 'first_data'
]);

$data = $dataBuilder->build();

通知和数据消息

接收同时包含通知和数据负载的消息时,应用的行为取决于应用是在后台还是前台——基本上,取决于接收消息时应用是否活跃(来源)。

  • 后台,应用在通知托盘中接收通知负载,并且仅在用户点击通知时才处理数据负载。
  • 前台,您的应用接收一个包含两个负载的消息对象。

主题

对于主题消息,Laravel-FCM提供了一个易于使用的api,用于抽象Firebase条件。为了制作例如Firebase官方文档中给出的条件,必须像以下Laravel-FCM那样进行

官方文档条件

'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)
$topics = new Topics();

$topics->topic('TopicA')
       ->andTopic(function($condition) {
	       $condition->topic('TopicB')->orTopic('TopicC');
       });

测试

对于集成测试,您可以使用mockery和Mocks包提供的mock响应。

该包提供了3种“MockResponse”

  • MockDownstreamResponse
  • MockGroupResponse
  • MockTopicResponse

您可以根据以下示例mock FCM调用

$numberSucess = 2;
$mockResponse = new \LaravelFCM\Mocks\MockDownstreamResponse(numberSucess);

$mockResponse->addTokenToDelete('token_to_delete');
$mockResponse->addTokenToModify('token_to_modify', 'token_modified');
$mockResponse->setMissingToken(true);

$sender = Mockery::mock(\LaravelFCM\Sender\FCMSender::class);
$sender->shouldReceive('sendTo')->once()->andReturn($mockResponse);

$this->app->singleton('fcm.sender', function($app) use($sender) {
	return $sender;
});

API文档

您可以在API参考中找到有关API的更多文档。

许可证

此库是开源软件,根据MIT许可证许可。

本部分文档的部分内容来自官方文档。您可以在Firebase Cloud Messaging网站上找到完整内容。