phppush-notificationgoogle-cloud-messaging

Problem with Firebase push notification using php


I want to send push notifications using PHP, but I am getting this error. { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } }

Here is my PHP code:-

  <?PHP

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the form data
$topic = $_POST['topic'];
$title = $_POST['title'];
$body = $_POST['body'];
$imageURL = $_POST['image_url'];

// Validate the data (you may want to add more robust validation)
if (empty($topic) || empty($title) || empty($body)) {
    die('Error: All fields are required.');
}

// Your Firebase project's server key
$serverKey = 'my key';

// FCM endpoint
$url = 'https://fcm.googleapis.com/v1/projects/myprojectid/messages:send';

// Message data
$message = [
    'message' => [
        'topic' => $topic,
        'notification' => [
            'title' => $title,
            'body' => $body,
        ],
    ],
];

// Check if an image URL is provided
if (!empty($imageURL)) {
    $message['message']['data']['image_url'] = $imageURL;
}

// Headers
$headers = [
    'Authorization: Bearer ' . $serverKey,
    'Content-Type: application/json',
];

// Initialize cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session and get the response
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Print the response (for debugging purposes)
echo $response;
} else {
// If the request method is not POST, redirect or handle accordingly
header('Location: index.php');
exit();
}

?>

Solution

  • It looks like you're calling the v1 API with the good-old FCM server key. From looking at the upgrade guide's section on authorizing requests it seems like that is no longer supported on the new API:

    In place of the server key string used in legacy requests, HTTP v1 send requests require an OAuth 2.0 access token.

    So you will need to mint an OAuth 2 token and pass that into the Authorization instead.