Skip to content
Todo se AprendeAyuda y trucos para programación
  • Home
  • Categorías
    • Debian
    • JS
    • PHP
    • WordPress
    • MySql
    • Cordova

Send notification with FCM and PHP

24/01/2020 11 comments Article Cordova, PHP

Enviar una notificación desde PHP con FCM (Firebase Cloud Messaging)

Tengo una clase que se encarga de enviar los mensajes, no esta muy depurada pero funciona, incluso se podria crear una solo función.

 <?php
class NotifyGoogleFcm {

  // https://firebase.google.com/docs/cloud-messaging/http-server-ref
  // https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
  // https://github.com/fechanique/cordova-plugin-fcm
  // https://www.npmjs.com/package/cordova-plugin-fcm-notification

  private static $urlFcmGoogle = 'https://fcm.googleapis.com/fcm/send';
  private static $apiKey = '_YOUR_API_KEY_';
  private $header;
  private $notify = array();

  public $title;
  public $body;
  public $data = array(); // Si queremos pasar datos a la app, no solo notificarlo
  public $color = '#22c08a';
  public $sound = 'default';
  public $icon;

  // Se envia a todos los dispositivos, pero si pasamos un unico token se envia solo a ese dispositivo
  // Si un usuario se ha subscrito a un topico (/topics/PHP) podemos enviar solo a esas personas
  // ej: $this->to = "dtbjlnBC3Os:APA91bEHzYAdwZrCOvrMc5ottIbX6mygHi2N5UKg-_fdzsf63U_Ste";
  public $to = '/topics/all';
  // Si queremos enviar a mas de uno el mismo mensaje
  // ej:  $this->registration_ids = array("dtbjlnBC3Os:APA91bEHzYAdwZrCOvrMc5ottIbX6m","dfuTx5jdD0w:APA91bFfDkzY0ntMOt-ddORc9DZ_");
  public $registrationIds = array();

  function __construct(){
    $this->header = array (
      'Authorization: key= '.self::$apiKey,
      'Content-Type: application/json'
    );

    $this->notify = array(
      'priority' => 'high'
      ,'restricted_package_name' => ''
    );
  }

  public function sendNotify(){

    $this->notify = array(
      'notification' => array(
        'title' => $this->title,
        'body' => $this->body,
        'color' => $this->color,
        'sound' => $this->sound,
        'click_action' => 'FCM_PLUGIN_ACTIVITY',
      )
    );

    // Check variables
    if(!empty($this->icon))
      $this->notify['notification']['icon'] = $this->icon;

    if(is_array($this->data) && count($this->data) > 0)
      $this->notify['data'] = $this->data;

    if(is_array($this->registrationIds) && count($this->registrationIds) > 0):
      $this->notify['registration_ids'] = $this->registrationIds;
    else:
      $this->notify['to'] = $this->to;
    endif;

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, self::$urlFcmGoogle);
    curl_setopt($ch,CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_HTTPHEADER, $this->header);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($this->notify));

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
  }
}
?> 

Como utilizarla, con esto enviamos una notificación a todos los usuarios

$clNotify = new NotifyGoogleFcm();
$clNotify->title = 'Titulo para la notificación';
$clNotify->body = 'El mensaje que se le quiere indicar al usuario';
$clNotify->sendNotify();

Enviar a un solo usuario

$clNotify = new NotifyGoogleFcm();
$clNotify->to = "dtbjlnBC3Os:APA91bEHzYAdwZrCOvrMc5ottIbX6my..............";
$clNotify->title = 'Titulo para la notificación';
$clNotify->body = 'El mensaje que se le quiere indicar al usuario';
$clNotify->sendNotify(); 

Enviar a varios usuario sabiendo el token

$clNotify = new NotifyGoogleFcm();
$clNotify->registrationIds = array("dtbjlnBC3Os:APA91bEHzYAdwZrCOvrMc5....","dfuTx5jdD0w:APA91bFfDkzY0ntMOt......");
$clNotify->title = 'Titulo para la notificación';
$clNotify->body = 'El mensaje que se le quiere indicar al usuario';
$clNotify->sendNotify();

Me he basado en el código publicado en Stackoverflow

En la parte de Android, estoy utilizando Cordova con el plugin cordova-plugin-fcm-notification

