纳兰诺木拉/notificationapi

用于与Laravel通道一起使用 notificationapi.com 的包

1.0 2024-02-15 02:13 UTC

This package is auto-updated.

Last update: 2024-09-16 02:50:54 UTC


README

Laravel的通知API

创建用于在Laravel项目中使用 notification-api 服务的包(https://www.notificationapi.com/

通知API的官方文档:https://docs.notificationapi.com/

安装

要在项目中获取最新版本的 notificationapi-laravel,请在 "composer" 中要求它

$ composer require nairanomura/notificationapi-laravel

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

{
    "require": {
        "nairanomura/notificationapi-laravel": "1.0"
    }
}

配置

直接在应用程序配置文件 config/app.php 中注册提供者

'providers' => [
	// ...
	
	NairanOmura\NotificationApi\NotificationApiServiceProvider::class,
]

提供者将自动在 config/services.php 中添加以下行。

return [
   
    //...
    'notification-api' => [
        'key' => env('NOTIFICATION_API_KEY'),
        'secret' => env('NOTIFICATION_API_SECRET'),
    ]
];

因此,请将以下环境变量添加到 .env 文件中以完成配置

#.env
NOTIFICATION_API_KEY=clientID
NOTIFICATION_API_SECRET=clientSecret

这些密钥是在注册账户后由通知API提供的

使用

使用Artisan创建通知

php artisan make:notification SomeNotification

在您的通知的 public function via($notifiable) 方法中返回 [notification-api]

public function via($notifiable)
{
    return ['notification-api'];
}

将方法 public function toNotificationApi($notifiable) 添加到您的通知中

//...

public function toNotificationApi($notifiable) 
{
    return [
        "notificationId" => "notification_example",
        "user" => [
            "id" => $notifiable->getAttribute('id'),
            "email" => $notifiable->getAttribute('email'),
        ],
        "mergeTags" => [
            "userName" => auth()->user()->name,
            "clickAction" => config('app.env')."/example"
        ]
    ];
}

通知发送示例

注意:要按用户模型调用通知,用户模型必须具有 "Notifiable" 特性

    class User extends Authenticatable
    {
        use Notifiable;
        //...
#notify one user
$user->notify((new SomeNotification(..)));

#notify multiple users
Notification::send($users, new SomeNotification(..);

额外:助手

安装和配置后,我们可以通过调用助手 notification_api 或类 NotificationApiService 来使用库

示例

$data = [
  "notificationId" => "order_tracking",
  "user" => [
    "id" => "example@mail.com",
    "email" => "example@mail.com",
    "number" => "+15005550006"
  ],
  "mergeTags" => [
    "item" => "Krabby Patty Burger",
    "address" => "124 Conch Street",
    "orderId" => "1234567890"
  ]
];

$result = notification_api($data);
#or
$result = (new NotificationApiService)->send($data)