rodrigobertin
10/13/2015 - 2:38 PM

Enviar notificaciones push phonegap

Enviar notificaciones push phonegap

<?php 
/**
 * Class PushNotification
 * Enviar notificaciones push mediante php
 * requiere un formulario con lo datos
 */
class PushNotification
{
	public $apiKey; //api key de google

	/**
	 * Verificar que existe el api key de google
	 */
	public function PushNotification()
	{
		if (!isset($this->apiKey)) {
			echo '<script>alert("Definir un api key de google")</script>';
		}
	}

	/**
	 * Recorrer los registrados
	 * en el sistema y enviar
	 * las notificaciones
	 * @param $mensaje
	 */
	public function EnvioMasivo($tabla,$mensaje, $resumen, $titulo, $imagen)
	{
		$devicesReg = mysql_query("SELECT *  FROM $tabla ORDER BY id DESC ") or die(mysql_error());

		while ($row = mysql_fetch_assoc($devicesReg)) {
			self::Send($row['device_id'], $mensaje, $resumen, $titulo, $imagen);
		}
	}
	
	/**
	 * Enviando notificaciones push
	 * segun el RegID del dispositivo
	 * @param $RegDevice
	 * @param $message
	 */
	public function SendAndroid($RegDevice, $message, $resumen, $titulo, $imagen = '')
	{
		// variable post http://developer.android.com/google/gcm/http.html#auth
		$url = 'https://android.googleapis.com/gcm/send';


		if ($imagen == '') {
			//enviar notificacion sin imagen
			$fields = array(
				'registration_ids' => array($RegDevice),
				'data' => array(
					"message" => $message,
					"title" => $titulo,
					"vibrationPattern"=> [2000, 1000, 500, 500],
					"style" => "inbox",
					"summaryText" => $resumen,
					"ledColor" => [0, 0, 255, 0]
				),
			);

		} else {
			//enviar notificacion con imagen
			$fields = array(
				'registration_ids' => array($RegDevice),
				'data' => array(
					"message" => $message,
					"title" => $titulo,
					"style" => "picture",
					"vibrationPattern"=> [2000, 1000, 500, 500],
					"picture" => $imagen,
					"summaryText" => $resumen,
					"ledColor" => [0, 0, 255, 0]
				),
			);
		}


		$headers = array(
			'Authorization: key=' . $this->apiKey,
			'Content-Type: application/json'
		);
		// abriendo la conexion
		$ch = curl_init();

		// 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);

		// Deshabilitamos soporte de certificado SSL temporalmente
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

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

		// Cerramos la conexion
		curl_close($ch);
		echo $result;
	}
	
	private $appleApiUrl = 'ssl://gateway.sandbox.push.apple.com:2195';
  private $privateKey = 'ck.pem';
  private $privateKeyPassPhrase = 'YOUR-PRIVATE-KEY-PASSPHRASE-HERE';
  
	public function sendApple($deviceToken, $message)
    {
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', $this->privateKey);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $this->privateKeyPassPhrase);
        // Open a connection to the APNS server
        $fp = stream_socket_client(
            $this->appleApiUrl,
            $err,
            $errstr,
            60,
            STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
            $ctx);
        if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
        echo 'Connected to APNS' . PHP_EOL;
        // Create the payload body
        $body['aps'] = array(
            'alert' => $message,
            'sound' => 'default',
            'badge' => +1
        );
        // 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);
        return $result;
    }

}

?>