Una vez instalado el plugin, como utilizarlo.

/**
 Wait for device API libraries to load
 */
 document.addEventListener("deviceready", onDeviceReady, false); 

/**
 Device APIs are available
 */
 function onDeviceReady() {
  FCMPlugin.getToken(function(token){
   console.log('getToken');
   console.log(token);
   // function to save token on DB (MySql, SqlServer, etc…)
  });
  FCMPlugin.onTokenRefresh(function(token){
   console.log('onTokenRefresh');
   console.log(token);
   // function to save token on DB (MySql, SqlServer, etc…)
  });
  FCMPlugin.onNotification(function(data){
   if(data.wasTapped){
    //Notification was received on device tray and tapped by the user.
    console.log(data);
   }else{
    //Notification was received in foreground. Maybe the user needs to be notified.
    console.log(data);
   }
  });
 } 
5 1 vote
Article Rating
Tags: android, cordova, cordova-plugin-fcm-notification, fcm, firebase, php, send notification
Subscribe
Notify of
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Best SEO Company
30/01/2020 01:59

Awesome post! Keep up the great work! 🙂

-1
Reply
AffiliateLabz
15/02/2020 21:43

Great content! Super high-quality! Keep it up! 🙂

-1
Reply
Raizel
21/01/2021 02:31

no puedo instalar el plugin cordova-plugin-fcm-notification me da error plugin.xml para cordova no se encuentra

0
Reply
Marius P
Author
Reply to  Raizel
22/01/2021 09:40

Hola, prueba con este cordova-plugin-fcm-with-dependecy-updated, ya que el otro por lo visto ya no se mantiene.

0
Reply
Raizel
Reply to  Marius P
26/01/2021 04:14

gracias muy buen post la verdad me sirvió, luche con algunos problemas pero al final me dio

0
Reply
Raizel
27/01/2021 04:15

amigo otra pregunta, de casualidad sabes como activar el conteo de las notificaciones sobre el icono de la app ?, hay q activar alguna propiedad del plugin fcm para eso ?

0
Reply
Marius P
Author
Reply to  Raizel
08/02/2021 09:57

Hola, siento en responder, como no he tenido la necesidad de utilizarlo no se muy bien como funciona, pero he encontrado lo siguiente:
En el plugin hay una pull en github para eso: https://github.com/fechanique/cordova-plugin-fcm/pull/136 pero me parece que no se ha fusionado.
Si no veo que hay un plugin para eso: https://github.com/katzer/cordova-plugin-badge

Espero que te sirva.
Saludos

0
Reply
Raizel
Reply to  Marius P
08/02/2021 20:38

gracias, lo mirare, tengo una pregunta, sabes por que las notificaciones no suenan en algunos dispositivos ? o es solo cosa de los xiaomi ?

0
Reply
Marius P
Author
Reply to  Raizel
22/02/2021 09:39

Hola Raizel,
La verdad que yo en todo los dispositivos que he probado han sonado, por lo que no te podria ayudar en este caso.
Podrías mirar a nivel de notificaciones en los ajuste del Xiaomi ver si la app que has creado tiene asignado algun sonido.

Saludos

0
Reply
sergio
19/06/2021 03:16

Buenas tardes tienes algún correo en donde te pueda contactar megustaria cotizar un proyecto

0
Reply
Marius P
Author
Reply to  sergio
25/06/2021 09:08

Hola Sergio, ya te he enviado un correo a la dirección de email que has indicado al publicar el comentario.
Saludos

0
Reply

Entradas recientes

  • Bash mysql dump database
  • Minificar CSS y Javascript con PHP
  • Tabla SQL población España
  • Validar DNI (NIF), CIF, NIE
  • Table tr collapsible Jquery

Categorías

  • Cordova
  • Debian
  • JS
  • MySql
  • PHP
  • Sin categoría
  • WordPress

Archivos

Copyright Todo se Aprende 2022 | Theme by ThemeinProgress | Proudly powered by WordPress

wpDiscuz
Utilizamos cookies para asegurar que damos la mejor experiencia al usuario en nuestro sitio web. Si continúa utilizando este sitio asumiremos que está de acuerdo.Estoy de acuerdoLeer más