Recentemente, trabalhei com um projeto Phonegap para dispositivos Android utilizando notificações push. A ideia é simples. Precisamos usar o Push Notification Plugin para Android. Primeiro precisamos nos registrar no serviço Google Cloud Messaging para Android no console do Google, e só então poderemos enviar notificações push para nosso dispositivo Android.
O Push Notification Plugin fornece um exemplo simples para enviar notificações utilizando Ruby. Normalmente meu backend é feito com PHP (e às vezes Python), então, em vez de utilizar um script ruby, iremos criar um script simples em PHP para enviar as notificações push.
O script é muito simples:
<?php $apiKey = "myApiKey"; $regId = "device reg ID"; $pusher = new AndroidPusher\Pusher($apiKey); $pusher->notify($regId, "Hola"); print_r($pusher->getOutputAsArray());
E toda biblioteca pode ser vista abaixo:
<?php
namespace AndroidPusher;
class Pusher
{
const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
private $apiKey;
private $proxy;
private $output;
public function __construct($apiKey, $proxy = null)
{
$this->apiKey = $apiKey;
$this->proxy = $proxy;
}
/**
* @param string|array $regIds
* @param string $data
* @throws \Exception
*/
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
/**
* @return array
*/
public function getOutputAsArray()
{
return json_decode($this->output, true);
}
/**
* @return object
*/
public function getOutputAsObject()
{
return json_decode($this->output);
}
private function getHeaders()
{
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
private function getPostFields($regIds, $data)
{
$fields = [
'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
'data' => is_string($data) ? ['message' => $data] : $data,
];
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
}
Talvez possamos melhorar a biblioteca com um parser para o output do Google, basicamente porque precisamos manipular esse output para sabermos se o usuário desinstalou o aplicativo (e precisamos remover seu reg-id da nossa base de dados), mas pelo menos agora ela cobre todas as nossas necessidades. Você pode ver o código no Github.
***
Artigo traduzido pela Redação iMasters, com autorização do autor. Publicado originalmente em http://gonzalo123.com/2013/08/05/sending-android-push-notifications-from-php-to-phonegap-applications/




