PHP apple push notification fail when multiple - php

I have written a function to send push notifications to iOS devices. It sends pushes to more than 100 devices for now. However sometimes it is not sending push notifications. When I debug through the process I identified based on push notification the whole process fails. but the issues is all push tokens are in valid format. So my initial code was like this.
$certificatePath = CERTIFICATE_PATH . "/".APN_CERTIFICATE_FILE;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($streamContext, 'ssl', 'passphrase', APN_PASSWORD);
$apns = stream_socket_client(APN_HOST . ':' . APN_PORT , $error, $errorString, 2, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
if (!$apns) {
echo "Failed to connect $err $errstrn";
return false;
}
$payload = array();
$payload['aps'] = array('alert' =>$message,'title'=>$title, 'sound' => 'default','data'=>array());
$payload = json_encode($payload);
foreach ($pushTokens as $pushToken)
{
$pushToken = str_replace(' ', '', $pushToken);
if(!ctype_xdigit($pushToken))
continue;
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $pushToken)) . pack ("n",strlen($payload)) . $payload;
$rst = fwrite($apns, $apnsMessage);
}
fclose($apns);
As a fix I changed the code to different way. I know this code is expensive since it open and close connection for every push notification.
$certificatePath = CERTIFICATE_PATH . "/".APN_CERTIFICATE_FILE;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($streamContext, 'ssl', 'passphrase', APN_PASSWORD);
$payload = array();
$payload['aps'] = array('alert' =>$message,'title'=>$title, 'sound' => 'default','data'=>array());
$payload = json_encode($payload);
foreach ($pushTokens as $pushToken)
{
$apns = stream_socket_client(APN_HOST . ':' . APN_PORT , $error, $errorString, 2, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
if (!$apns) {
echo "Failed to connect $err $errstrn";
return false;
}
$pushToken = str_replace(' ', '', $pushToken);
if(!ctype_xdigit($pushToken))
continue;
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $pushToken)) . pack ("n",strlen($payload)) . $payload;
$rst = fwrite($apns, $apnsMessage);
fclose($apns);
}
I am wondering if it is an issue with fwrite or somewhere else. Appreciate if someone can help me with my first method as it is speed, and run with minimum resources.

Related

Can't push notification to APNS to update my pass in Apple Wallet

I'm trying to push notification to APNS to update my pass in Apple Wallet app. According to this document, we only need to send the pass type identifier and the push token to APNs. Then they will take care of the rest.
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = base_path('app/config/passbook/certificates.pem');
$payload = ['aps' => []];
$payload = json_encode($payload);
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
stream_context_set_option($streamContext, 'ssl', 'passphrase', 'xxxxxx');
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if(!$apns) {
Logger::logError(1, "Passbook push notification error", ['serial_number' => $serialNumber, 'pass_type_id' => $passIdentify]);
return "Failed to connect (stream_socket_client): $error $errorString";
} else {
foreach($push_tokens as $idx => $push_token) {
$msg = chr(0) . pack('n', 32) . pack('H*', $push_token) . pack('n', strlen($payload)) . $payload;
fwrite($apns, $msg);
}
}
#socket_close($apns);
fclose($apns);
There is no error returned but it seem doesn't work. What do I do wrong? Please help.
This is the code working on my project
$errors = [];
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = base_path('app/config/passbook/certificates.pem');
$payload = ['aps' => []];
$payload = json_encode($payload);
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
stream_context_set_option($streamContext, 'ssl', 'passphrase', 'xxxxxxxxx');
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
stream_set_blocking ($apns, 0);
if( ! $apns) {
return "Failed to connect (stream_socket_client): $error $errorString";
} else {
foreach($push_tokens as $idx => $push_token) {
$msg = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $push_token)) . chr(0) . chr(mb_strlen($payload)) . $payload;
$success = fwrite($apns, $msg);
if ($success === strlen($msg)) { // log success
Logger::logPassbook('Push success', ['push_token' => $push_token]);
} else {
Logger::logPassbook('Push failed', ['push_token' => $push_token]);
}
}
}
#socket_close($apns);
fclose($apns);
return $errors;

Unable to send push notification to ios using php

