mve / fcm-php
发送 Google Firebase Cloud 消息
Requires
- php: >=8.1
- psr/log: ^3.0
- symfony/http-client: ^6.3
Requires (Dev)
- mockery/mockery: ^1.6
- monolog/monolog: ^3.5
- phpunit/phpunit: ^10.4
README
使用 PHP 发送 Google Firebase Cloud 消息。
API 文档
查看 API 文档
准备
首先,请确保您有一个 Firebase 项目,并且已经下载了私钥 JSON 文件。有关更多信息,请参阅 https://firebase.google.com/docs/admin/setup。
每次调用 Google API 都必须使用从 Google API 获取的访问令牌进行身份验证。这些访问令牌在一小时后过期。这个库会从 Google API 获取访问令牌并缓存一小时,但它本身不实现缓存机制,而是期望调用者实现 Mve\FcmPhp\Models\CacheInterface
。
入门指南
使用 Messaging
类发送消息
$messaging = new Messaging(new MyCache(), '/path/to/file.json', Log::getLogger());
参数
- 如前所述的
Mve\FcmPhp\Models\CacheInterface
实例。 - Google Firebase 私钥 JSON 文件的路径。
- 可选的
Psr\Log\LoggerInterface
实现。如果您想查看请求和响应的日志,则需要此实现。
向设备发送消息
sendAll
方法使用 HTTP/2 多路复用。它非常快,可以用于发送一批通知。
// Create messages. The first argument is the ID - this can be used to map the result to the specific message after sending. $messages = [ new TokenMessage(1, 'token1', "Content of notification", "Title of notification"), new TokenMessage(2, 'token1', "Content of notification", "Title of notification") ]; // Send the messages try { $sendResult = $messaging->sendAll($messages); foreach ($sendResult->getSent() as $messageId => $firebaseId) { // Successfully sent messages } foreach ($sendResult->getUnregistered() as $messageId => $fcmError) { // The tokens for these messages can be deleted safely. } foreach ($sendResult->getErrors() as $messageId => $fcmError) { // See the $fcmError for specifics about this error. } } catch (\Mve\FcmPhp\Models\FcmException $ex) { // This is bad, but it's at least an error we got from the Google API die('Exception from the Google API: ' . $ex->fcmError->content); } catch (\Exception $ex) { // This is also bad, and it's a non Google API exception, maybe network error? die('Some other exception: ' . $ex->getMessage()); }
测试
首先确保环境变量 JSON_FILE
指向您的 Google Firebase 私钥 JSON 文件
export JSON_FILE="/path/to/file.json"
如果您想测试一个或多个有效的注册令牌,将其设置为 TOKENS
环境变量
export TOKENS="token1, token2"
如果您在测试期间想使用现有的访问令牌,您可以使用以下方式设置它
export ACCESS_TOKEN="my-access-token"
测试获取有效的访问令牌
这将测试从 Google API 获取访问令牌。
./vendor/bin/phpunit tests/AccessTokenHandlerTest.php
测试无效的注册令牌
这将测试一些无效的令牌。
./vendor/bin/phpunit tests/MessagingWithoutEnvTokenTest.php
测试有效的注册令牌
这将测试一个或多个有效的令牌。
仅在您设置了 TOKENS
环境变量时才有效。
./vendor/bin/phpunit tests/MessagingWithEnvTokenTest.php