Apple push notification with cURL
17,930
Solution 1
Here is the code for device token and json message,I think this will help you.
$url = 'https://gateway.sandbox.push.apple.com:2195';
$cert = 'AppCert.pem';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $cert);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, "passphrase");
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"device_tokens": ["458e5939b2xxxxxxxxxxx3"], "aps": {"alert": "test message one!"}}');
$curl_scraped_page = curl_exec($ch);
Solution 2
This code works
$deviceToken = '...';
$passphrase = '...';
$message = '...';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'xxx.pem');
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);
$body['aps'] = array('alert' => $message,'sound' => 'default');
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
fclose($fp);
Author by
Pierre
Updated on July 25, 2022Comments
-
Pierre almost 2 years
Is there a way to implement in PHP a posting push notification system by using cURL (instead of stream_socket_client) ?
I wrote :
$url = 'https://gateway.sandbox.push.apple.com:2195'; $cert = 'AppCert.pem'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSLCERT, $cert); curl_setopt($ch, CURLOPT_SSLCERTPASSWD, "passphrase"); $curl_scraped_page = curl_exec($ch);
But how to set the device token and the json message ?
-
Zbyszek about 9 yearsDoes not work and according to documentation you need binary format not full json so it shouldn't work. It looks like API of Urban Airship push endpoint.
-
Zbyszek about 9 yearsSee stackoverflow.com/questions/13730351/… if you need proxy with stream_context_create.
-
Romain Bruckert over 7 yearsNot working. And you cant send push notifications to Apple via HTTP. You must indeed use TCP binary communication.