Push Notifications for multiple Apps from one server - php

I am using RMSPushNotificationsBundle for handling push notifications. I am sending pushNotifications to multiple apps from one server. I am using setAPNSPemAsString method which pick right certificate. But push notification is sent only first time. Can anyone tell me why? Thank you!
public function sendIOS($appName){
$notifications = $this->container->get('rms_push_notifications');
$message = new iOSMessage();
$message->setMessage($this->message);
$message->setData($this->getData());
$message->setAPSSound("default");
$message->setDeviceIdentifier($this->pushToken);
if ($appName !="appName") {
$pemFile = $this->container->getParameter("rms_push_notifications.ios.".$appName.".pem");
$passphrase = $this->container->getParameter("rms_push_notifications.ios.".$appName.".passphrase");
$pemContent = file_get_contents($pemFile);
$notifications->setAPNSPemAsString($pemContent, $passphrase);
}
return $notifications->send($message);
}

I'm not sure what's the problem but following small code worked for me. At least you can use this to test connection to APNS server.
<?php
// your private key's passphrase
$passphrase = $_POST('passphrase');
$pemFilesPath = 'path/to/pem/folder/';
// path to pem file
$appCert = $_POST('pemfile');
$pemFile = $pemFilePath.$appCert;
$notifications = $_POST('notifications');
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $pemFile);
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;
$records = 0;
foreach ($notifications as $deviceToken => $message)
{
// 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;
if (!$fp) {
exit("Connection intruptted " . E_USER_ERROR . PHP_EOL);
}
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if(!$result) {
print_r("Failed writing to stream.", E_USER_ERROR);
fclose($fp);
die;
}
/* uncomment this part for troubleshooting
else {
$tv_sec = 1;
$tv_usec = null; // Timeout. 1 million micro seconds = 1 second
$read = array($fp); $we = null; // Temporaries. "Only variables can be passed as reference."
$numChanged = stream_select($read, $we, $we, $tv_sec, $tv_usec);
if(false===$numChanged) {
print_r("Failed selecting stream to read.", E_USER_ERROR);
fclose($fp);
die;
}
else if($numChanged>0) {
$command = ord(fread($fp, 1));
$status = ord(fread($fp, 1));
$identifier = implode('', unpack("N", fread($fp, 4)));
$statusDesc = array(
0 => 'No errors encountered',
1 => 'Processing error',
2 => 'Missing device token',
3 => 'Missing topic',
4 => 'Missing payload',
5 => 'Invalid token size',
6 => 'Invalid topic size',
7 => 'Invalid payload size',
8 => 'Invalid token',
255 => 'None (unknown)',
);
print_r("APNS responded with command($command) status($status) pid($identifier).", E_USER_NOTICE);
if($status>0) {
$desc = isset($statusDesc[$status])?$statusDesc[$status]: 'Unknown';
print_r("APNS responded with error for pid($identifier). status($status: $desc)", E_USER_ERROR);
// The socket has also been closed. Cause reopening in the loop outside.
fclose($fp);
die;
}
else {
// Apple docs state that it doesn't return anything on success though
$records++;
}
} else {
$records++;
}
}
*/
$records++;
}
echo "Send notifications to $records devices";
// Close the connection to the server
fclose($fp);
?>
Note: Wrote this small code long time ago and it worked fine. I don't remember the source now but there was a tutorial. Have not tested recently so you may need to revise it.
Some suggestions:
Open connection and write to the server all your notifications then close it.
Reading server response reduces functionality but is good for troubleshooting and for start. So use that part as needed.
Take a look at this documentation for more error explanation APNs Provider API

Related

PHP - APNs messages are delivered but not received on iOS device

