php apns 推送

2013-08-28 21:33  1683人阅读  评论 (0)

php apns 推送

<?php
// 转换
// openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
// openssl pkcs12 -nocerts -out key.pem -in key.p12
// openssl rsa -in key.pem -out key.unencrypted.pem
// cat cert.pem key.unencrypted.pem > ck.pem
$deviceToken = '';
$passphrase = '';
$message = '123456';

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.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);

//if (!$fp)
//exit("Failed to connect amarnew: $err $errstr" . PHP_EOL);

//echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
'badge' => +1,
'alert' => $message,
'sound' => 'default'
);

$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered amar'.$message. PHP_EOL;

// Close the connection to the server
fclose($fp);