paxha/laravel-push-notifications

Laravel 包,用于向 Android 和 IOS 设备发送推送通知。(GCM、FCM、APN)

v6.0.0 2022-05-24 05:56 UTC

README

Build Status Total Downloads Latest Stable Version License

这是一个易于使用的推送通知包。

可用的推送服务提供商

  • GCM
  • FCM
  • APN

安装

Laravel 版本低于 5.8

在控制台中输入

composer require "edujugon/push-notification:^v3.0.0"

Laravel 5.8/6 及以上

在控制台中输入

composer require edujugon/push-notification

该包将自动注册其服务提供者。

将包的配置文件发布到应用的配置目录中

php artisan vendor:publish --provider="Edujugon\PushNotification\Providers\PushNotificationServiceProvider" --tag="config"

直接访问 laravel facade 示例

配置

发布配置后,您可以在 config/pushnotification.php 中找到推送服务配置。

GCMFCM 的默认配置参数为

  • priority => normal
  • dry_run => false
  • apiKey => 您的 ApiKey

您可以通过调用方法 setConfig 如下动态更新这些值或添加新的值

$push->setConfig([
    'priority' => 'high',
    'dry_run' => true,
    'time_to_live' => 3
]);

APN 的默认配置参数为

  • certificate => __DIR__ . '/iosCertificates/yourCertificate.pem'
  • passPhrase => 'MyPassPhrase'
  • passFile => __DIR__ . '/iosCertificates/yourKey.pem' // 可选
  • dry_run => false

(如果您使用的是开发 *.pem 证书,请确保将 dry_run 设置为 true,对于生产环境设置为 false

您也可以动态更新这些值并添加更多

$push->setConfig([
    'passPhrase' => 'NewPass',
    'custom' => 'MycustomValue',
    'dry_run' => true
]);

即使您可以动态更新推送服务的 URL 如下所示

$push->setUrl('http://newPushServiceUrl.com');

除非真的有必要,否则不要更新 URL。

您可以在 setConfig() 关联数组中指定客户端在放弃之前尝试连接 APN 的次数。默认值为 3 次尝试。您可以通过指定 connection_attempts 来覆盖此值。请注意,请求尝试的默认次数为 3。

如果您希望无限期重试,请将 connection_attempts 设置为零。

$push->setConfig([
    'passPhrase' => 'NewPass',
    'custom' => 'MycustomValue',
    'connection_attempts' => 0,
    'dry_run' => true
]);

用法

$push = new PushNotification;

默认情况下,它将使用 GCM 作为推送服务提供商。

对于 APN 服务

$push = new PushNotification('apn');

对于 FCM 服务

$push = new PushNotification('fcm');

现在您可以使用您需要的任何方法。请参阅 API 列表。

API 列表

仅适用于 Gcm 和 Fcm

仅适用于 Fcm

直接访问 用法示例

setService

setService 方法设置要使用的推送服务,您通过参数传递名称作为字符串。

语法

object setService($name)

setMessage

setMessage 方法设置消息参数,您通过参数传递值作为数组。

语法

object setMessage(array $data)

setApiKey

仅适用于 gcm 和 fcm

setApiKey 方法设置您应用的 API Key,您通过参数传递密钥作为字符串。

语法

object setApiKey($api_key)

setDevicesToken

setDevicesToken 方法设置设备的 tokens,您通过参数传递 token 作为数组或字符串(如果只有一个 token)。

语法

object setDevicesToken($deviceTokens)

send

send 方法发送通知。

语法

object send()

getFeedback

getFeedback 方法获取通知响应,您可以使用它通过链式调用 send 方法,或者在任何发送通知后调用它。

语法

object getFeedback()

getUnregisteredDeviceTokens

getUnregisteredDeviceTokens 方法获取无法接收通知的设备的 tokens,因为这些设备未注册到推送服务提供商。您可以使用它通过链式调用 send 方法,或者在任何发送通知后调用它。

语法

array getUnregisteredDeviceTokens()

setConfig

setConfig 方法设置推送服务配置,您通过参数数组传递名称。

语法

object setConfig(array $config)

setUrl

setUrl 方法设置推送服务URL,您通过字符串参数传递名称。

语法

object setUrl($url)

除非真的有必要,否则不要更新 URL。

sendByTopic

仅适用于fcm

sendBytopic 方法通过主题发送消息。它也接受主题条件。更多详细信息 这里

如果isCondition为true,$topic将被视为一个表达式

语法

object sendByTopic($topic,$isCondition)

使用示例

您可以链式调用方法。

GCM示例

$push->setMessage([
        'notification' => [
                'title'=>'This is the title',
                'body'=>'This is the message',
                'sound' => 'default'
                ],
        'data' => [
                'extraPayLoad1' => 'value1',
                'extraPayLoad2' => 'value2'
                ]
        ])
        ->setApiKey('Server-API-Key')
        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...]);

APN示例

$push->setMessage([
            'aps' => [
                'alert' => [
                    'title' => 'This is the title',
                    'body' => 'This is the body'
                ],
                'sound' => 'default',
                'badge' => 1

            ],
            'extraPayLoad' => [
                'custom' => 'My custom data',
            ]
        ])
    ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...]);

或单独执行

$push->setMessage([
       'notification' => [
               'title'=>'This is the title',
               'body'=>'This is the message',
               'sound' => 'default'
               ],
       'data' => [
               'extraPayLoad1' => 'value1',
               'extraPayLoad2' => 'value2'
               ]
       ]);
$push->setApiKey('Server-API-Key');
$push->setDevicesToken(['deviceToken1'
    ,'deviceToken2',
    'deviceToken3'
]);

