使用 Laravel 10 通过 Firebase Cloud Messaging API (V1) 发送以上 (2000) 多个设备令牌的通知

问题描述 投票:0回答:1

我使用云消息 API(旧版)发送通知,告知我可以将消息发送到每个 CURL 中的所有 1000 台设备。现在,当他们更新和使用 Firebase Cloud Messaging API (V1) 时,我无法逐个设备向设备发送令牌,如果我将它们放入 foreach 循环中,如果我增加我的额外时间,则将花费更长的时间,并且性能也会更高应用程序服务器(php 8.1 .0)。这让我担心安全方面。

另外:我删除了 firebase 控制台中的服务器密钥(旧版)。

服务: `

namespace App\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Firebase\JWT\JWT;

class FcmService
{
    protected $client;
    protected $url;
    protected $credentialsFilePath;

    public function __construct()
    {
        $this->client = new Client();
        $this->credentialsFilePath = public_path('xxxxxx.json');
        $this->url = 'https://fcm.googleapis.com/v1/projects/xxxx/messages:send';
    }

 public function sendMultiNotification(array $tokens, string $title, string $body)
{
    $responses = [];
    $batchSize = 500; // Maximum allowed tokens per request

    // Split tokens into batches
    foreach (array_chunk($tokens, $batchSize) as $tokenBatch) {
        $message = [
            'message' => [
                'tokens' => $tokenBatch, // Use 'tokens' for multiple device tokens
                'notification' => [
                    'title' => $title,
                    'body' => $body,
                ],
            ],
        ];

        try {
            $response = $this->client->post($this->url, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->generateAccessToken(),
                    'Content-Type' => 'application/json',
                ],
                'json' => $message,
            ]);

            // Log the response status and body
            \Log::info('FCM Response Status: ' . $response->getStatusCode());
            \Log::info('FCM Response Body: ' . $response->getBody());

            $responses[] = json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            \Log::error('FCM Error: ' . $e->getMessage());
            $responses[] = ['error' => $e->getMessage()];
        }
    }

    return $responses; // Return all responses for each batch
}

    protected function generateAccessToken()
    {
        $credentials = json_decode(file_get_contents($this->credentialsFilePath), true);
        $now = time();
        $payload = [
            'iss' => $credentials['client_email'],
            'sub' => $credentials['client_email'],
            'iat' => $now,
            'exp' => $now + 3600,
            'aud' => 'https://fcm.googleapis.com/',
        ];

        return JWT::encode($payload, $credentials['private_key'], 'RS256');
    }
}

----------::------------ 控制器:


namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\FcmService;
use Illuminate\Http\Request;

class FcmController1 extends Controller
{
    protected $fcmService;

    public function __construct(FcmService $fcmService)
    {
        $this->fcmService = $fcmService; // Assign the injected service to the class property
    }


    public function send(Request $request)
    {
        $tokens =['xxxxx',xxx2'];
$title = 'Your Notification Title';
$body = 'Your Notification Body';

$responses = $this->fcmService->sendMultiNotification($tokens, $title, $body);

        return response()->json($response);
    }
}

错误:

"error": "客户端错误:

POST https://fcm.googleapis.com/v1/projects/newbonuscard/messages:send
导致
400 Bad Request
响应: { “错误”: { “代码”:400, "message": "收到无效的 JSON 负载。'message' 处的未知名称 \"tokens\":Prot(已截断...) ”

php firebase firebase-cloud-messaging laravel-10
1个回答
0
投票

如果您正在寻找一种在 Laravel 中发送 Firebase Cloud Messaging (FCM) 推送通知的简单方法,我开发了一个名为 heyharpreetsingh/fcm 的包,可以简化该过程。它允许您高效地向移动设备(Android、iOS)和网络平台发送通知。

如何使用: 通过 Composer 安装软件包:

composer require heyharpreetsingh/fcm

在 bootstrap/providers.php (Laravel 11) 或 config/app.php (Laravel 10 及以下版本) 中注册服务提供者

Heyharpreetsingh\FCM\Providers\FCMServiceProvider::class,

通过在 Firebase 控制台中生成私钥并在 .env 文件中添加 JSON 文件的路径来设置 Firebase 凭证

FCM_GOOGLE_APPLICATION_CREDENTIALS=storage/ServiceAccount.json

向各个设备发送通知,如下所示:

use Heyharpreetsingh\FCM\Facades\FCMFacade;

FCMFacade::send([
   "message" => [
        "token" => "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", // Device token
        "notification" => [
            "body" => "This is an FCM notification message!",
            "title" => "FCM Message"
        ]
    ]
]);

本指南对您有帮助吗?请支持我的工作,留下👏鼓掌以表谢意。

© www.soinside.com 2019 - 2024. All rights reserved.