Cannot recieve feedback from iOS Push Notification using PHP - php

I have set up a php file on my own server and used it to send push notifications. I have already tried it with two devices and it works well. The problem is with the feedback method which returns nothing. I have already tried everything and disabled firewall and so on. Note that i tested the feedback like this: I run the app on both devices. They both get the notification. then i delete the app on one of them and try again. Here is the PHP code i used:
<?php
$deviceToken1 = '.....';
$deviceToken2 = '.....';
$tokenArr = array($deviceToken1,$deviceToken2);
$passphrase = '.....';
$message = $_POST['message'];
$newsID = $_POST['newsID'];
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// 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)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
for($i = 0; $i < count($tokenArr); $i++)
{
$body['aps'] = array(
'alert' => $message,
'badge' => 1,
'sound' => 'sound.aiff',
'newsID' => $newsID);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $tokenArr[$i]) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
echo '<br/>'.date("Y-m-d H:i:s").' Message not delivered' . PHP_EOL;
}
else {
echo '<br/>'.date("Y-m-d H:i:s").' Message successfully delivered' . PHP_EOL;
}
}
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
$apns = stream_socket_client('ssl://feedback.sandbox.push.apple.com:2196', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
echo $apns;
if(!$apns)
{
echo '<br/>';
echo "Error $errcode : $errstr\n";
return;
}
else {
echo "APNS feedback results\n";
while ($devcon = fread($fp, 38))
{
$arr = unpack("H*", $devcon);
$rawhex = trim(implode("", $arr));
$feedbackTime = hexdec(substr($rawhex, 0, 8));
$feedbackDate = date('Y-m-d H:i', $feedbackTime);
$feedbackLen = hexdec(substr($rawhex, 8, 4));
$feedbackDeviceToken = substr($rawhex, 12, 64);
echo "TIMESTAMP:" . $feedbackDate . "\n";
echo "DEVICE ID:" . $feedbackDeviceToken. "\n\n";
}
}
?>

Related

How can I send bulk push in ios without using loop

Right now I use loop to send bulk points, I want to send bulk push in ios, how can I send this without using loop.
Here is my code:
function sendToBulkIphone($artistID,$type="artist") {
$deviceToken = $this->deviceToken;
$message = $this->message;
$postid = $this->postid;
$notificationtype = $this->NotificationType;
$time = $this->time;
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushkey/artist_'.$artistID.'/ck_user_production.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', '1234'); STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
$body['title']="Notification";
$body['message']=$message;
$body['postid']=$postid;
$body['NotificationType']=$notificationtype;
$body['time']=$time;
for($n=0;$n<count($deviceToken); $n++) {
// Build the binary notification
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken[$n]). pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));//, strlen($msg)
if (!$result) {
$jsondata['message'] = 'Message not delivered';
$jsondata['status'] = 0;
}
else {
$jsondata['message'] = 'Message successfully delivered';
$jsondata['status'] = 1;
}
}
fclose($fp);
return true;
}
Can anyone please tell me how can I resolve this issue ?
I'm sad to tell you but you can't.
As the Apple API only takes one token by one, you're forced to send each notification inside a loop.
See : https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html

Don't send notifications to multiple iOS in PHP

I can not send push messages to multiple iOS devices querying the database, it only sends it to the last record , I tried various solutions found in stackoverflow but it still fails in any , can anyone help me?
<form action="" method="post">
<label for="txtmensagem">Mensagem:</label>
<input type="text" name="txtmensagem" size="30"/>
<input type="submit" value="Enviar"/>
</form>
<?php
//conect with database
include_once('conexao.php');
$message = stripslashes(ucfirst($_POST['txtmensagem']));
// executa a query
$dados = mysql_query("SELECT * FROM token_push WHERE so='ios'");
$passphrase = 'XXXXX'; //pushchat
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'xx.pem');//xx.pem
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// 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 conect to APNS
//if (!$fp)
//exit("Falha na conexão: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
if (!empty($message)){
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'conteudo' => $conteudo,
'comando' => 'noticia',
'badge' => +1,
'idConteudo' => mysql_insert_id(),
);
// Encode the payload as JSON
$payload = json_encode($body);
//insert token in array
while ($row = mysql_fetch_array($dados)) {
$deviceToken = array();
$deviceToken[] = $row['token'];
}
foreach($deviceToken as $device){
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $device) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
}
}
//return if send or not
if (!$result)
echo 'Ops!' . PHP_EOL;
else
echo 'Aehoooooo!' . PHP_EOL;
// Close the connection to the server
fclose($fp);

