rodrigobertin
1/19/2016 - 3:28 PM

Push notifications php all platforms

Push notifications php all platforms

/**
 * Class Notificaciones
 * Clases para el envio de notificaciones
 */
class Notificaciones
{

  // (Android)API access key from Google API's Console.
  private $API_ACCESS_KEY;
  // (Windows Phone 8) The name of our push channel.
  private $channelName;
  // (iOS) Private key's passphrase.
  private $certificadoPass; // password del .pem
  private $certificado; //archivo .pem

  /**
   * Notificaciones constructor.
   * Change the above three variables as per your app.
   * @param $google_api_key
   * @param $certificado
   * @param $wp8_channel
   */
  public function __construct($google_api_key, $certificadoIosPass, $certificadoIosFile, $wp8_channel)
  {
    //google
    $this->API_ACCESS_KEY = $google_api_key;

    //ios
    $this->certificadoPass = $certificadoIosPass;
    $this->certificado = $certificadoIosFile;

    //wp8
    $this->channelName = $wp8_channel;
  }

  /**
   *
   * CREATE TABLE appColectivos (
   * id        INT(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
   * deviceID  LONGTEXT, -- para android
   * ios_token LONGTEXT, -- para ios
   * wp8_uri   LONGTEXT, -- para wp8
   * uuid      VARCHAR(256)          DEFAULT NULL,
   * fecha     TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
   * ciudad    VARCHAR(256)          DEFAULT NULL,
   * modelo    VARCHAR(256) NOT NULL
   * );
   *
   */
  /**
   * Enviar a todos los dispositivos
   * registrados en la base de datos
   * @param $sql
   * @param $titulo
   * @param $mensaje
   * @return bool
   */
  public function SendAll($sql, $titulo, $mensaje, $imagen)
  {
    $devicesReg = mysql_query($sql) or die(mysql_error());

    if (mysql_num_rows($devicesReg) != 0) {
      while ($row = mysql_fetch_assoc($devicesReg)) {
        $android_reg_id = $row['deviceID'];
        $ios_token = $row['deviceID'];
        //para windows solo la url
        $wp8_uri = ($this->channelName);

        switch ($row['plataforma']) {
          case 'android':
          case 'Android':
            if ($android_reg_id != '') {
              self::Send_Android($titulo, $mensaje, $android_reg_id, $imagen);
            }
            break;

          case 'IOs':
          case 'Ios':
          case 'ios':
            if ($ios_token != '') {
              self::Send_iOS($titulo, $mensaje, $ios_token);
            }
            break;

          case 'wp8':
          case 'win32NT':
          case 'Win32NT':
            //echo 'windows<br>';
            self::Send_WP($titulo, $mensaje);
            break;
        }
      }
      return true;

    } else {
      echo '<script>alert("No se encontraron dispositivos registrados en la base")</script>';
      return false;
    }
  }

  /**
   * Enviar a todas las plataformas
   * @param $titulo
   * @param $mensaje
   * @param $android_reg_id
   * @param $ios_token
   * @param $wp8_uri
   */
  public function SendAllPlatforms($titulo, $mensaje, $android_reg_id, $ios_token, $wp8_uri)
  {
    self::Send_Android($titulo, $mensaje, $android_reg_id);
    self::Send_iOS($titulo, $mensaje, $ios_token);
    self::Send_WP($titulo, $mensaje, $wp8_uri);
  }

  /**
   * Sends Push notification for Android users
   * @param $titulo
   * @param $mensaje
   * @param $reg_id
   * @return mixed
   */
  public function Send_Android($titulo, $mensaje, $reg_id, $imagen = '', $post = false)
  {
    // variable post http://developer.android.com/google/gcm/http.html#auth
    $url = 'https://android.googleapis.com/gcm/send';
    if ($post == true) {
      $url = 'http://developer.android.com/google/gcm/http.html#project:' . $this->API_ACCESS_KEY;
    }

    if ($imagen == '') {
      //enviar notificacion sin imagen
      $fields = array(
       'registration_ids' => array($reg_id),
       'data' => array(
         //"icon"=> "img/icon.png",
        "icon" => "http://reclamos.eycon.com/img/icon.png",
        "message" => $mensaje,
        "title" => $titulo,
         //"style" => "inbox",
        "vibrationPattern" => "[2000, 1000, 500, 500]",
        "summaryText" => $titulo,
        "ledColor" => "[0, 0, 255, 100]"
       ),
      );

    } else {
      //enviar notificacion con imagen
      $fields = array(
       'registration_ids' => array($reg_id),
       'data' => array(
        "icon" => "http://reclamos.eycon.com/img/icon.png",
         //"icon"=> "img/icon.png",
        "message" => $mensaje,
        "title" => $titulo,
        "style" => "picture",
        "picture" => $imagen,
        "vibrationPattern" => "[2000, 1000, 500, 500]",
        "summaryText" => $titulo
         //"ledColor" => [0, 0, 255, 0]
       ),
      );
    }

    $headers = array(
     'Authorization: key=' . $this->API_ACCESS_KEY,
     'Content-Type: application/json'
    );

    return $this->useCurl($url, $headers, json_encode($fields));
  }

