📜  php中的web应用程序的firebase推送通知(1)

📅  最后修改于: 2023-12-03 15:18:33.876000             🧑  作者: Mango

PHP中的Web应用程序的Firebase推送通知

Firebase是Google提供的一种移动和Web应用程序的后备服务。它为开发人员提供了一种简单且易于使用的方式来将实时功能集成到应用程序中,包括实时数据库,身份验证和云存储。此外,Firebase提供了一种推送通知服务,可让您在向应用程序的用户推送消息时减少工作量。

准备工作

在开始使用Firebase推送通知之前,您需要进行一些准备工作。

Firebase帐户和项目

首先,您需要拥有Firebase帐户并在Firebase控制台中创建项目。创建项目后,您将能够从Firebase中获取必要的凭据和密钥,以便您的应用程序可以与Firebase交互。

Firebase Cloud Messaging API

您还需要了解Firebase Cloud Messaging(FCM)API,它是Firebase推送通知服务的基础。您可以通过该API向设备发送消息,并管理消息的传递。在使用FCM API时,您需要使用适当的安全机制,例如HTTPS或适当的TLS握手。

Firebase Admin SDK

最后,您需要使用Firebase Admin SDK。该SDK是要在Web服务器上运行的服务帐户密钥,它允许您从后端代码中直接调用FCM API,而不需要与每个用户的设备进行交互。

使用PHP向Firebase发送推送通知

以下是向Firebase发送推送通知的基本步骤。

步骤1:获取Firebase Admin SDK

首先,您需要从Firebase控制台中获取服务帐户密钥文件,该文件包含您需要使用的秘密和凭据。

要在您的PHP项目中使用Firebase Admin SDK,您必须安装Firebase PHP库,该库提供了与Firebase交互所需的所有功能。

在终端中使用以下命令可以安装Firebase PHP库:

composer require kreait/firebase-php
步骤2:配置Firebase Admin SDK

在安装Firebase PHP库后,您需要配置Firebase Admin SDK以使用您的凭据。在PHP文件的顶部中添加以下代码即可:

//引入Firebase PHP库
require_once __DIR__.'/vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

//将路径替换为您的服务账户密钥位置
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/serviceAccount.json');
$firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    ->create();

请注意,上面的代码需要您在服务帐户密钥文件的路径处提供正确的路径。

步骤3:发送推送通知

要发送推送通知,请使用以下代码和Firebase Admin SDK的Firebase Messaging组件:

//创建Firebase Messaging实例
$messaging = $firebase->getMessaging();

//设置推送通知有效载荷
$payload = [
    'title' => 'Title of Notification',
    'body' => 'This is a test notification'
];

//获取FCM设备标记或设备标识符数组
$deviceTokens = ['device_token_1', 'device_token_2'];

//创建消息实例
$message = \Kreait\Firebase\Messaging\MessageToDevices::withTarget('token',$deviceTokens)
->withNotification($payload['title'], $payload['body']);

//发送推送通知
$sendReport = $messaging->send($message);

在上面的代码中,$payload变量存储推送通知的有效载荷。设备标记存储在$deviceTokens变量中,您可以使用单个标记或标记数组向多个设备发送通知。

为了更好的演示说明,下面是一个完整的PHP代码片段,用于向指定主题的所有设备发送推送通知:

//引入Firebase PHP库
require_once __DIR__.'/vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

//将路径替换为您的服务账户密钥位置
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/serviceAccount.json');
$firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    ->create();

//创建Firebase Messaging实例
$messaging = $firebase->getMessaging();

//设置推送通知有效载荷
$payload = [
    'title' => 'Title of Notification',
    'body' => 'This is a test notification'
];

//创建主题
$topic = 'test_topic';

//创建消息实例
$message = \Kreait\Firebase\Messaging\MessageToTopic::create($topic)
    ->withNotification($payload['title'], $payload['body']);

//发送推送通知
$sendReport = $messaging->send($message);

//在控制台打印响应
echo json_encode($sendReport)."\n";
结论

Firebase提供了一种简单且易于使用的方式来在您的应用程序中集成推送通知服务。使用Firebase Admin SDK的Firebase Messaging组件,您可以轻松地向多个设备发送推送通知,并跟踪推送通知的传递。