iPhone push notification server : something to do after server changed? - php

I successfully manage to implement an iPhone push notification server (PHP) last year; I had to change the server, and was thinking that moving files was sufficient... I was wrong, since the modification notifications are not sent anymore. There's no error, everything seems ok, but notification aren't received.
Below is my server code; anyone can think of a cause, or a way to find the problem ? (notes: the $deviceTokens var is correct, contains the device tokens, and I've successfully tested my .pem certificate with an openssl command).
$payload['aps'] = array('alert' => 'notification!!', 'sound' => 'push.aif');
$payload = json_encode($payload);
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', 'libraries/ck_prod.pem');
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:' . 2195, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
if($error) {
log_message('error', $errorString);
return;
}
log_message('debug', 'sending push notification...');
if($apns) {
foreach($deviceTokens as $deviceToken) {
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
}
fclose($apns);
} else {
log_message('error', 'error while sending push notification');
}

Well well... Maybe I should have notice that I was contacting the test server (gateway.sandbox.push.apple.com)... Some days are just difficult...

Related

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';

Apple Push Notifications System Not Receving Message! (PHP)

This is the code I wrote to send apple push notifications.
in the device_tokens i'm sending an array with all of the tokens I want to send message to.
For some reason, I stopped recieving messages from this system.
and it used to work before!
private function send_iphone_notification($device_tokens, $message)
{
define("PRODUCTION_MODE", true);
$apnsPort = 2195;
// Choose dev or production apns host and certificate
if(PRODUCTION_MODE) {
$apnsHost = 'gateway.push.apple.com';
$apnsCert = $_SERVER['DOCUMENT_ROOT'].'/ant/www/apns/PushIphone.pem';
} else {
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsCert = $_SERVER['DOCUMENT_ROOT'].'/ant/www/apns/CertificatesDev.pem';
}
// Notification content
$payload = json_encode(array('notification_from_panel' => 1, 'aps' => array('alert' => $message, 'badge' => 1, 'sound' => 'default')));
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
stream_context_set_option($streamContext, 'ssl', 'passphrase', "");
// loop all devices tokens
foreach ($device_tokens as $device_token)
{
try {
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
} catch(Exception $e) {
echo $e->getMessage();
continue;
}
$deviceToken = str_replace(" ","",substr($device_token,1,-1));
//echo $deviceToken;
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(mb_strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
//socket_close($apns);
fclose($apns);
}
}
I have some experience with Apple's push service and i have to say that apple seems to have soem restrictions in place.
First of all you dont need to close and open the socket connection for every message. That will save you a lot of time. On the other hand you have to check if the connection is broken before you send the next message.
Anyway, it seemed that apple does not like it much when you connect a hundred times a second and send messages. Apples has blocked me for that as well in the passed.
But when you send the message with a already established connection, and at some point the connection is returning an error/ is disconnected, you dont know at what message he stopped. But you can define a identifier for each message and check the error returned when the connection is broken.
I noticed that apples server returns the error with a couple of seconds delay. That makes it hard do deal with it the easy way.
I have written a class to handle all of that but did not jet have time to publish it! If you are interested in it, check the github project for it at https://github.com/tinned-software/PHP-Tinned-MobilePush
I hope to finish the documentation soon.

Iphone push notification service problem

I am using Push Notification in my app and a PHP server that manages database with tokens and sending payload to Apple servers. Sending messages to a small number of devices (I have tried with 2) works well but when I want to send a message to entire database ( over 20.000 devices ) it doesn't work. Connection with Apple server is made ( i get no errors of connection ) but the two devices I have ( that are also in database ) do not received the message.
The PHP code is:
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'path/to/my/certificate.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);
while($row = mysql_fetch_array($result))
{
$deviceToken=$row['token'];
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
if ($error==0)
{
echo "Notification was sent successfully to ".$row['token']."<br/>";
}
else
{
echo "Notification failure to ".$row['token']."<br/>";
}
}
socket_close($apns);
fclose($apns);
As a result I am getting "Notification was sent successfully" for all the records in database but it seems like it doesn't send the message because I don't see it on my devices. When I am using the same code to send message to 2 tokens it works well. What could be the problem? Is there an upper limit for number of devices I can send to with one connection?
Not sure if there is a limit, but I'm sure it won't be low as I have successfully sent notifications to thousands of devices at a time in the past (although currently I'm shooting them about 250-500 at a time).
Try replacing this:
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
With this:
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n", strlen($payload)) . $payload;
Also, you might be interested in trying this out: http://code.google.com/p/apns-php/

Enhanced Apple Push Notification: Response error at provider server

i am working on a project in PHP which requires me to push an alert notification on APNS server. I have used enhanced push notification format. but I am not receiving response as specified by the APNS docs. I am getting response in three digits usually 133, 132, 154, 138, etc. Which I concluded to be Status signs, eg. 133 is 1, 3, 3. but now I have also received 139. so I doubt that my interpretation of response is wrong. But I am not getting where it is wrong. And important thing is though I am receiving these responses Alert is getting pushed and I am receiving notification on my iPhone as well as on iPad.
My code is as follows:
$payload['aps'] = array('alert' => $message, 'badge' => 1, 'sound' => 'default');
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195; // default port
$apnsCert = 'apns-dev.pem'; // APNS crtificate.
$passPhrase = '';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
stream_context_set_option($streamContext, 'ssl', 'passphrase', $passPhrase);
try{
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
if (!$apns) {
print "Failed to connect {$error} {$errorString}\n";
}
else {
// Sending the payload
$apnsMessage = chr(0) . pack('n', 1) . pack('n', $nid) . pack('n', time() + 604800) . pack('n', 32) . pack('H*', str_replace(' ', '', $alert_device_token)) . pack('n', strlen($payload)) . $payload;
echo 'APNS Message: ' . $apnsMessage;
$fwrite = fwrite($apns, $apnsMessage);
echo 'APNS response: ' . $fwrite;
And when this get executed i got the following response printed on the browser:
APNS Message: ��=ŸÂ� òc6–U:õŸŠ ¸Þ ÷ćÚ0ßqšÊzÂífÕnZ�`{"aps":{"alert":"Your EUR\/USD SELL alert price has been reached!","badge":1,"sound":"default"}}APNS response: 139
Can anyone please tell me what does this 139 means here. am doing anything wrong here.
The echoed "139" is the return value of fwrite(). It's the number of bytes written by fwrite()
See: PHP: fwrite

Apple Push Notification Service with PHP Script

I'm trying so send push notifications ton my iPhone (APNS). I read this post and try to implement it. So all my certificates are good (normaly).
Now I have this php script :
$device = '4f30e047 c8c05db9 3fa87e7d ca5325f7 738cb2c0 0b4a02d4 d4329a42 a7128173'; // My iphone deviceToken
$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
$payload['server'] = array('serverId' => $serverId, 'name' => $name);
$output = json_encode($payload);
$apnsCert = 'apple_push_notification_production.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
//socket_close($apns); seems to be wrong here ...
fclose($apns);
When I run this script nothing happen. no error just an empty page but my iPhone doesn't receive the push notification ...
Have you got an idea?
Thanks a lot !
no space in device token, strip them
For development certificate you need url
'ssl://gateway.sandbox.push.apple.com:2195'
but for production
'ssl://gateway.push.apple.com:2195'
Strip the spaces from token and even then it's not work then
$apnsHost = 'gateway.sandbox.push.apple.com';
Remove "sandbox" from this url and it will run.
If you have more than one device and you loop through them I found that you have to create a new stream_context_create for each fwrite to prevent apple from closing the connection for a bad token.
FYI
To send notifications success fully you have to do 1 more thing.
Replace $output = json_encode($payload);
to $payload = json_encode($payload);
You are missing to provice certificate private key. Add this row:
stream_context_set_option($streamContext, 'ssl', 'passphrase', $certificatePrivateKey);

Categories