How to build a simple APNS server with PHP?

-2

I'm creating a small notification firing service.

I made this code, to make several shots of pushs, where devicetokens comes from a server.  But I'm encountering the following problem:

When I directly assign a token in the $deviceToken array, push normally arrives on the smartphone.

When the token comes from the server, the successful delivery message appears, but the push does not reach the smartphone.

Code:

<?php

include "conexao.php";

$sql="SELECT 'devicetoken' FROM 'devicetokensios'  ORDER BY 'index'";

$resultado = mysql_query($sql) or die ("Erro .:" . mysql_error());

$deviceToken = array();


// Passando tokens para o array
  while($r = mysql_fetch_assoc($resultado))
{
     $deviceToken [] = $r['devicetoken'];


}

// Coloque sua senha do certificado aqui:
$passphrase = '';

// Coloque sua mensagem aqui:
$message = 'Teste de novas mensagens!!!';

////////////////////////////////////////////////////////////////////////////////


$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'dev30.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Abre uma conexão com o servidor APNS
$fp = stream_socket_client(
    'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp)
    exit("Falha para conectar: $err $errstr" . PHP_EOL);

echo 'Conectado a APNS' . PHP_EOL;

// Cria o corpo do payload
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
    );

// Codifica o payload como JSON
$payload = json_encode($body);

// Looping Principal de Envio
for($idx = 0; $idx< count($deviceToken);$idx++){

// Construindo o binário da notificação
$msg = chr(0).pack('n', 32).pack('H*',$deviceToken[$idx]).pack('n', strlen($payload)).$payload;


// Enviando para o servidor
$result = fwrite($fp, $msg, strlen($msg));

if (!$result)
    echo 'Mensagem não enviada' . PHP_EOL;
else
    echo 'Mensagem enviada com sucesso.  ||  ' . PHP_EOL;

// tempo para intervalo entre mensagens
usleep(1000000); 
}

// Fecha conexão com os servidores
mysql_close();
fclose($fp);

?>

On the server the devicetoken column has the following settings:

  

char (64), utf8_general_ci

An important note, when I manually put multiple devices (in this case several times) in the array, I am able to loop through the send and send several times. But the intention is to be for several different.

    
asked by anonymous 15.11.2014 / 03:27

1 answer

0

I noticed that there was a loss of the last digits of devicetokens on the server due to the length of the string, so I adjusted the column to a new data length and re-inserted the device token on the server.  After testing using the database as the source of the tokens I could see that it was solved.

I was able to resolve the problem by setting the server to the following settings:

  

varchar (64), utf8_bin

    
16.11.2014 / 03:07