2015年7月1日 星期三

[iOS] Apple Push Notification Service - 實作 Server 端

在上一篇 [iOS] Google Cloud Messaging for iOS 完整說明了 iOS app 實作以及 GCM Server 的實作。這篇將補齊 APNS Server 端的實作方式。

  1. 製作 ck.pem 供 APNS Server 使用
    • 輸出 Push Notification Service 憑證 ([iOS] Google Cloud Messaging for iOS 有說明製作方法),儲存成 cert.p12
    • 展開 Push Notification Service 憑證,輸出該專用金鑰,儲存成 key.p12
    • 使用終端機並指到上列兩個檔案的儲存地,依序輸入下列指令
    • openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
      
      openssl pkcs12 -nocerts -out key.pem -in key.p12
      
      cat cert.pem key.pem > ck.pem
      
    • 將 ck.pem 放置 Server 上
  2. 完整 PHP 程式碼
  3. // Put your device token here (without spaces):
    $deviceToken = 'iOS App 的 DeviceToken';
    
    // Put your private key's passphrase here:
    $passphrase = 'ck.pem 的金鑰';
    
    // Put your alert message here:
    $message = 'Hello APNS!';
    
    $ctx = stream_context_create();
    //stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.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,
        $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);