Send notification with FCM and PHP

Send notification with FCM and 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
Subscribe
Notify of
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Awesome post! Keep up the great work! 🙂

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

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

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

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 ?

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

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