首先您必須到 https://developer.apple.com/ 去新增一個 App,一般就是你要用 push notification 的應用程式

設定好名字,還有 ID ,記得要把 Push Notifications 的服務打勾

我這裡說明就用中文,因為英文的說明有一堆了

接下來就可以打開您的 Mac / 應用程式 / 工具程式 / 鑰匙圈存取

我們選憑證輔助程式,從憑證授權要求憑證




把他存下來,我舉的例子就叫 PushMsg ,把檔名改成 PushMsg 所以你會得到 PushMsg.certSigningRequest 這一個 CSR ,待會要到 apple 網站上面產生憑證



產生後,到鑰匙圈存取 應用程式,選鑰匙的地方,你會看到有 PushMsg 的公鑰和密鑰,點選專用密鑰,按下滑鼠右鍵輸出憑證,輸出成 PushMsg.p12 待會用










這時候,請用剛剛的 PushMsg.certSigningRequest 到 Apple 開發者網站的 App 設定 notification 的地方去產生憑證,可以下載後,

開發模式,你會得到 aps_development.cer ,實際部署模式,請依此類推



我們現在有 PushMsg.certSigningRequest , PushMsg.p12 , 還有 aps_development.cer 接下來,我們來產生,Server 端程式需要的憑證格式

這裡的程式,我們用 Golang 的範例,其他用 Python , Node.js 或是其他語言的朋友請依此類推

產生 cert.pem


openssl x509 -in aps_development.cer -inform der -out cert.pem

產生 key.pem 由於我很懶,key.pem 不想加密碼,程式不想再判斷密碼部分,我用這樣,如果你要加 pass phrase 就不要加上 -nodes 即可

openssl pkcs12 -in PushMsg.p12 -out key.pem -nodes

最後就是用 Apple 文件上面的 openssl 測試即可,沒有錯誤,就是 OK 了

openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert cert.pem -key key.pem

最後附上 golang 的測試程式,實際上已經有現成的 library 可以用 https://github.com/anachronistic/apns

只有連線的測試,有用 openssl 測試就可了,直接執行沒有錯誤,就是連線沒有問題了,送訊息可以直接用上面的 library


package main

import (
“crypto/tls”
“fmt”
“net”
“os”
)

func main() {

// load
cert, err := tls.LoadX509KeyPair("./cert.pem", “./key.pem”)
if err != nil {
fmt.Println(“key error: “, err)
os.Exit(1)
}
conf := &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: “gateway.sandbox.push.apple.com”,
}

// connect to APPLE
conn, err := net.Dial(“tcp”, “gateway.sandbox.push.apple.com:2195”)

if err != nil {
fmt.Println(“tcp error: “, err)
os.Exit(1)
}

tlsconn := tls.Client(conn, conf)

// be nice
err = tlsconn.Handshake()
if err != nil {
fmt.Println(“tls error: “, err)
os.Exit(1)
}

}




參考資料

http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html

http://bravenewmethod.com/2011/02/25/apple-push-notifications-with-go-language/