我浏览了Github,但找不到任何相关的类或文档。
https://github.com/google/google-api-php-client-services/tree/master/src/Google/Service
我正在尝试将 FCM 消息从服务器发送到 Web 客户端。以下是我目前如何实现这一目标。
<?php
header('Content-Type: text/json');
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
)
)
);
$server_key = 'ya29.ElqKBGN2Ri_Uz...HnS_uNreA';
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = 'Authorization:key = '.$firebase_api_key."rn".'Content-Type: application/json'."rn".'Accept: application/json'."rn";
$registration_ids = array('bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...');
$fields = array('registration_ids' => $registration_ids, 'data' => $data);
$content = json_encode($fields);
$context = array('http' => array( 'method' => 'POST', 'header' => $headers, 'content' => $content));
$context = stream_context_create($context);
$response = file_get_contents($url, false, $context);
print($response);
但我希望有一个谷歌服务,为了将来的兼容性,我可以使用。请参阅下面的示例。
<?php
header('Content-Type: text/json');
require_once __DIR__.'/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$data = array(
'message' => array(
'notification' => array(
'title' => 'FCM Message',
'body' => 'This is an FCM Message',
),
'token': 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'
)
);
$fcm = new Google_Service_FirebaseCloudMessaging($client);
$response = $fcm->send($data);
print($response);
首先为您的服务帐号生成一个私钥文件:
-
在 Firebase 控制台中,打开设置>服务帐号(https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk(。
-
单击生成新私钥,然后单击生成密钥进行确认。
- 安全地存储包含密钥的 JSON 文件。
请参阅:https://firebase.google.com/docs/cloud-messaging/migrate-v1
通过作曲家安装 Google 客户端 PHP 源代码
$ composer require google/apiclient
现在使用 API
<?php
require __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/api-project-1234567-firebase-adminsdk-abcdefg.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$http_client = $client->authorize();
$message = [
'message' => [
'token' => 'dG****:****r9jM',
'notification' => [
'body' => 'This is an FCM notification message!',
'title' => 'FCM Message',
],
],
];
$project = 'api-project-1234567';
// Send the Push Notification - use $response to inspect success or errors
$response = $http_client->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
echo (string)$response->getBody() . PHP_EOL;
当然,您必须将令牌替换为接收方令牌,将凭据文件替换为您在第一步中下载的凭据文件,并将项目替换为您的项目 ID。
我在这里找到了解决方案:https://gist.github.com/Repox/64ac4b3582f8ac42a6a1b41667db7440
FCM 服务已于 2019-05-17 更新中新增
https://github.com/googleapis/google-api-php-client-services/commit/29cd38940096a3e973ad348d69101d1c2f1526d8#diff-dfabf19b00a6fe639dc70ab311952848