Reputation: 10159
I set up a PHP script to send push notifications using this tutorial. I run the script without any errors but nothing shows up on my device. What am I doing wrong?
Upvotes: 0
Views: 2221
Reputation: 91
Create a common function for the push notification Pass the following params in the function devicetoken, message and extra params as per your app requirement. if you are using developer pem file then you have to use "gateway.sandbox.push.apple.com:2195" and if you are using distributer panm file the you have to use "gateway.push.apple.com:2195"
public function pushtoios($devicetoken, $message, $params = array()) {
$passphrase = 'apple';
$ctx = stream_context_create();
/*Development pam file*/
//stream_context_set_option($ctx, 'ssl', 'local_cert', your path.'apns-dev.pem');
/*Distributer pam file*/
stream_context_set_option($ctx, 'ssl', 'local_cert', your path.'apns-distr.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
/*For Development pam file*/
//$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
/*For Distributer pam file*/
$fp = stream_socket_client('ssl://gateway.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);
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
$body['type'] = $params['type'];
$body['params'] = $params;
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $devicetoken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
return false;
} else {
return true;
}
fclose($fp);
}
Upvotes: 7
Reputation: 553
I have same problem but solved now by editing this line that i overlook...
$output = json_encode($payload);
to
$payload = json_encode($payload);
The first one will give strlen error but on my server the error does not generate. I got an strlen error when running on local host after failing trying on real server.
I also add an ssl passpharse for the local_cert, because my pem file has password.
Below is the final code that works... Please replace your_token_hex_string and your_passphrase with your own information.
$device = 'your_token_hex_string';
$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
$options = array('ssl' => array(
'local_cert' => 'apns_dev.pem',
'passphrase' => 'your_passphrase'
));
$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);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
fclose($apns);
Upvotes: 0