如果您只想发送通知到1台设备,您可以将值作为字符串传递。

$push->setDevicesToken('deviceToken');

发送通知

方法send()也可以链式调用上述方法。

$push->setMessage([
       'notification' => [
               'title'=>'This is the title',
               'body'=>'This is the message',
               'sound' => 'default'
               ],
       'data' => [
               'extraPayLoad1' => 'value1',
               'extraPayLoad2' => 'value2'
               ]
       ])
    ->setApiKey('Server-API-Key')
    ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
    ->send();

通过主题发送通知(仅限FCM

$push = new PushNotification('fcm');
$response = $push->setMessage(['message'=>'Hello World'])
            ->setApiKey('YOUR-API-KEY')
            ->setConfig(['dry_run' => false])
            ->sendByTopic('dogs');

或带有条件

$push = new PushNotification('fcm');
$response = $push->setMessage(['message'=>'Hello World'])
            ->setApiKey('YOUR-API-KEY')
            ->setConfig(['dry_run' => false])
            ->sendByTopic("'dogs' in topics || 'cats' in topics",true);

理解Gcm和Fcm消息有效负载

通知消息

setMessage方法设置消息时添加notification键,如下所示

$push->setMessage([
           'notification' => [
                   'title'=>'This is the title',
                   'body'=>'This is the message',
                   'sound' => 'default'
                   ]
           );

您可以在setMessage方法设置消息时添加一些额外的有效负载,添加一个data键。

$push->setMessage([
           'notification' => [
                   'title'=>'This is the title',
                   'body'=>'This is the message',
                   'sound' => 'default'
                   ],
           'data' => [
                   'extraPayLoad1' => 'value1',
                   'extraPayLoad2' => 'value2'
                   ]
           ]);

数据消息

默认情况下,此包将通知作为数据消息发送。因此,无需添加data键。

$push->setMessage([
           'title'=>'This is the title',
           'body'=>'This is the message',
           'myCustomVAlue' => 'value'
       ]);

上面的例子就像您正在发送以下内容

$push->setMessage([
           'data' => [
                   'title'=>'This is the title',
                  'body'=>'This is the message',
                  'myCustomVAlue' => 'value'
                   ]
           ]);

有关更多详细信息,请参阅gcm/fcm通知有效负载支持概念选项

获取通知响应

如果您想获取推送服务响应,可以调用getFeedback方法

    $push->getFeedback();

或者再次将其链式调用到上述方法

    $push->setMessage(['body'=>'This is the message','title'=>'This is the title'])
                        ->setApiKey('Server-API-Key')
                        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
                        ->send()
                        ->getFeedback();

它将返回一个包含响应的对象。

APN服务器反馈和包反馈

每次发送通知时,它都会检查APN服务器是否有关于您的证书的任何反馈。如果有,响应将合并到我们的反馈中,如下所示

class stdClass#21 (4) {
  public $success =>
  int(0)
  public $failure =>
  int(1)
  public $tokenFailList =>
  array(1) {
    [0] =>
    string(64) "c55741656e6c3185f3474291aebb5cf878b8719288e52bf4c497292b320312c5"
  }
  public $apnsFeedback =>
  array(1) {
    [0] =>
    class stdClass#16 (3) {
      public $timestamp =>
      int(1478272639)
      public $length =>
      int(32)
      public $devtoken =>
      string(64) "c55741656e6c3185f3474291aebb5cf878b8719288e52bf4c497292b320312c5"
    }
  }
}

获取未注册设备令牌

发送通知后,您可以检索未注册令牌的列表

$push->getUnregisteredDeviceTokens();

此方法返回来自推送服务提供商的未注册令牌数组。如果没有未注册的令牌,它将返回一个空数组。

Laravel别名外观

注册此包的别名外观后,您可以像以下这样使用它

PushNotification::setService('fcm')
                        ->setMessage([
                             'notification' => [
                                     'title'=>'This is the title',
                                     'body'=>'This is the message',
                                     'sound' => 'default'
                                     ],
                             'data' => [
                                     'extraPayLoad1' => 'value1',
                                     'extraPayLoad2' => 'value2'
                                     ]
                             ])
                        ->setApiKey('Server-API-Key')
                        ->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...])
                        ->send()
                        ->getFeedback();

它将返回发送的通知的推送反馈。

通知通道

格式化推送通知

如果通知支持作为推送消息发送,您应该在通知类上定义toApn和/或toFcm/toGcm方法。此方法将接收一个$notifiable实体,并应返回一个Edujugon\PushNotification\Messages\PushMessage实例

public function toApn($notifiable)
{
    return new PushMessage('Hello world');
}

自定义标题和正文

public function toApn($notifiable)
{
    return (new PushMessage)
        ->title('Hello world')
        ->body('...');
}

自定义通知声音

public function toApn($notifiable)
{
    return (new PushMessage)
        ->body('Hello world')
        ->sound('default');
}

自定义徽章数量

public function toApn($notifiable)
{
  return (new PushMessage)
        ->body('Hello world')
        ->sound('default')
        ->badge(7);
}

传递服务配置

public function toApn($notifiable)
{
    return (new PushMessage)
        ->body('Hello world')
        ->config(['dry_run' => false]);
}

将其添加到通知通道中

public function via($notifiable)
{
    return [ApnChannel::class];
}

别忘了在类顶部添加使用声明

路由推送通知

只需在实体上定义routeNotificationForApn和/或routeNotificationForFcm/routeNotificationForGcm方法即可

/**
 * Route notifications for the Apn channel.
 *
 * @return string|array
 */
public function routeNotificationForApn()
{
    return $this->ios_push_token;
}