fbpx

如何透過 PHP 發送 Apple Notification Push

依照前一篇文章「iOS APNS 訊息推播 - Apple Push Notification Service 介紹」的介紹,大部分的工作 APNS 都幫我們做好了,我們只要透過憑證連上 APNS 並且依據以下規格進行溝通,訊息就能夠發送。

Simple Notification Format
Enhanced Notification Format
在 PHP 的實作上透過 stream_context_create() 函式建立 SSL 連線,再利用 pack() 函式實作上述的規格來傳送 Bytes 資料 (Payload),以下是 PHP 最精簡的發送訊息程式碼,執行後可以順利與 APNS 溝通與發送訊息。各位可以依據需求修改程式來發送 Enhanced 或 Simple 訊息,或者切換 Sandbox 或 Production 環境。程式範例如下:
<?php

// Production mode
$certificateFile = 'apns-dis.pem';
$pushServer = 'ssl://gateway.push.apple.com:2195';
$feedbackServer = 'ssl://feedback.push.apple.com:2196';

// Sandbox mode
$certificateFile = 'apns-dev.pem';
$pushServer = 'ssl://gateway.sandbox.push.apple.com:2195';
$feedbackServer = 'ssl://feedback.sandbox.push.apple.com:2196';

// push notification
$streamContext = stream_context_create();           
stream_context_set_option($streamContext, 'ssl', 'local_cert', $certificateFile);
$fp = stream_socket_client(
    $pushServer, 
    $error, 
    $errorStr, 
    100, 
    STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, 
    $streamContext
);

// make payload
$payloadObject = array(
    'aps' => array(
        'alert' => 'Server Time:'.date('Y-m-d H:i:s'),
        'sound' => 'default',
        'badge' => 3
    ),
    'custom_key' => 'custom_value'
);
$payload = json_encode($payloadObject);

$deviceToken = 'aa3b045415034b96da5e98f57e35735a8ed8b842506f770ee769de32c6305ed7';
$expire = time() + 3600;
$id = time();

if ($expire) {
    // Enhanced mode
    $binary  = pack('CNNnH*n', 1, $id, $expire, 32, $deviceToken, strlen($payload)).$payload;
} else {
    // Simple mode
    $binary  = pack('CnH*n', 0, 32, $deviceToken, strlen($payload)).$payload;
}
$result = fwrite($fp, $binary);
fclose($fp);

?>

參考資料

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料