  /**
   * Sends Push's toast notification for Windows Phone 8 users
   * @param $titulo
   * @param $mensaje
   * @param $uri
   * @return array
   */
  public function Send_WP2($titulo, $mensaje)
  {
    $mensaje = strip_tags($mensaje);
    $mensaje = utf8_encode($mensaje);

    $titulo = strip_tags($titulo);
    $titulo = utf8_encode($titulo);

    $delay = 2;
    $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
     "<wp:Notification xmlns:wp=\"WPNotification\">" .
     "<wp:Toast>" .
     "<wp:Text1>" . ($titulo) . "</wp:Text1>" .
     "<wp:Text2>" . ($mensaje) . "</wp:Text2>" .
     "</wp:Toast>" .
     "</wp:Notification>";

    $sendedheaders = array(
     'Content-Type: text/xml',
     'Accept: application/*',
     'X-WindowsPhone-Target: toast',
     "Content-Length : " . strlen($msg),
     "X-NotificationClass: $delay"
    );

    //enviar
    $response = $this->useCurl($this->channelName, $sendedheaders, $msg);

    $result = array();
    foreach (explode("\n", $response) as $line) {
      $tab = explode(":", $line, 2);
      if (count($tab) == 2)
        $result[$tab[0]] = trim($tab[1]);
    }
    //echo '<pre>'.print_r($result).'</pre>'.'<hr>';
    return $result;
  }

  /**
   * Send para windows phone 2
   * @param $titulo
   * @param $mensaje
   */
  public function Send_WP($titulo, $mensaje)
  {
    $mensaje = strip_tags($mensaje);
    $mensaje = utf8_encode($mensaje);

    $titulo = strip_tags($titulo);
    $titulo = utf8_encode($titulo);

    // aquí va el código que envia wp8

    $toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
     "<wp:Notification xmlns:wp=\"WPNotification\">" .
     "<wp:Toast>" .
     "<wp:Text1>" . $titulo . "</wp:Text1>" .
     "<wp:Text2>" . $mensaje . "</wp:Text2>" .
     //"<wp:Param>?numero=" . $numero. "</wp:Param>" .
     "</wp:Toast> " .
     "</wp:Notification>";

    // Create request to send
    $r = curl_init();
    curl_setopt($r, CURLOPT_URL, $this->channelName);
    curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($r, CURLOPT_POST, true);
    @curl_setopt($r, CURLOPT_HEADER, true);

    // add headers
    $httpHeaders = array('Content-type: text/xml; charset=utf-8',
     'X-WindowsPhone-Target: toast',
     'Accept: application/*', 'X-NotificationClass: 2',
     'Content-Length:' . strlen($toastMessage));
    curl_setopt($r, CURLOPT_HTTPHEADER, $httpHeaders);

    // add message
    curl_setopt($r, CURLOPT_POSTFIELDS, $toastMessage);

    // execute request
    $output = curl_exec($r);

    // buscamos la respuesta
    $output = curl_getinfo($r, CURLINFO_HTTP_CODE);

    echo $output . '<hr>';
    curl_close($r);
  }

  /**
   * Sends Push notification for iOS users
   * @param $titulo
   * @param $mensaje
   * @param $devicetoken
   * @return string
   */
  public function Send_iOS($titulo, $mensaje, $devicetoken)
  {
    $deviceToken = $devicetoken;

    $ctx = stream_context_create();
    // ck.pem is your certificate file
    stream_context_set_option($ctx, 'ssl', 'local_cert', $this->certificado);
    stream_context_set_option($ctx, 'ssl', 'passphrase', $this->certificadoPass);

    // Open a connection to the APNS server
    $fp = stream_socket_client(
     'ssl://gateway.sandbox.push.apple.com:2195',
     $err,
     $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
     $ctx);

    if (!$fp) {
      echo '<hr>';
      exit("Failed to connect: $err $errstr" . PHP_EOL);
    }

    // Create the payload body
    $body['aps'] = array(
     'alert' => array(
      'title' => $titulo,
      'body' => $mensaje,
     ),
     'sound' => 'default'
    );

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));

    // Close the connection to the server
    fclose($fp);

    if (!$result)
      return 'Message not delivered' . PHP_EOL;
    else
      return 'Message successfully delivered' . PHP_EOL;

  }

  /**
   * Curl
   * @param $model
   * @param $url
   * @param $headers
   * @param null $fields
   * @return mixed
   */
  public function useCurl($url, $headers, $fields)
  {
    // Open connection
    $ch = curl_init();
    if ($url) {
      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      //curl_setopt($r, CURLOPT_URL,_URL_TO_SEND_TO_);
      //curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
      //url_setopt($r, CURLOPT_POST, true);
      //curl_setopt($ch, CURLOPT_HEADER, true);

      // Disabling SSL Certificate support temporarly
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

      // Execute post
      $result = curl_exec($ch);
      if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
      }

      // Close connection
      curl_close($ch);

      if (!$result) {
        echo '<- Error curl -><br>' . $result;
      } else {
        //echo '<script>window.sessionStorage.result=' . $result . '</script>';
      }
      echo '<pre>' . $result . '</pre>';
      //return $result;
    }
  }
}