edujugon/push-notification

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

v5.4.0 2024-04-05 15:05 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。

您可以在放弃之前指定客户端尝试连接 APN 的次数。默认次数为 3 次。您可以通过在 setConfig() 关联数组中指定 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 方法设置设备的 token,您通过参数作为数组传递 token 或如果只有一个则传递字符串。

语法

object setDevicesToken($deviceTokens)

send

send 方法发送通知。

语法

object send()

getFeedback

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

语法

object getFeedback()

getUnregisteredDeviceTokens

getUnregisteredDeviceTokens 方法获取无法接收通知的设备的 token,因为它们未注册到推送服务提供商。您可以使用它通过链式调用 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;
}