playable-cn/push-notification

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

v5.1.1 2023-10-27 08:55 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 方法设置设备的 tokens,您通过参数传递 token 作为数组或字符串(如果只有一个 token)。

语法

object setDevicesToken($deviceTokens)

send

send 方法发送通知。

语法

object send()

getFeedback

getFeedback 方法获取通知响应,您可以使用它将 send 方法链接起来或在任何发送通知之后调用它。

语法

object getFeedback()

getUnregisteredDeviceTokens

getUnregisteredDeviceTokens 方法用于获取无法接收通知的设备令牌,因为这些设备未注册到推送服务提供商。您可以将其与 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' => [
                'ext1' => 'value1',
                'ext2' => '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

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

或单独操作

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

voip 推送

$push->setMessage([
            'headers' => [
                'apns-push-type' => 'voip',
                'apns-expiration' => 0,
                'apns-topic' => 'your.app.bundleid.voip',
            ],
            'ext' => 'json_encode_string'
        ])
    ->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' => [
               'ext1' => 'value1',
               'ext2' => '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' => [
                   'ext1' => 'value1',
                   'ext2' => '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' => [
                                     'ext1' => 'value1',
                                     'ext2' => '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;
}