I am using following code to send push notification to ios devices. I am getting successfully delivered message in php side but not receiving push in iOS device.
I have checked with replacing .pem files nd also tested with sendbox and production both. Its not working both. Please provide me the way of debugging this issue.
function iosTest($tToken)
{
// Provide the Host Information.
//$tHost = 'gateway.sandbox.push.apple.com';
$tHost = 'gateway.push.apple.com';
$tPort = 2195;
//echo "hi";
// Provide the Certificate and Key Data.
$tCert = $_SERVER['DOCUMENT_ROOT'].'/N****d.pem';
// Provide the Private Key Passphrase (alternatively you can keep this secrete
// and enter the key manually on the terminal -> remove relevant line from code).
// Replace XXXXX with your Passphrase
$tPassphrase = 'harsh';
// Provide the Device Identifier (Ensure that the Identifier does not have spaces in it).
// The message that is to appear on the dialog.
$tAlert = 'Testing..';
// The Badge Number for the Application Icon (integer >=0).
$tBadge = 1;
// Audible Notification Option.
$tSound = 'default';
// The content that is returned by the LiveCode "pushNotificationReceived" message.
$tPayload = 'APNS Message Handled by LiveCode';
// Create the message content that is to be sent to the device.
$tBody['aps'] = array (
'alert' => $tAlert,
'badge' => $tBadge,
'sound' => $tSound,
);
//$tBody ['payload'] = $tPayload;
// Encode the body to JSON.
$tBody = json_encode ($tBody);
echo $tBody;
// Create the Socket Stream.
$tContext = stream_context_create ();
stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert);
// Remove this line if you would like to enter the Private Key Passphrase manually.
stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase);
// Open the Connection to the APNS Server.
$tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext);
// Check if we were able to open a socket.
if (!$tSocket)
exit ("APNS Connection Failed: $error $errstr" . PHP_EOL);
// Build the Binary Notification.
$tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody;
// Send the Notification to the Server.
$tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg));
if ($tResult)
echo 'Delivered Message to APNS' . PHP_EOL;
else
echo 'Could not Deliver Message to APNS' . PHP_EOL;
// Close the Connection to the Server.
fclose ($tSocket);
//send_feedback_request();
}
Thanks in advance.
Kindly use the following code as it working on my end
<?php
// Put your device token here (without spaces):
$deviceToken = '17b2f31afd5c9736ad48ffca8d1936046431c6fc1f3f3ac661bcbfbf97ca60cc';
// Put your private key's passphrase here:
$passphrase = '';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'HireRightNew.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;
// Create the payload body
$body['aps'] = array(
'alert' => 'Breaking News',
'sound' => 'default',
'link_url' => $url,
'category' => 'NEWS_CATEGORY',
);
// 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);
?>

Sending high volumes of notifications

I need to send thousands (actually 10 000) push notifications at the same time, to do this, I checked StackOverflow and found those two questions:
Apple Push Notification: Sending high volumes of messages
Apple Push Notification: Sending high volumes of messages
And I implemented my push system using php:
// Create the payload body
$body['aps'] = [
'alert' => $notification->getMessage(),//$notification is just a notification model, where getMessage() returns the message I want to send as string
'sound' => 'default'
];
// Encode the payload as JSON
$payload = json_encode($body);
$fp = self::createSocket();
foreach($devices as $device) {
$token = $device->getToken();
$msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload;
if(!self::sendSSLMessage($fp, $msg)){
//$msg is a parameter of the method, it's the message as string
fclose($fp);
$fp = self::createSocket();
}else{
//Here I log "n notification sent" every 100 notifications
}
}
fclose($fp);
Here is the createSocket() method:
private static function createSocket(){
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', PUSH_IOS_CERTIFICAT_LOCATION);
stream_context_set_option($ctx, 'ssl', 'passphrase', PUSH_IOS_PARAPHRASE);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
stream_set_blocking ($fp, 0);
if (!$fp) {
FileLog::log("Ios failed to connect: $err $errstr");
}
return $fp;
}
And the sendSSLMessage() method:
private static function sendSSLMessage($fp, $msg, $tries = 0){
if($tries >= 10){
return false;
}
return fwrite($fp, $msg, strlen($msg)) ? self::sendSSLMessage($fp, $msg, $tries++) : true;
}
I'm not getting any error message from apple, everything looks fine except nobody is receiving the notification.
Before this, I was using a method creating one socket connection per message and closing it after sending the message, but it was way too slow so we decided to change it, so I know that it's not a client related issue.
You have to first crate $fp socket then pass it to sendSSLMessage
// initally create Socket here
$fp = self::createSocket();
foreach($devices as $device) {
$token = $device->getToken();
$msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload;
if(!self::sendSSLMessage($fp, $msg)){
fclose($fp);
$fp = self::createSocket();
}
}
fclose($fp);
UPDATE
// define in $body['aps'] message with sub array like this
$message = $notification->getMessage();
$body['aps'] = array(
'alert' => array(
'body' => $message,
),
'sound' => 'default',
);

iOS push notification not working using PHP

