How to write an apple push Notification Server

Source: Internet
Author: User
Tags openssl rsa pkcs12

A new feature introduced to iPhone OS 3.0 is push notifications, which allows you to install applicationsProgramDevices directly send messages. Apple has shown this feature in news or IM applications, and it is perfect for our server monitoring service program server density.


Our program provides an option to send notifications directly to your iPhone when a server event you set occurs. This is very useful because it reminds users to immediately open our program to view the server details that caused this warning.


Apple provides detailed code documentation on iPhone OS that implements and processes prompts on devices, but it only includes the message provider Server programming guide.


As a message provider, we need to connect to the Apple push notification service (apns) to send messages to the iPhone. To reduce battery usage, a device only needs to maintain a connection with apns.


In this tutorialCodeThis section describes how to create a push notification server to connect to apns and use push notifications to monitor iPhone programs on our servers. We use PHP for development. Our examples are compatible with PHP 5.

  Basic Structure


Connect to apns using a unique SSL license

    1. You need to send messages cyclically
    2. Build a payload for each message
    3. Disconnect from apns

The process of remote notification data is one-way. The provider packs data that includes the client program device token and the payload and sends it to apns. Then, apns sends the notification to the final device.


-Apple documentation

  Restrictions
    • The payload is limited to 256 bytes-it includes the message body and other attributes you want to conveyor. Push notifications are not suitable for transmitting a large amount of data. For example, we send only one short message to notify the server that the event being monitored has been triggered.
    • Apns does not provide feedback on message sending success or failure. One reason is that if a device cannot be connected, the messages sent to it will be stored in the queue, however, only the newly sent messages are stored in the queue-the messages that were previously sent but failed to be sent are overwritten.
    • Push notifications are not suitable for sending emergency notifications because messages can only be sent when the device has a Wi-Fi or mobile phone service connection, this is why we recommend using it with other methods, such as email or SMS.
    • The SSL license used to communicate with apns (discussed below) is generated at the program layer. The implementation method involved in this tutorial is only applicable to a single iPhone program, so if you have multiple programs, you need to modify the code to make it suitable for using multiple licenses.
  Device token


Each push message must be sent to a specific device. This is achieved by using the unique devicetoken (device token) generated by apns in your iPhone program. Once you get this token, you need to store it on the server rather than in your iPhone program. It looks like this:

C9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc


In our server density iPhone program, we call the corresponding Token Generation Method when the program starts, and then call the http api back to our server. This will allow devicetoken to be stored in the database of the relevant user on the server, so that we can use it to communicate with the user holding this device.

  Feedback Service


Apple also provides a feedback service that you should query regularly. It provides a list of device tokens that have been used before but are no longer valid (for example, the user has uninstalled your iPhone program. You can delete these device tokens from your database.


This tutorial does not involve the use of feedback services.

  License


The first thing to do with push services is to get a push license. It is used to identify your communication with apns through SSL.


Generate an SSL license for Apple push notification on Mac:

  1. Log on to the iPhone developer connection portal and click app IDs.
  2. Create an app ID that does not use wildcards. The wildcard ID cannot be used for the push notification service. For example, our iPhone program id is like this: ab123127cd.com. serverdensity. iPhone
  3. Click "Configure" next to the app ID, and then press the button to generate the push notification license. Follow the steps in the Wizard to generate a signature, upload the signature, and finally download the generated license. This step is also described in the Apple documentation.
  4. Double-click the. Cer file to introduce your aps_developer_identity.cer to the keychain.
  5. Start the keychain assistant on Mac, and then select the certificates category in login keychain. You will see an extensible option "Apple development push services"
  6. Expand this option and right-click "Apple development push services"> export "Apple development push services id123 ". Save as a apns-dev-cert.p12 file.
  7. Extend Apple development push services to do the same for private key and save it as a apns-dev-key.p12 file.
  8. You need to use terminal commands to convert these files to the PEM format:
    OpenSSL PKCS12-clcerts-nokeys-out apns-dev-cert.pem-In apns-dev-cert.p12openssl PKCS12-nocerts-out apns-dev-key.pem-In apns-dev-key.p12
  9. If you want to remove the password, do not set or execute it during export/conversion:
    OpenSSL RSA-In apns-dev-key.pem-out apns-dev-key-noenc.pem
  10. Finally, you need to synthesize keys and license files into apns-dev.pem files that are used when connecting to apns:
    Cat apns-dev-cert.pem apns-dev-key-noenc.pem> apns-dev.pem


Save this file as an easy-to-remember name that you may use later. The above steps are also suitable for generating product licenses.

  Load content


The load is formatted in JSON format following RFC 4627 standard. It consists of the following parts:

    • Tip-text string displayed on the device
    • Identifier-the integer displayed on the program icon on the device Screen
    • Sound-display the text name of the sound that the message sends at the same time as the device
    • This tutorial only processes sending simple text strings, but also sends dictionary sets for various options, such as Displaying Custom buttons.
  Create Load


Using PHP, you can easily create loads based on arrays and convert them to JSON:

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


Show the $ payload content and you can see the content sentApnsJSON string:

 
{"APs": {"alert": "This is the alert text", "badge": 1, "sound": "default "}}


This will display the message on the device, trigger the raise sound and place "1" on the program icon. The default buttons "close" and "View" are displayed in the pop-up window.


For the server density iPhone program, it is very important for users to press "View" to directly access the server that generates this prompt, so we have added additional 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 );


When you press view, the custom server value is passed to the program on the device. The JSON value is as follows:

 
{"APs": {"alert": "This is the alert text", "badge": 1, "sound": "default"}, "server ": {"serverid": 1, "name": "server name ")}


The 256-byte limit applies to the entire load, including the custom dictionary set.

  Native Interface


In server density, once a prompt is generated, a load is created and inserted into the queue. Therefore, when necessary, we can send multiple loads at the same time.


This method is recommended for Apple, because if you frequently connect and disconnect when sending various loads, apns may block your IP address.

As described by Apple:

Native interfaces use native sockets, which have binary content and adopt data stream technology without feedback.

  Open connection


The PHP 5 code for opening the connection is as follows:

 
$ 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 );


If an error occurs, see $ errorstring. It also contains detailed information when the SSL license is incorrect.


The license file is in the current working directory of the executed PHP code. You can specify its absolute path if needed.

Note that the development license and sandbox should be used for testing. The finished host name is gateway.push.apple.com, and you must use different product licenses.

  Sending Load


Here, we cyclically send the entire load queue. A simple example of building binary content sent to apns is as follows:

 
$ Apnsmessage = CHR (0 ). CHR (0 ). CHR (32 ). pack ('H * ', str_replace ('','', $ devicetoken )). CHR (0 ). CHR (strlen ($ payload )). $ payload; fwrite ($ apns, $ apnsmessage );


Note that $ devicetoken is extracted from the database and spaces are removed. We should also check whether $ payload exceeds 256 bytes.


$ Apnsmessage includes the correct binary load, while fwrite writes the load to the currently active data stream connection.


After completion, close the connection:

 
Socket_close ($ apns); fclose ($ apns );

  

Php-apns


There is an open-source server library PHP-apns which implements all of the above functions and relies on memcached. We don't want to use any third-party code, so we have compiled our own servers. We use a custom cron system and run it once in seconds.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.