79260001

Date: 2024-12-07 05:09:21
Score: 0.5
Natty:
Report link

v1 API No longer works, you have to migrate to HTTP v1 https://firebase.google.com/docs/cloud-messaging/migrate-v1

Library Google Api Client https://github.com/googleapis/google-api-php-client/releases

Get JSON from Firebase "Manage Service Accounts".

Can check this code example:

require_once '/google-api-php-client/vendor/autoload.php';

function notification($notifications){
$serviceAccountPath = 'service-account-file.json';

// Your Firebase project ID
$projectId = 'xxxxxx';

// Example message payload
$message = [
   'token' => 'deviceToken',
       'notification' => [
          'title' => $title,
           'body' => $msg,
        ],
    ];

  $accessToken = getAccessToken($serviceAccountPath);
  $response = sendMessage($accessToken, $projectId, $message);
}

function getAccessToken($serviceAccountPath) {
    $client = new Client();
    $client->setAuthConfig($serviceAccountPath);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    $client->useApplicationDefaultCredentials();
    $token = $client->fetchAccessTokenWithAssertion();
    return $token['access_token'];
}

function sendMessage($accessToken, $projectId, $message) {
    $url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
    $response = curl_exec($ch);
    
    curl_close($ch);
    return $response;
}
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Ashraful Huq