ios push notification performance

This is my php push notification code for ios below:
<?php
// Put your device token here (without spaces):
$deviceToken = "********************************************";
// Put your private key's passphrase here:
$passphrase = "********";
function pushIOSNotification($message)
{
GLOBAL $deviceToken;
GLOBAL $passphrase;
$ctx = stream_context_create();
$path = dirname(__FILE__).'/ck.pem';
//echo $path;
stream_context_set_option($ctx, 'ssl', 'local_cert', $path);
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// 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)
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'
);
// 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));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
}
This code is only for one device,
if I need send to everyone and support localization,
this code will be like these below.
foreach($deviceTokens as $deviceToken){
$deviceOS = "query this device os from memcache";
if($deviceOS == "ios")
{
$lang = "query this device langauge from memcache";
$message = $messageData[$lang];
pushIOSNotification($deviceToken,$message);
}
}
but I doubt this performance of this code,
because deviceTokens length is the number of all members.

About the apple Enhanced notification format

I use php to send push message to apns , i use "Enhanced notification format" to sent .. but i can not get the return" Codes in error-response packet" anyone can help me ?? here is my code
<?php
header("Content-Type: text/html; charset=UTF-8");
$deviceToken = "123";
$content = "testing";
if(isset($content))
{
$newContent=substr($content,0,30)."...";
$re_content=iconv("GB2312","UTF-8",$newContent);
$pass = 'Ladder';
$body = array("aps" => array("alert" => $re_content, "badge" => 1, "sound" => 'received5.caf'));
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'dev.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
//$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
stream_set_blocking ($fp, 0);
if (!$fp)
{
print "Failed to connect $err $errstrn";
return;
}
else
{
print "Connection OK\n<br/>";
}
$payload = json_encode($body);
$msg =
// new: Command "1"
chr(1)
// new: Identifier "1111"
. chr(1) . chr(1) . chr(1) . chr(1)
// new: Expiry "tomorrow"
. pack('N', time() + 86400)
// old
. chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
//print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
//checkAppleErrorResponse($fp);
echo 'Done\n';
fclose($fp);
echo $apple_error_response = fread($fp, 6);
/* return false;
exit(); */
}
?>
I call this function after fwrite and before close commands
function error_response($fp)
{
$read = array($fp);
$null = null;
$changedStreams = stream_select($read, $null, $null, 0, 1000000);
if ($changedStreams === false)
{
echo ("Error: Unabled to wait for a stream availability");
}
elseif ($changedStreams > 0)
{
$responseBinary = fread($fp, 6);
if ($responseBinary !== false || strlen($responseBinary) == 6)
{
$response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
var_dump($response);
}
}
}
It works when I sending a notification in the enhanced format. But doesn't work with notification in the simple format. I don't have idea why... Any clue?

Android can use like apple push-notification with php?

i use php to post to apple ..
$message = $error_msg;
$deviceToken = $dtoken;
$badge = 1;
$sound = 'received3.caf';
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '/home/administrator/applecert/apns-dev.pem');
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
error_reporting(E_ALL);
if (!$fp) {
print "Failed to connect $err $errstr\n";
return;
} else {
print "Connection OK\n";
}
$payload = json_encode($body);
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
fclose($fp);
and andriod have similar way to post with php?
thanks ,all
Take a look at the C2DM service google offers :
http://code.google.com/intl/fr-FR/android/c2dm/
This code is well tested.
Note : You need to remember 3 points to check.
Passphrase : confirm with IOS developer.
.PEM : Please verify with your IOS develoepr created '.PEM' file is for sandbox or live server.
PORT 2195 : Need to verify whether this port has opened or not on your server.
If you have done these 3 steps, Now you can send push notification with below code with few configuration changes.
function pushNotification($deviceToken, $msg, $sounds, $type) {
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '');
// Put your private key's passphrase here:
$passphrase = ;
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
$body['aps'] = array(
'alert' => $msg,
'sound' => $sounds,
'badge' => 1,
'type' => $type,
);
$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));
// print_r($result);
fclose($fp);
}

Categories