iOS 的消息推送機制,可以拆成三個參與方與三個階段來看。Provider 是某個應用的推送服務器,APNS 則是 Apple Push Notification Service,蘋果的中轉服務器。
落到開發流程上就是五步:應用註冊消息推送;iOS 向 APNS 申請並取得 device token,應用拿到它;應用把 device token 上報給自己的推送服務端;服務端帶著 token 向 APNS 發消息;APNS 再把消息送到 iPhone 上的應用。
$ openssl pkcs12 -in cert.p12 -out apple_push_notification_production.pem -nodes -clcerts
生成的 .pem 就是 PHP 連接 APNS 所需的憑證。把它與 push.php 放在同一目錄上傳到服務器。
<?php
// 這裡是設備的 deviceToken(記得去掉空格)
$deviceToken = '740f4707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bb78ad';
// 私鑰密碼
$passphrase = 'abc123456';
// 要推送的提示內容
$message = 'My first push test!';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apple_push_notification_production.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// 正式發布地址(發佈到 App Store 後使用)
// $fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
// 沙盒測試地址
$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: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// 組裝 payload
$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));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
fclose($fp);
?>
實務提醒:sandbox 與 production 的 device token 互不通用,上線前務必切換地址;示例用的是早期的二進制接口格式,新項目建議採用 HTTP/2 的 APNs 接口並配合 JWT 認證;私鑰與密碼切勿硬編碼在代碼庫中。