如何在不使用控制台的情况下发送 Firebase 云消息通知?

当前位置: 剧情吧 > php教程>
电视猫时间: 2025-01-06 16:08:56

  如何在不使用控制台的情况下发送 Firebase 云消息通知?

要在不使用 Firebase 控制台的情况下发送 Firebase 云消息通知(Firebase Cloud Messaging, FCM),可以通过编程方式使用 Firebase 提供的 HTTP v1 API 或 Legacy HTTP API。这可以让您从服务器端或应用程序中发送通知。

以下是详细步骤:


1. 前置准备

1.1 创建 Firebase 项目

确保已经在 Firebase 控制台中创建了一个项目,并启用了 Firebase Cloud Messaging 服务。

1.2 获取服务器密钥

  1. 在 Firebase 控制台中导航到 项目设置 > 云消息传递
  2. 获取 服务器密钥(Legacy HTTP API Key)。
  3. 如果使用 HTTP v1 API,还需要下载 服务账号密钥文件

2. 使用 HTTP v1 API

2.1 服务账号密钥文件

  1. 在 Firebase 控制台,转到 项目设置 > 服务账户
  2. 下载 JSON 格式的服务账号密钥文件。

2.2 配置 HTTP 请求

使用 https://fcm.googleapis.com/v1/projects/{project-id}/messages:send 作为请求 URL。

示例代码(使用 PHP 和 cURL

function sendNotification($firebaseKeyFile, $deviceToken, $title, $body)
{
    // 加载服务账号密钥文件
    $key = json_decode(file_get_contents($firebaseKeyFile), true);

    // 获取访问令牌
    $jwtHeader = ['alg' => 'RS256', 'typ' => 'JWT'];
    $jwtPayload = [
        'iss' => $key['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'iat' => time(),
        'exp' => time() + 3600,
    ];
    $jwt = base64_encode(json_encode($jwtHeader)) . '.' . base64_encode(json_encode($jwtPayload));
    $signature = '';
    openssl_sign($jwt, $signature, file_get_contents($key['private_key']), OPENSSL_ALGO_SHA256);
    $jwt .= '.' . base64_encode($signature);

    // 获取访问令牌
    $response = json_decode(file_get_contents('https://oauth2.googleapis.com/token', false, stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/x-www-form-urlencoded',
            'content' => http_build_query([
                'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                'assertion' => $jwt,
            ]),
        ],
    ])), true);
    $accessToken = $response['access_token'];

    // 发送通知
    $url = 'https://fcm.googleapis.com/v1/projects/{project-id}/messages:send';
    $data = [
        'message' => [
            'token' => $deviceToken,
            'notification' => [
                'title' => $title,
                'body' => $body,
            ],
        ],
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

// 使用示例
$firebaseKeyFile = 'path/to/service-account-key.json';
$deviceToken = 'user-device-token';
$title = '测试通知';
$body = '这是一条测试通知内容';
$response = sendNotification($firebaseKeyFile, $deviceToken, $title, $body);
echo $response;

注意

  • 替换 {project-id} 为您的 Firebase 项目 ID。
  • deviceToken 是目标设备的 FCM 令牌。

3. 使用 Legacy HTTP API

如果您不需要高级功能,可以使用较简单的 Legacy HTTP API。

3.1 配置 HTTP 请求

  • URL: https://fcm.googleapis.com/fcm/send
  • 请求头:包含 AuthorizationContent-Type
  • 请求体:使用 JSON 格式指定消息。

示例代码(使用 PHP 和 cURL

function sendLegacyNotification($serverKey, $deviceToken, $title, $body)
{
    $url = 'https://fcm.googleapis.com/fcm/send';

    $data = [
        'to' => $deviceToken,
        'notification' => [
            'title' => $title,
            'body' => $body,
        ],
    ];

    $headers = [
        'Authorization: key=' . $serverKey,
        'Content-Type: application/json',
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

// 使用示例
$serverKey = '您的服务器密钥';
$deviceToken = '目标设备令牌';
$title = '测试通知';
$body = '这是一条测试通知内容';
$response = sendLegacyNotification($serverKey, $deviceToken, $title, $body);
echo $response;

4. 对比 HTTP v1 和 Legacy API

特性 HTTP v1 API Legacy HTTP API
安全性 使用 OAuth2 授权更安全 使用服务器密钥,安全性较低
功能 支持条件通知、多种消息类型等 功能有限,只适合简单场景
复杂度 配置稍复杂 简单,易于实现
推荐场景 高级消息发送和多条件过滤 快速实现通知发送或简单用例

总结

  1. 如果需要高级功能或更高安全性,建议使用 HTTP v1 API
  2. 如果仅需要快速实现简单的通知发送, Legacy HTTP API 是更简单的选择。
  3. 无论使用哪种方式,请确保服务器密钥或服务账号文件妥善保管,避免泄露。
    最新电视剧
    热门电视剧
    影视资讯
    最新剧情排行榜
    最新电视剧剧情