我按照
中给定的示例使用下面的代码https://firebase.google.com/docs/cloud-messaging/migrate-v1
但是它不起作用,这是我的示例,按照 Laravel 框架,之前按照 POST 运行的相同代码
https://fcm.googleapis.com/fcm/send
$data_win = [
"registration_ids" => $data['win_firebaseToken'],
"notification" => [
"title" => $data['from_number'],
"body" => $value,
],
];
$dataString = json_encode($data_win);
$headers = [
"Authorization: Bearer " . $SERVER_API_KEY,
"Content-Type: application/json",
];
$ch = curl_init();
curl_setopt(
$ch,
CURLOPT_URL,
env('FIREBASE_TOKEN_ADDRESS')
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
$response_arr[] = $response;
所以请让我知道本节的待决内容,但我的旧代码如下
发布https://fcm.googleapis.com/fcm/send
它可以工作,但根据新的更改,从旧版 FCM API 迁移到 HTTP v1 不起作用
谢谢
您需要对请求格式和标头进行一些更改。
composer require google/auth
然后:
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
function getAccessToken()
{
$jsonKeyFilePath = storage_path('path/to/your-service-account-file.json');
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $jsonKeyFilePath);
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client(['handler' => $stack]);
$response = $client->get('https://www.googleapis.com/oauth2/v4/token');
$json = json_decode($response->getBody(), true);
return $json['access_token'];
}
更新端点和标头
use GuzzleHttp\Client;
function sendNotification($data, $value)
{
$accessToken = getAccessToken();
$headers = [
"Authorization" => "Bearer " . $accessToken,
"Content-Type" => "application/json",
];
$payload = [
"message" => [
"token" => $data['win_firebaseToken'],
"notification" => [
"title" => $data['from_number'],
"body" => $value,
],
],
];
$client = new Client();
try {
$response = $client->post(env('FIREBASE_TOKEN_ADDRESS'), [
'headers' => $headers,
'json' => $payload,
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
// Usage example
$data = [
'win_firebaseToken' => 'your_firebase_token',
'from_number' => 'Notification Title',
];
$value = 'Notification body message';
$response = sendNotification($data, $value);
print_r($response);