I am trying to implement push notification in iOS in PHP using APNS library. Here is my code :
<?php
// Put your device token here (without spaces):
$deviceToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// Put your private key's passphrase here:
$passphrase = 'XXXXXX';
// Put your alert message here:
$message = 'My first push notification!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'Certificates.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;
// 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));print_r($result);
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
It show message sending successfully but in iOS it does not show notification.
2015-07-28 08:32:39 Connected to APNS result = 97
2015-07-28 08:32:39 Message successfully delivered
2015-07-28 08:32:39 Connection closed to APNS
Why this is happening? Am I missing anything ?
his mistake is with the ios 9 if so stop using the code in objective C and use in swift as it has a bug in generating objectiv token - C for ios9.
I recommend urgent change your code.
Also through this thought was the server when the scheduled ios changed for swift everything was resolved and my php was almost equal.
Care:
$ msg = chr (0). pack ('N', 32). pack (H * ','. '$deviceToken [0].'). pack ('N', strlen ($ payload)). $ payload;
There are two potential reason that is causing this:
Your app is in foreground
Your device token is invalid
In my app. I am directly getting deviceToken that's in NSData
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *deviceTokenString = [NSString stringWithFormat:#"%#", deviceToken];
// this is producing something like:
// <xxxxxxx 9b0f527f xxxxxxxx 2727ed28 xxxxxxxx 4e693a61 xxxxxxx ac2f7dbb>
//
// and i am directly saving that to my servers database
Here's what i have in my server.
$from_database = "<xxxxxxx 9b0f527f xxxxxxxx 2727ed28 xxxxxxxx 4e693a61 xxxxxxx ac2f7dbb>";
// this removes the '<' and '>' to make the device token valid
//
$token_string = substr($from_database, 1, -1);
$token_array[] = $token_string;
// you can also add multiple 'token_string' to the 'token_array' for push notification broadcasting, i am currently doing that and it is working properly.
...
public function __push_notification($message_input, $token_array)
{
$message = stripslashes($message_input);
$passphrase = 'xxxxxx';
$cert = realpath('xxx.pem');
$payload = '{
"aps" :
{
"alert" : "'.$message.'",
"badge" : 1,
"sound" : "bingbong.aiff"
}
}';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $cert);
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)
{
// echo "Failed to connect $err $errstr <br>";
return;
}
else
// echo "Post notification sent<br>";
$dev_array = array();
$dev_array = $token_array;
foreach ($dev_array as $device_token)
{
$msg = chr(0) .
pack("n", 32) .
pack('H*', str_replace(' ', '', $device_token)) .
pack("n", strlen($payload)) .
$payload;
// echo "sending message :" . $payload . "n";
fwrite($fp, $msg);
}
fclose($fp);
}
Also check this, might be helpful: Facing problems in ios push notification php code

Facing problems in ios push notification php code

