I'm currently in the process of setting up a provider server to send out push notifications to iOS devices with my app installed.
I'm struggling to find any recent versions of working examples but have put the following together. I'm getting no errors returned but the push notification isn't showing up on my test device.
I can confirm the latest device token is being used and the .pem cert is valid.
Any help on this would be greatly appreciated.
Best regards, J
$apnsHost = 'api.sandbox.push.apple.com';
$apnsCert = '/cert.pem';
$apnsPort = 2197;
$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);
$payload['aps'] = array(
'alert' => array(
'title' => 'Sample push number ' . mt_rand(100, 999),
'body' => 'Sample push body goes here'
),
'badge' => 9,
'sound' => 'default',
'my_value_1' => 'more data',
'my_value_2' => 'even more data'
);
// JSON-encode payload
$output = json_encode($payload, JSON_NUMERIC_CHECK);
// Cancel if payload too long
if(strlen($output) > 2048){
die('Payload too long ('.strlen($output).'): Aborted');
}
// Build the binary notification (correctly)
$token = '185e522cd0e3f35f09sdg398f25fe28038f6a0743339b0a378';
$apnsMessage = chr(0).pack('n', 32).$token.pack('n', strlen($output)).$output;
// Send it to the server
$result = fwrite($apns, $apnsMessage, strlen($apnsMessage));
// Result returns number of bytes sent on success, false otherwise
if(intval($result) > 0){
// Push sent
$response = $result.' bytes sent. $payload size is: '.strlen($output).' (payload limit is 2048 bytes)';
fclose($apns);
}else{
// Push failed
$error = error_get_last();
$response = (is_array($error) ? $error['message'] : 'undefined error');
}
// Show result
die($response);
Output: 240 bytes sent. $payload size is: 171 (payload limit is 2048 bytes)