这是一个辅助类,用于简化通过 Firebase Cloud Messaging 发送通知的过程。

1.0.2 2024-06-20 04:36 UTC

This package is auto-updated.

Last update: 2024-09-20 05:26:17 UTC


README

此包提供了使用 Guzzle HTTP 客户端轻松发送 Firebase Cloud Messaging (FCM) 通知的方式。

安装

首先,通过 Composer 安装此包

composer require wildanmzaki/fcm

使用方法

初始化

您需要提供 Firebase 服务账户凭据文件路径和项目 ID 以初始化 Client

use WildanMZaki\Fcm\Client;
use WildanMZaki\Fcm\Notification;

// Path to your Firebase service account credentials
$credentialsFilePath = storage_path('service-account.json');
$projectId = 'your-firebase-project-id';

// Initialize the client
$client = new Client($credentialsFilePath, $projectId);

向特定设备发送通知

您可以通过提供设备令牌来向特定设备发送通知。

// Create a notification
$notification = Notification::to('device-token')
    ->setTitle('Notification Title')
    ->setBody('Notification Body')
    ->setImage('https://example.com/image.png')
    ->setData(['key' => 'value']);

// Send the notification
$response = $client->send($notification);

// Print the response
print_r($response);

向主题发送通知

您可以通过提供主题名称来向主题发送通知。

// Create a notification
$notification = Notification::topic('your-topic')
    ->setTitle('Notification Title')
    ->setBody('Notification Body')
    ->setImage('https://example.com/image.png')
    ->setData(['key' => 'value']);

// Send the notification
$response = $client->send($notification);

// Print the response
print_r($response);

WildanMZaki\Fcm\Client

Client 类负责向 FCM API 发送通知。

__construct(string $credentialsFilePath, string $projectId, bool $isProduction = false)

  • $credentialsFilePath - Firebase 服务账户凭据文件路径。
  • $projectId - 您的 Firebase 项目 ID。
  • $isProduction - (可选) 如果为 true,客户端将初始化为生产使用。

send(Notification $notification)

  • notification - Notification 类的实例。
  • 返回来自 FCM API 的响应。

WildanMZaki\Fcm\Notification

Notification 类用于构建通知有效负载。

static to(string $token): self

  • $token - 要发送通知的设备令牌。
  • 返回 Notification 类的实例。

static topic(string $topic): self

  • $topic - 要发送通知的主题。
  • 返回 Notification 类的实例。

setTitle(string $title): self

  • $title - 通知的标题。
  • 返回当前 Notification 类的实例。

setBody(string $body): self

  • $body - 通知的主体。
  • 返回当前 Notification 类的实例。

setImage(string $image): self

  • $image - 包含在通知中的图片的 URL。
  • 返回当前 Notification 类的实例。

setData(array $data): self

  • $data - 要包含在通知中的附加数据关联数组。
  • 返回当前 Notification 类的实例。

build(): array

  • 构建通知有效负载。
  • 返回通知有效负载作为数组。

许可证

此包是开源软件,使用 MIT 许可证授权。