I use this code in php...
function pushnotificationios( $deviceToken, $message, $badges){
$passphrase = "12345";
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $_SERVER['DOCUMENT_ROOT'].'/include/ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
"ssl://gateway.push.apple.com:2195", $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
$body['aps'] = array(
//'badge' => $badges,
'badge' => "+1",
'alert' => $message['message'],
'sound' => 'default',
'content-available' => '1'
);
$body['msg'] =$message;
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
//echo "<pre>"; print_r($result);
fclose($fp);
return $result;
}
.pem file and their password is correct. but when i hit this function then only on production mode it give me return false;
$result = pushnotificationios( $deviceToken, $message, $badges);
echo "<pre>"; print_r($result);
And it takes too much time to response.
Currently i am not find any solution.. my api is going to apple and my notifications is not working. The interesting thing is its a chating app and whole app is based on notifications. Its a bad day for me.
Please help if something happen good for me for app.
In production mode don't use sandbox url
$fp = stream_socket_client(
"ssl://gateway.push.apple.com:2195", $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
Production:
ssl://gateway.push.apple.com:2195
.
Development:
ssl://gateway.sandbox.push.apple.com:2195
In my app. I am directly getting deviceToken that's in NSData
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *deviceTokenString = [NSString stringWithFormat:#"%#", deviceToken];
// this is producing something like:
// <xxxxxxx 9b0f527f xxxxxxxx 2727ed28 xxxxxxxx 4e693a61 xxxxxxx ac2f7dbb>
//
// and i am directly saving that to my servers database
Here's what i have in my server.
/***
* Function: template_user_info
*
* Parameter
* • $message_input
* - String message
* • $token_array
* - Array contains: `token` ex. "<xxxxxxx 9b0f527f xxxxxxxx 2727ed28 xxxxxxxx 4e693a61 xxxxxxx ac2f7dbb>"
* Note:
* this removes the '<' and '>' to make the device token valid
* `$device_token = str_replace(">","",str_replace("<","",$device_token));`
* ---
*/
public function __push_notification($message_input, $token_array)
{
$push_config = array(
"development" => array(
"status" => true,
"cert" => realpath('xxx.pem'),
"pass" => 'xxxxxx',
"server" => 'ssl://gateway.sandbox.push.apple.com:2195'
),
"production" => array(
"status" => true,
"cert" => realpath('xxx.pem'),
"pass" => 'xxxxxx',
"server" => 'ssl://gateway.push.apple.com:2195'
)
);
$message = stripslashes($message_input);
foreach ($push_config as $key => $value)
{
if ($value['status'] === true)
$this->__exe_push_notification($message, $value, $token_array);
}
}
private function __exe_push_notification($message, $config, $token_array)
{
$cert = $config['cert'];
$pass = $config['pass'];
$server = $config['server'];
$payload = '{
"aps" :
{
"alert" : "'.$message.'",
"badge" : 1,
"sound" : "bingbong.aiff"
}
}';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $cert);
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
$fp = stream_socket_client($server, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
{
// echo "Failed to connect $err $errstr <br>";
return;
}
else
// echo "Post notification sent<br>";
$dev_array = array();
$dev_array = $token_array;
foreach ($dev_array as $device_token)
{
$device_token = str_replace(">","",str_replace("<","",$device_token));
$msg = chr(0) .
pack("n", 32) .
pack('H*', str_replace(' ', '', $device_token)) .
pack("n", strlen($payload)) .
$payload;
// echo "sending message :" . $payload . "n";
fwrite($fp, $msg);
}
fclose($fp);
}
If you still cant send notification check this Troubleshooting Push Notifications
Edit
I've been looking at your push notification push, a while ago, then i've noticed that your 'badge' => "+1"
You cannot increment badge like that.
The only option is to manage it in your app and using database to keep on track..
and maybe it is causing the problem.. and badge must be a Number, here: Table 3-1
And also check this discussion might help you as well..
Edit 02/12/19
I've updated the php code for push notification to support both development and production.
Yup.. finaly i got the solution.
The problem is the port. I using Bluehost server. Bluehost block the port which is used by push notification. Now i changed my server and notifications working for me..
Thanks all budy

Sending multiple iPhone push notifications + APNS + PHP

I am working on a PHP website + iPhone application and API for iPhone application, has a messaging system for students and doctors, when any one sends message (from website or iPhone) the other user should get push notification on his iphone. For example if student adds a new question for teacher, a push notification on teachers iPhone/iPad will be send to teacher and when teacher replies to student's answer, student will get a push notification.
Since there is no restriction on number of teachers and student registering to website, my question is how to send push messages to registered user's iPhone? I want to send push message as soon as someone replies or adds a question. Please provide me PHP code for sending multiple push messages.
I am saving device token for each user while registration.
When teacher reply to question I am sending mail to student, I want to send a push notification too to student and vice versa so please specify code able to manage error conditions.
Simple way to do it without use any file. You can call it multiple times with different tokeid.
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckipad.pem');
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 amarnew: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'badge' => +1,
'alert' => $message,
'sound' => 'default'
);
$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 amar'.$message. PHP_EOL;
// Close the connection to the server
fclose($fp);
You should better use APNS library for PHP. You can find it here. Look through samples that developers provide.
I also had problems with certificates. My actions were:
locate file ApnsPHP/Abstract.php
make some changes to _connect() method, paste this lines
$streamContext = stream_context_create(
array(
'ssl' => array(
'local_cert' => $this->_sProviderCertificateFile,
'passphrase' => ''
)
)
);
$this->_hSocket = #stream_socket_client(
$sURL,
$nError,
$sError,
$this->_nConnectTimeout,
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
$streamContext);
instead of original listed there
now you can use *.pem certificates without need of entrust_root_certification_authority.
This worked fine for me.
This is the way I have done it finally
Downloaded apns-php
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!';
}

Categories