我使用 firebase 完成了在 flutter android 部分中设置通知的过程,当我从面板发送通知时,它可以正常工作。
我想用 php 自动执行此操作。我尝试了互联网上的代码,但没有一个起作用。如果您能帮助我解决这个问题,我将非常高兴。
这里是代码。我想要所有设备
<?php
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='token';
$notification = [
"title" =>"title12",
"body" => "body of message.",
"alert" => "Test Push Message",
"sound" => "default",
];
$data = [
"title" => "This is notification title",
"body" =>"This is notification text",
"priority" => "high",
"content_available" => true
];
$fcmNotification = [
'to' => '/topics/alerts',
'notification' => $notification,
'data' => $data,
'priority' => 10
];
$headers = [
'Authorization: key= server_key',
'Content-Type: application/json'
];
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$cRequest = curl_init();
curl_setopt($cRequest, CURLOPT_URL, $fcmUrl);
curl_setopt($cRequest, CURLOPT_POST, true);
curl_setopt($cRequest, CURLOPT_HTTPHEADER, $headers);
curl_setopt($cRequest, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cRequest, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cRequest, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($cRequest);
curl_close($cRequest);
echo $result;
?>
对于 PHP,你应该遵循这个 - https://firebase-php.readthedocs.io/en/stable/cloud-messaging.html
一次发送多条消息 您可以一次性发送最多 500 条准备好的消息(每条消息都有一个令牌、主题或条件作为目标):
use Kreait\Firebase\Messaging\CloudMessage;
$messages = [
// Up to 500 items, either objects implementing Kreait\Firebase\Messaging\Message
// or arrays that can be used to create valid to Kreait\Firebase\Messaging\Cloudmessage instances
];
$message = CloudMessage::new(); // Any instance of Kreait\Messaging\Message
/** @var Kreait\Firebase\Messaging\MulticastSendReport $sendReport **/
$sendReport = $messaging->sendAll($messages);
通知示例
use Kreait\Firebase\Messaging\RawMessageFromArray;
$message = new RawMessageFromArray([
'notification' => [
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification
'title' => 'Notification title',
'body' => 'Notification body',
'image' => 'http://lorempixel.com/400/200/',
],
'data' => [
'key_1' => 'Value 1',
'key_2' => 'Value 2',
],
'android' => [
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidconfig
'ttl' => '3600s',
'priority' => 'normal',
'notification' => [
'title' => '$GOOG up 1.43% on the day',
'body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
'icon' => 'stock_ticker_update',
'color' => '#f45342',
],
],
'apns' => [
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig
'headers' => [
'apns-priority' => '10',
],
'payload' => [
'aps' => [
'alert' => [
'title' => '$GOOG up 1.43% on the day',
'body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
],
'badge' => 42,
],
],
],
'webpush' => [
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushconfig
'headers' => [
'Urgency' => 'normal',
],
'notification' => [
'title' => '$GOOG up 1.43% on the day',
'body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
'icon' => 'https://my-server/icon.png',
],
],
'fcm_options' => [
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#fcmoptions
'analytics_label' => 'some-analytics-label'
]
]);
$messaging->send($message);
验证消息
try {
$messaging->validate($message);
// or
$messaging->send($message, $validateOnly = true);
} catch (InvalidMessage $e) {
print_r($e->errors());
}
Send Push Notification via the new HTTP v1 API:
Install the below Repository:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Middleware;
use GuzzleHttp\Exception\ClientException;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Auth\Http\AuthenticatedRequest;
$DEVICE_TOKEN = 'XyZ';
$apiEndPoint = 'https://fcm.googleapis.com/v1/projects/my_project_id/messages:send';
$serverKey = FIREBASE_API_KEY ;
$serviceAccountFilePath = FCPATH."firebase_cloud/myproject-5fb21-firebase-adminsdk-gtjwk-105209f085.json";
if (!file_exists($serviceAccountFilePath)) {
die("Service account JSON file not found.");
}
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $serviceAccountFilePath);
$credentials = new ServiceAccountCredentials(
['https://www.googleapis.com/auth/cloud-platform'],
$serviceAccountFilePath
);
$accessToken = $credentials->fetchAuthToken();
$newAccessToken = $accessToken['access_token'];
$serverKey = FIREBASE_API_KEY;
$message = [
'message' => [
'token' => $DEVICE_TOKEN,
'notification' => [
'body' => 'This is an FCM notification message!',
'title' => 'FCM Message'
]
]
];
$json = json_encode($message);
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $newAccessToken,
'Accept: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiEndPoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$response = curl_exec($ch);
if(curl_errno($ch)) {
echo 'FCM request error: ' . curl_error($ch);
} else {
$decodedResponse = json_decode($response, true);
echo 'FCM response: ';
print_r($decodedResponse);
}
curl_close($ch);
}