Sending Multiple Iphone Push Notifications + Apns + PHP

Sending multiple iPhone push notifications + APNS + PHP

This is the way I have done it finally

  1. Downloaded apns-php
  2. PHP Code



    set_time_limit(0);
$root_path = "add your root path here";
require_once($root_path."webroot\cron\library\config.php");
require_once($root_path."Vendor\ApnsPHP\Autoload.php");

global $obj_basic;
// Basic settings

$timezone = new DateTimeZone('America/New_York');
$date = new DateTime();
$date->setTimezone($timezone);
$time = $date->format('H:i:s');


//Get notifications data to send push notifications
$queueQuery = " SELECT `notifications`.*, `messages`.`mes_message`, `messages`.`user_id`, `messages`.`mes_originated_from` FROM `notifications`
INNER JOIN `messages`
ON `notifications`.`message_id` = `messages`.`mes_id`

WHERE `notifications`.`created` <= NOW()";

$queueData = $obj_basic->get_query_data($queueQuery);

if(!empty($queueData)) {

// Put your private key's passphrase here:
$passphrase = 'Push';

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'server_certificates_bundle_sandbox.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 '<br>'.date("Y-m-d H:i:s").' Connected to APNS' . PHP_EOL;

foreach($queueData as $val) {
// Put your device token here (without spaces):
$deviceToken = $val['device_token'];

// Create message

// Get senders name
$sql = "SELECT `name` FROM `users` WHERE id =".$val['user_id'];
$name = $obj_basic->get_query_data($sql);
$name = $name[0]['name'];
$message = $name." : ";

// Get total unread messaged for receiver
$query = "SELECT COUNT(*) as count FROM `messages` WHERE mes_parent = 0 AND user_id = ".$val['user_id']." AND mes_readstatus_doc != 0 AND mes_status = 1";
$totalUnread = $obj_basic->get_query_data($query);
$totalUnread = $totalUnread[0]['count'];



$message .= " This is a test message.";


// Create the payload body
$body['aps'] = array(
'alert' => $message,
'badge' => $totalUnread,
'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 '<br>'.date("Y-m-d H:i:s").' Message not delivered' . PHP_EOL;
} else {
$sqlDelete = "DELETE FROM `notifications` WHERE id = ".$val['id'];
$query_delete = $obj_basic->run_query($sqlDelete,'DELETE');

echo '<br>'.date("Y-m-d H:i:s").' Message successfully delivered' . PHP_EOL;
}
}
// Close the connection to the server
fclose($fp);
echo '<br>'.date("Y-m-d H:i:s").' Connection closed to APNS' . PHP_EOL;
} else {
echo '<br>'.date("Y-m-d H:i:s").' Queue is empty!';
}

iOS Multiple push notifications using php code does not send to all devices

After many efforts i found what was going wrong. The one token which is old or expired i was talking about in my question is the token generated by development APNs certificates (may be during development the distribution url got called and development token got saved in server), all other tokens are generated from distribution certificates. So if you send one development token in between distribution tokens the apple server shuts the connection with our server, and other tokens which are after that development token do not get processed. Never mix development and distribution tokens. Thank You.

How can I send push notification to multiple devices in one go in iPhone?

Bottom line, you can't. You need to send a message to each token.

Its not working like a email where you can have multiple recipients.

Once the connection is open you can send a bunch of messages, thats also the preferred way (based on Apples SDK).

from the SDK:

http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW2

You should also retain connections with APNs across multiple notifications. APNs may consider connections that are rapidly and repeatedly established and torn down as a denial-of-service attack. Upon error, APNs closes the connection on which the error occurred.

Using PHP to send iOS Push Notifications via APNs

Try using this php script , make sure that the .pem certificate exits in same path as that php script when you run it , also get a correct device token

 <?php
/* We are using the sandbox version of the APNS for development. For production
environments, change this to ssl://gateway.push.apple.com:2195 */
$apnsServer = 'ssl://gateway.sandbox.push.apple.com:2195';
/* Make sure this is set to the password that you set for your private key
when you exported it to the .pem file using openssl on your OS X */
$privateKeyPassword = '1234';
/* Put your own message here if you want to */
$message = 'Welcome to iOS 7 Push Notifications';
/* Pur your device token here */
$deviceToken =
'05924634A8EB6B84437A1E8CE02E6BE6683DEC83FB38680A7DFD6A04C6CC586E';
/* Replace this with the name of the file that you have placed by your PHP
script file, containing your private key and certificate that you generated
earlier */
$pushCertAndKeyPemFile = 'PushCertificateAndKey.pem';
$stream = stream_context_create();
stream_context_set_option($stream,
'ssl',
'passphrase',
$privateKeyPassword);
stream_context_set_option($stream,
'ssl',
'local_cert',
$pushCertAndKeyPemFile);

$connectionTimeout = 20;
$connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
$connection = stream_socket_client($apnsServer,
$errorNumber,
$errorString,
$connectionTimeout,
$connectionType,
$stream);
if (!$connection){
echo "Failed to connect to the APNS server. Error no = $errorNumber<br/>";
exit;
} else {
echo "Successfully connected to the APNS. Processing...</br>";
}
$messageBody['aps'] = array('alert' => $message,
'sound' => 'default',
'badge' => 2,
);
$payload = json_encode($messageBody);
$notification = chr(0) .
pack('n', 32) .
pack('H*', $deviceToken) .
pack('n', strlen($payload)) .
$payload;
$wroteSuccessfully = fwrite($connection, $notification, strlen($notification));
if (!$wroteSuccessfully){
echo "Could not send the message<br/>";
}
else {
echo "Successfully sent the message<br/>";
}
fclose($connection);

?>

Is it possible to send iOS push notifications to two different apps?

I don't know how to do this in PHP, but you should simply create the payload body + binary notification before opening the first connection and then create 2 connections(or loop a connection, if possible) to Apple's Push Server and send the same binary notification to both of them.



Best regards,

Gabriel Tomitsuka

Send Push Notification to multiple tokens with PHP (iOS)


$deviceToken = ARRAY();
while ($row = mysql_fetch_array($query)) {
$deviceToken[] = $row["devicetoken"];
}

...

// or use ($devArray = $deviceToken;)

foreach($deviceToken as $token){
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $token)) . pack ("n",strlen($payload)) . $payload;


Related Topics



Leave a reply



Submit