依照前一篇文章「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 環境。程式範例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
// 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);
?>
|
參考資料