设为首页 收藏本站
查看: 938|回复: 0

[经验分享] How to build an Apple Push Notification provider server (php)

[复制链接]

尚未签到

发表于 2017-4-10 08:22:38 | 显示全部楼层 |阅读模式
  
[size=1em]Device Token

[size=1em]Each push message must be “addressed” to a specific device. This is achieved by using a unique deviceToken generated by APNS within your iPhone application. Once this token has been retrieved, you need to store it on your server, not within your iPhone application itself. It looks something like this:

[size=1em]c9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc
[size=1em]For the Server Density iPhone application, we call the necessary generation methods on app launch and pass it back to our servers via an HTTP API call. This stores the deviceToken in a database on our servers for that user so we can then communicate with the device linked to that user.
[size=1em]Feedback Service
[size=1em]Apple provide a feedback service which you are supposed to occasionally poll. This will provide a list of deviceTokens that were previously but are no longer valid, such as if the user has uninstalled your iPhone application. You can then remove the deviceToken from your database so you do not communicate with an invalid device.
[size=1em]Using the feedback service is not covered by this tutorial.
[size=1em]Certificates
[size=1em]The first thing you need is your Push certificates. These identify you when communicating with APNS over SSL.
[size=1em]Generating the Apple Push Notification SSL certificate on Mac:


  • Log in to the iPhone Developer Connection Portal and click App IDs
  • Ensure you have created an App ID without a wildcard. Wildcard IDs cannot use the push notification service. For example, our iPhone application ID looks something likeAB123346CD.com.serverdensity.iphone
  • Click Configure next to your App ID and then click the button to generate a Push Notification certificate. A wizard will appear guiding you through the steps to generate a signing authority and then upload it to the portal, then download the newly generated certificate. This step is also covered in the Apple documentation.
  • Import your aps_developer_identity.cer into your Keychain by double clicking the.cer file.
  • Launch Keychain Assistant from your local Mac and from the login keychain, filter by the Certificates category. You will see an expandable option called “Apple Development Push Services”
  • Expand this option then right click on “Apple Development Push Services” > Export “Apple Development Push Services ID123″. Save this as apns-dev-cert.p12 file somewhere you can access it.
  • Do the same again for the “Private Key” that was revealed when you expanded “Apple Development Push Services” ensuring you save it as apns-dev-key.p12 file.
  • These files now need to be converted to the PEM format by executing this command from the terminal:
    openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
    openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
  • If you wish to remove the passphrase, either do not set one when exporting/converting or execute:
    openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
  • Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:
    cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

[size=1em]It is a good idea to keep the files and give them descriptive names should you need to use them at a later date. The same process above applies when generating the production certificate.
[size=1em]Payload Contents
[size=1em]The payload is formatted in JSON, compliant with the RFC 4627 standard. It consists of several parts:


  • Alert – the text string to display on the device
  • Badge – the integer number to display as a badge by the application icon on the device home screen
  • Sound – the text string of the name of the sound to accompany the display of the message on the device
  • This tutorial will only deal with the basics by sending a simple alert text string but this can also be another dictionary containing various options to display custom buttons and the like.

[size=1em]Creating the payload
[size=1em]Using PHP it is very easy to create the payload based on an array and convert it to JSON:

$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);

[size=1em] 
Echoing the contents of $payload would show you the JSON string that can be sent to APNS:

{
"aps" : { "alert" : "This is the alert text", "badge" : 1, "sound" : "default" }
}
[size=1em] 
This will cause a message to be displayed on the device, trigger the default alert sound and place a “1″ in the badge by the application icon. The default buttons “Close” and “View” would also appear on the alert that pops up.
[size=1em]For the Server Density server monitoring iPhone application, it is important for the user to be able to tap “View” and go directly to the server that generated the alert. To do this, we add an extra dictionary in of our own custom values:

$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
$payload['server'] = array('serverId' => $serverId, 'name' => $name);
$output = json_encode($payload);
[size=1em] 
The custom dictionary server is passed to the application on the device when the user taps “View” so we can load the right server. The JSON looks like this:

{
"aps" : { "alert" : "This is the alert text", "badge" : 1, "sound" : "default" },
"server" : { "serverId" : 1, "name" : "Server name")
}
[size=1em] 
The size limit of 256 bytes applies to this entire payload, including any custom dictionaries.
[size=1em]The raw interface
[size=1em]Once an alert is generated within Server Density, the payload is built and then inserted into a queue. This is processed separately so that we can send multiple payloads in one go if necessary.
[size=1em]Apple recommends this method because if you are constantly connecting and disconnecting to send each payload, APNS may block your IP.
[size=1em]As described by Apple:


[size=1em]The raw interface employs a raw socket, has binary content, is streaming in nature, and has zero acknowledgment responses.


[size=1em] DSC0000.jpg
[size=1em]Opening the connection
[size=1em]The PHP 5 code to open the connection looks like this:

$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
[size=1em] 
If an error has occurred you can pick up the error message from $errorString. This will also contain the details if your SSL certificate is not correct.
[size=1em]The certificate file is read in relative to the current working directory of the executing PHP script, so specify the full absolute path to your certificate if necessary.
[size=1em]Note that when testing you must use the sandbox with the development certificates. The production hostname is gateway.push.apple.com and must use the separate and different production certificate.
[size=1em]Sending the payload
[size=1em]At this point, the code we use loops through all the queued payloads and sends them. Constructing the binary content to send to APNS is simple:

$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
[size=1em] 
Note that the $deviceToken is included from our database and stripped of the spaces it is provided with by default. We also include a check to send an error to us in the event that the$payload is over 256 bytes.
[size=1em]$apnsMessage contains the correctly binary formatted payload and the fwrite call writes the payload to the currently active streaming connection we opened previously, contained in$apns.
[size=1em]Once completed, you can close the connection:

socket_close($apns);
fclose($apns);
[size=1em]php-apns
[size=1em]There is a free, open source server library that does all the above functionality called php-apns. We chose to implement it ourselves because it has a further dependancy on memcached, we do not want to rely on 3rd party code for large and critical aspects of our code-base and I am apprehensive about the suitability of PHP for running a continuous server process. We do all the above queue processing using our own custom cron system which runs every few seconds – that way PHP scripts do not need to be run as processes, something I’m not sure they were designed to do!
[size=1em]All done
[size=1em]That’s it! If you have any problems, post in the comments below and we’ll do our best to help out. Also, Stack Overflow is your friend.


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-362647-1-1.html 上篇帖子: PHP+Sphinx建立高效的站内搜索引擎 下篇帖子: php在线生成pdf中文乱码完美解决``
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表