I am trying to send a push notification to IOS using php and Yii framework. I created a function as follows to get data and send notification. $data is an array which contains a message and an array inside to keep registration IDs (device tokens). I ran it on my localhost but notification is not sent to my device. By the way, the output of my function is an integer value and I cannot recognize if the message has been sent or what!?
Is there anything wrong in my code?
private function _pushIOS($data)
{
// Create a connection
$apnsHost = $this->_notificationUrl;
$apnsPort = 2195;
$apnsCert = Yii::app()->controller->createUrl('/').'/my_certificate_dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if (!$apns)
exit("Failed to connect: $error $errorString" . PHP_EOL);
foreach($data['registration_ids'] as $deviceToken) {
$body = array();
$body['aps'] = array(
'alert' => $data['data']['message'],
'badge' => 1,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($apns, $apnsMessage, strlen($apnsMessage));
}
// Close the socket and connection to the server
#socket_close($apns);
fclose($apns);
return json_decode($result);
}
Finally, I got the answer. The problem was with the pem file path. Absolute path must be passed to the function to work. The following line should be replaced:
$apnsCert = Yii::app()->controller->createUrl('/').'/my_certificate_dev.pem';
Correct path:
$apnsCert = dirname(Yii::app()->request->scriptFile).'/my_certificate_dev.pem';

How to increase stream_set_timeout() in php

I am sending push message to iPhone devices Through steam_socket using php.It's working fine but i want to send a 1000 records at time in that case i get only 50 messages then i get Warning: stream_set_timeout():
how could i increase stream socket time is there any way to handle this type problem can any one please guide me.
here is my code
for($i=0;$i<100;$i++)
{
$gstr="3f3dad52b4fb50001cb223253a3d995542209d354eXXXXXXXXXXXXXXXX";
pushMessage($gstr,$_REQUEST['msg'].$i,"Thinkingofyou");
}
function pushMessage($deviceToken,$message,$app) {
echo "Sending iPhone Push Notifications to " . $deviceToken . "<br /><br />";
echo "Your Message: " . $message . "<br />";
$time = time();
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'aps-toyPush.pem';
$streamContext = stream_context_create();
stream_set_timeout($streamContext, 3600);
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
//stream_context_set_option($streamContext, 'ssl', 'passphrase', $passphrase);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if($apns) {
$payload = array();
$payload['aps'] = array('alert' => $message, 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
} else {
echo "Connection Failed - iPhone Push Notifications Server";
echo $errorString."<br />";
echo $error."<br />";
}
// socket_close($apns);
fclose($apns);
}
Thanks for advance.
Taken from a user's post in the PHP manual:
<?php
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>$sec, 'usec'=>$usec));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>$sec, 'usec'=>$usec));
?>

Apple Push notification not being sent

I have generated the .cer file, provision file with the correct device ID, generated the .pem file by combining the .cer and private key files, uploaded it to the server. The app id matches. I have provided the passphrase too, which is correct.
I tested the port and connection using telnet from the server, it connects fine.
I have tested the certificate by openssl command, and it returned 0 - no errors.
The certificates and the application is in development/debug mode, the iPhone is set up to receive notifications, the token is received and is delivered to the server correctly and in the same length - 64.
When sending the message from the server, the error code is 0 - which means no errors.
Here is the code sample from the server:
$options = array('ssl' => array(
'local_cert' => 'cert.pem',
'passphrase' => 'pass'
));
$streamContext = stream_context_create();
stream_context_set_option($streamContext, $options);
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
if ($apns)
{
$payload['aps'] = array('alert' => 'push test', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $token)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
fclose($apns);
}
else
{
echo "Connection failed";
echo $errorString."<br />";
echo $error."<br />";
}
What else can I possibly try?
The code that worked in the end is the following:
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushcert.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', 'pass');
// Create the payload body
$body['aps'] = array(
'alert' => array('body' => 'Message', 'action-loc-key' => 'Show'),
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Open a connection to the APNS server
$apns = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$apns)
{
echo "Failed to connect: $err $errstr" . PHP_EOL;
}
echo 'Connected to APNS' . PHP_EOL;
$imsg = chr(0) . pack('n', 32) . pack('H*', $message) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$res = fwrite($apns, $imsg, strlen($imsg));
if (!$res)
{
echo 'Message not delivered' . PHP_EOL;
}
else
{
echo 'Message successfully delivered' . PHP_EOL;
}
fclose($apns);

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