我查看了github,但找不到任何相关的类或文档。
https://github.com/google/google-api-php-client-services/tree/master/src/Google/Service
我正在尝试从服务器向Web客户端发送FCM消息。以下是我目前正在实现的目标。
<?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."\r\n".'Content-Type: application/json'."\r\n".'Accept: application/json'."\r\n";
$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);
但我希望有一个我可以使用的Google服务,以便将来兼容。见下面的例子。
<?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);
首先为您的服务帐户生成一个私钥文件:
见:https://firebase.google.com/docs/cloud-messaging/migrate-v1
通过composer安装Google Client 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