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.
Related
So, I moved my application to an EC2 instance, and Apple Push Notification Service stopped working. I'm using the same certificate, same script, same everything.
I've opened port 2195 in the security group for the EC2 instance.
from the EC2 intance, telnet gateway.push.apple.com 2195 works
my script receives no errors... everything gets to the end, even fwrite returns true... yet, I receive no push.
Things to note.
My EC2 instance is accessed via https where my old server was http, but since the script would be running locally, and has nothing to do with Apache, I don't see why this should matter. But, perhaps it does, so I'm letting you know :D
My script:
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$ssl = 'ssl://' . $apnsHost . ':' . $apnsPort;
$apns = stream_socket_client($ssl, $error, $errorString, 30, STREAM_CLIENT_CONNECT, $streamContext);
if($apns == false){
echo "Error: $errorString";
return false;
}
$payload['aps'] = array('alert' => $message, 'badge'=>$badge, 'sound' => 'default');
$payload = json_encode($payload);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_id)) . chr(0) . chr(strlen($payload)) . $payload;
if(fwrite($apns, $apnsMessage)){
return true;
}
return false;
I've checked all of my variables, they are set.
Any help would be greatly appreciated. This is driving me bonkers :P
Turns out I was giving a bad device id. The databases were different, and I stored something poorly. :(
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
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...
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);
I have a quick question. For the apple push notification service, I need to have my own server, which will send out the push notifications to the apple servers, right?
Can I do this with a simple PHP script on a regular webhosting account, or do I need a dedicated server with full blown admin access for that?
If this is possible in PHP, can anyone point me to some samples that can help me get started on this? Right now, I am pretty confident I won't have trouble implementing the client-side part, but the server side is still somewhat of a mystery to me...
Thank you!
Florian
You probably will be able to do this on a limited hosting account, as long as you can leave the connection open to the server most of the time. Some sample code:
http://code.google.com/p/php-apns/
Note also that some companies are starting up services to help you specifically with push hosting (I'll keep the post neutral and not mention names, I'm not sure which services are running just yet).
The Main problem with APNS is ports
so many providers doesnt open 2195 port
so concentrate on that initially then go for the host provider
Here is the code what i tried, but one problem is not able to get device notification
Hi ,
i tried the following code (PHP)
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apple_push_notification_production.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)
{
echo "Connection Established<br/>";
$deviceToken = '**********';//masked
$body = array();
$body['aps'] = array(’alert’ => "test message");
//$body['aps']['badge'] = 1;
$payload = json_encode($body);
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $apnsMessage . "<br/>";
print "sending payload :" . $payload . "<br/>";
fwrite($apns, $apnsMessage);
}
else
{
echo "Connection Failed";
echo $errorString;
echo $error;
}
socket_close($apns);
fclose($apns);
reply is Connection Established
sending message :�� d^÷Îå0ZCd%1ÄuwOOYš'ÊÈ}ârðm¾Í�,{"aps":{"\u2019alert\u2019":"test message"}}
sending payload :{"aps":{"\u2019alert\u2019":"test message"}}
But am not able to get the notification
any help?