Hoy vamos a aprender cómo podemos enviar un mensaje al endpoint de Firebase Cloud Messaging usando PHP. (https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=es-419)

Para ello necesitamos el endpoint de Google:
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
Y previamente tenemos que generar un token en nuestra aplicación, para ello vamos a Firebase, seleccionamos nuestro proyecto y pulsamos en Configuración del Proyecto:

Aquí dentro buscamos Cloud Messaging

Ahora vamos a la seccion de API de Firebase Cloud Messaging (V1) y comprobamos que esté habilitada.

Ahora buscamos Cuentas de servicio

Y generamos una Nueva Clave Privada

Guardamos este JSON en la raíz del proyecto y creamos un archivo llamado send_push.php
-app.json -send_push.php
Y añadimos lo siguiente en send_push.php
function enviarMensajeCloud($tituloEnviar, $mensajeEnviar, $tokenEnviar) {
$accessToken = getAccessToken();
$projectId = getProjectId();
$url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";
$data = array(
'message' => array(
'token' => $tokenEnviar,
'notification' => array(
'title' => $tituloEnviar,
'body' => $mensajeEnviar,
),
'data' => array(
'key_1' => 'Value for key_1',
'key_2' => 'Value for key_2',
),
),
);
$payload = json_encode($data);
$headers = array(
'Content-type: application/json',
'Authorization: Bearer ' . $accessToken,
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
// Manejar la respuesta según tus necesidades
// Puedes imprimir el resultado para depuración
echo $result;
}
function getAccessToken() {
// Lee el contenido del archivo app.json
$filePath = __DIR__ . '/app.json';
if (!file_exists($filePath)) {
die('Error: No se encuentra el archivo app.json en ' . $filePath);
}
// Lee el contenido del archivo app.json
$jsonContent = file_get_contents($filePath);
if ($jsonContent === false) {
die('Error al leer el archivo app.json');
}
$jsonData = json_decode($jsonContent, true);
$privateKey = $jsonData['private_key'];
$clientId = $jsonData['client_id'];
$jwtHeader = base64_encode(json_encode(array("alg" => "RS256", "typ" => "JWT")));
$jwtClaimSet = base64_encode(json_encode(array(
"iss" => $clientId,
"scope" => "https://www.googleapis.com/auth/firebase.messaging",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => time() + 3600, // La validez del token es de 1 hora
"iat" => time(),
)));
$signature = '';
openssl_sign("$jwtHeader.$jwtClaimSet", $signature, $privateKey, OPENSSL_ALGO_SHA256);
$jwtSignature = base64_encode($signature);
$assertion = "$jwtHeader.$jwtClaimSet.$jwtSignature";
$url = "https://www.googleapis.com/oauth2/v4/token";
$data = array(
"grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion" => $assertion,
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);
return $responseData['access_token'];
}
function getProjectId() {
// Lee el contenido del archivo app.json
$filePath = __DIR__ . '/app.json';
if (!file_exists($filePath)) {
die('Error: No se encuentra el archivo app.json en ' . $filePath);
}
// Lee el contenido del archivo app.json
$jsonContent = file_get_contents($filePath);
if ($jsonContent === false) {
die('Error al leer el archivo app.json');
}
$jsonData = json_decode($jsonContent, true);
return $jsonData['project_id'];
}
// Usa esta función para enviar un mensaje
enviarMensajeCloud('Título del mensaje', 'Cuerpo del mensaje', 'token_del_dispositivo');
Recuerda añadir correctamente el nombre del proyecto en esta línea:
$jsonContent = file_get_contents('app.json');
Y lo mismo para ‘token_del_dispositivo’, tendrás que usar un Token de dispositivo válido aquí te explico cómo puedes obtenerlo: https://devcodelight.com/?p=7128

Ingeniero en Informática, Investigador, me encanta crear cosas o arreglarlas y darles una nueva vida. Escritor y poeta. Más de 20 APPs publicadas y un libro en Amazon.