一、先在工程里配置好證書,準備好這些相關(guān)文件:
a、Push.certSigningRequest
b、Push.p12
c、aps_developer_identity.cer
二、在應(yīng)用服務(wù)器采用PHP的方式將消息推送給APNS
php連接APNS也是需要證書的,還記得我們上面獲得的幾個證書嗎?打開終端,對上面的證書做如下處理
1. cd 進入證書所在目錄 把.cer文件轉(zhuǎn)換成.pem文件:
$ openssl x509 -in aps_developer_identity.cer -inform der
-out PushChatCert.pem
2. 把私鑰Push.p12文件轉(zhuǎn)換成.pem文件:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in Push.p12
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying – Enter PEM pass phrase:
你首先需要為.p12文件輸入passphrase密碼短語,這樣OpenSSL可以讀它。然后你需要鍵入一個新的密碼短語來加密PEM文件。還是使用”pushchat”來作為PEM的密碼短語。你需要選擇一些更安全的密碼短語。
注意:如果你沒有鍵入一個PEM passphrase,OpenSSL將不會返回一個錯誤信息,但是產(chǎn)生的.pem文件里面將不會含有私鑰。
3. 把私鑰和證書整合到一個.pem文件里:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
為了測試證書是否工作,執(zhí)行下面的命令:
$ telnet gateway.sandbox.push.apple.com 2195
Trying 17.172.232.226…
Connected to gateway.sandbox.push-apple.com.akadns.NET.
Escape character is ‘^]’.
它將嘗試發(fā)送一個規(guī)則的,不加密的連接到APNS服務(wù)。如果你看到上面的反饋,那說明你的MAC能夠到達APNS。按下Ctrl+C 關(guān)閉連接。如果得到一個錯誤信息,那么你需要確保你的防火墻允許2195端口。
然后再次連接,這次用我們的SSL證書和私鑰來設(shè)置一個安全的連接:
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195
-cert PushChatCert.pem -key PushChatKey.pem
Enter pass phrase for PushChatKey.pem:
你會看到一個完整的輸出,讓你明白OpenSSL在后臺做什么。如果連接是成功的,你可以鍵入一些字符。當(dāng)你按下回車后,服務(wù)就會斷開連接。如果在建立連接時有問題,OpenSSL將會給你一個錯誤消息,
ck.pem文件就是我們需要得到php連接APNS 的文件,將ck.pem和push.php放入同一目錄上傳到服務(wù)器,
4. push.php的代碼如下:
<code>
<?php
// Put your device token here (without spaces):
$deviceToken = 'e54a28777d6e8cdf8b39e01b1362adad1dc54ee2e3cf5658eb3036a0914e009c';
// Put your private key's passphrase here:密語
$passphrase = '1yyg';
// Put your alert message here:
$message = '恭喜你中獎了。。啊哈哈哈哈,推送測試而已';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '1yyg_dev.pem');
// stream_context_set_option($ctx, 'ssl', 'local_cert', '1yyg_pro.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
// 'ssl://gateway.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$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' . PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
<\code>
三、終端執(zhí)行php代碼
命令:cd 進入到php的目錄文件下
php push.php
你會發(fā)現(xiàn)出現(xiàn)推送成功的提示。。。當(dāng)然是英文版。。
有什么問題或者疑問歡迎底下留言。。。。