Keep receiving 403 when trying to send FCM notification from a PHP script
with Google API Client for PHP 7.4 library installed
Warning: file_get_contents(https://fcm.googleapis.com/v1/projects//messages:send): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in file_get_contents()
My code is
require_once libraries_get_path('google-api-php-client') . '/vendor/autoload.php';
$client = new Google_Client();
// see https://stackoverflow.com/questions/49782134/how-to-use-the-fcm-http-v1-api-with-php
try {
$client->setAuthConfig(libraries_get_path('google-api-php-client') .
'<service_account>/.json');
$client->addScope(Google_Service_FirebaseCloudMessaging::CLOUD_PLATFORM);
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
$accessToken = generateToken($client);
$client->setAccessToken($accessToken);
$accessToken = $accessToken["access_token"];
$device_token = <device_token>;
$payload = ["message" => ["token" => $device_token, "notification"=>["title" => 'test message', "body"=> 'message body']]];
$postdata = json_encode($payload);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "rnAuthorization: Bearer $accessToken",
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://fcm.googleapis.com/v1/projects/<project_id>/messages:send', false, $context);
} catch (Exception $e) {
watchdog('pilatesTestFCM exception', print_r($e, true));
}
return false;
where service_account.json contains
{
"type": "service_account",
"project_id": "",
"private_key_id": "...",
"private_key": "...",
"client_email": "...iam.gserviceaccount.com",
"client_id": "...",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-7mo9f%40pilates-studio-fdfc4.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
I”m dealing with a legacy Drupal 7.x site so bumping PHP up to 8 is not an option. Sofar my suspicion is that the Google API PHP 7.4 library is the problem.
Any ideas/suggestions will be highly appreciated.