Tuesday, June 3, 2014

Push Notification Server Side Code in PHP

<?php

$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);

?>

===============================================================

<?php

// Create a stream to the server
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', 'apns-dev.pem');

$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

// You can access the errors using the variables $error and $errorString

$message = 'You have just pushed data via APNS';

// Now we need to create JSON which can be sent to APNS

$load = array(    'aps' => array(
                'alert' => $message,
                'badge' => 1,
                'sound' => 'default'
                )
            );

$payload = json_encode($load);

// The payload needs to be packed before it can be sent

$apnsMessage = chr(0) . chr(0) . chr(32);
$apnsMessage .= pack('H*', str_replace(' ', '', $token));
$apnsMessage .= chr(0) . chr(strlen($payload)) . $payload;


// Write the payload to the APNS

fwrite($apns, $apnsMessage);
echo "just wrote " . $payload;

// Close the connection
fclose($apns);

?>


No comments: