PHP Apple Push Implementation (APNS)

Source: Internet
Author: User
Tags openssl rsa pkcs12 what openssl ssl certificate

The following information is collected and collated online

1, in iOS Dev Center to produce relevant certificates and files with the client implementation (no longer repeat, many online,)
Online Tutorials:
Official documents: Provisioningdevelopment/provisioningdevelopment.html#//apple_ref/doc/uid/tp40008194-ch104-sw1

2, after the production of download down, double-click Import. Then find the certificate you just imported at the keychain access, expand to see the key, check the certificate, export the. p12 file, because PHP is not good at processing this format, so convert it to a. pem file, as follows, in the terminal execution:
OpenSSL pkcs12-in certificatenamep12-out certificatename. Pem-nodes (drag tragedy into the terminal to avoid writing paths), Make a production,development certificate separately

4, the server, create a test file apns.php, and put certificatename. PEM in the same directory,
Official address:, Port 2195 (using official certificate)
Test address:, Port 2195 (using test certificate)

Received token from the device, which I filled in manually. $deviceToken = "015c5a2377ac146830f8ed09059b82bb91ed7190ebf74b633809bc2245da95ee";//Construct message body $body = Array ("APS" = Array ("alert" = "test test test", "badge" = 1, "sound" = ' received5.caf ')); $ctx = Stream_context_create (); STREAM_ Context_set_option ($ctx, "SSL", "Local_cert", "Certificatename.pem");//Establish socket connection $fp = Stream_socket_client ("ssl:// ", $err, $errstr, Stream_client_connect, $ctx); if (! $fp) {print" Failed to Connec T $err $errstrn "; Return }print "Connection OK"; $payload = Json_encode ($body); $msg = chr (0). Pack ("n", 32). Pack ("h*", $deviceToken). Pack ("n", strlen ($payload)). $payload;p rint "Sending message:". $payload. "\ n"; fwrite ($fp, $msg); fclose ($FP);

5. Server Feedback
When the user deletes our app, we should stop pushing this machine, this SSL address is:
Official machine:, Port 2196
Test machine:, Port 2196

A view of the body Communicatingwithaps/communicatingwithaps.html

PHP is as follows:

$certFile = ' Apns-dev.pem '; while (true) {$ctx = Stream_context_create (); Stream_context_set_option ($ctx, ' SSL ', ' Local_ Cert ', $certFile);//stream_context_set_option ($ctx, ' SSL ', ' Passphrase ', $this->certpass); Echo "Try to open stream\ n "; $fp = stream_socket_client (' ssl:// ', $err, $errstr, 5, Stream_client_connect, $CTX), if (! $fp) {print "Failed to connect". $err. $errstr. "\ n"; exit ();} Else{echo ' Connected to feedback sandbox ... '; while (($in = Fread ($fp, 1024x768))! = EOF) {echo ' read ' $in. "\ n";} Socket_close ($FP); fclose ($FP);} Sleep (2000);}

Note that you will not be able to return data until you delete your app and then send a push.

Development status Server address 2195
Product Status Server address

The APNS device token for the development and production two versions is different, the former is develop.obtained under the mobileprovision. The latter is obtained by the mobileprovision of production.
Two versions of development and productionYou can share an app ID (not recommended. Before each debug, remove the app on the device and repackage the build. And the public AppID will often be crazy, early upstream, the afternoon will not be. So not recommended), butCan't share a mobileprovision, the distribution certificate is generated separately for use by the production version.
Note: Distribution version is unable to debug on the device debug!
Development and production two versions of code sign are different, the former isiphone Developer, the latter is the iphone distribution. Be careful not to be mistaken.

Either the development push sslcertificate or the production push SSL Certificate have an expiration time. Development Push SSL Certificatevalid for approx .Four monthsabout, whileProductionpush SSL Certificateis valid forOne year. It is important to note that a new certificate is generated before it expires to avoid impact.

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-CERT.P12
OpenSSL rsa-in apns-dev-key.pem-out Apns-dev-key-noenc.pem
Cat Apns-dev-cert.pem Apns-dev-key-noenc.pem > Apns-dev.pem

Generate an Apple push notification SSL license on your Mac:
1.Sign in to IPhone Developer Connection Portal and click App IDs
2.Create an App ID that does not use a wildcard character. Wildcard IDs cannot be used with push Notification Services. For example, our iphone program ID looks like
3.Click "Configure" next to the app ID and press the button to produce the push notification license. Generate a signature and upload according to the steps guided by the wizard, and finally download the generated license. This step is also mentioned in the Apple documentation.
4.Introduce your aps_developer_identity.cer into the keychain by double-clicking the. cer file.
5.Start the Keychain assistant on your 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 then right-click Apple Development Push Services > Export Apple Development Push services ID123. Save as APNS-DEV-CERT.P12 file.
7.Expand Apple Development Push Services to do the same for Private Key and save as APNS-DEV-KEY.P12 file.
8.These files need to be converted to PEM format via terminal commands:
OpenSSL pkcs12-clcerts-nokeys-out apns-dev-cert.pem-in APNS-DEV-CERT.P12
9. Convert the PEM that gets key:
OpenSSL pkcs12-nocerts-out apns-dev-key.pem-in APNS-DEV-CERT.P12
If you want to remove the password, either do not set or execute it when exporting/converting:
OpenSSL rsa-in apns-dev-key.pem-out Apns-dev-key-noenc.pem
Finally, you need to synthesize the keys and license files into a APNS-DEV.PEM file, which you need to use 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 might use later. The above steps are also appropriate for generating product licenses.

How to verify that the certificate is correct:

$ telnet 2195

Trying ...

Connected to

Escape character is ' ^] '.

It will attempt to send a regular, unencrypted connection to the APNS service. If you see the feedback above, it means that your Mac can reach APNS. Press CTRL + C to close the connection. If you get an error message, then you need to make sure that your firewall allows port 2195.

Then connect again, this time using our SSL certificate and private key to set up a secure connection:

$ OpenSSL s_client-connect

-cert Pushchatcert.pem-key Pushchatkey.pem

Enter Pass phrase for PUSHCHATKEY.PEM:

You'll see a complete output that lets you understand what OpenSSL is doing in the background. If the connection is successful, you can type some characters. When you press ENTER, the service disconnects. If there is a problem setting up the connection, OpenSSL will give you an error message, but you'll have to flip the output log up to find it.

Of course, the above to test the prodution version is correct, the replaced with is good.

The client is doing well, applying for a certificate, copying the code, on the line.
Server side, if it is PHP, that must use the. PEM certificate, if it is Java, that must use the. P12 certificate. (You may also need to double-click the certificate to install!) )
The JSON packets emitted by the server are size-limited, with a maximum of 256 bytes, including a custom dictionary set.
The alert string in APS can be added "\ n" for line breaks.
In addition to Alert,badge,sound in the JSON package, it is possible to customize the value.

Extra 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 the user presses "View", the custom server value is passed to the program on the device. The JSON values are as follows:
"Action-loc-key": "Show",
"Body": "This is the alert text"
"Badge": 1,
"Sound": "Default"},
"Server": {"ServerID": 1, "name": "Server Name")
The 256-byte limit applies to the entire payload, including the custom dictionary set.

Native Interface
In server density, once a hint is generated, a payload is created and inserted into the queue. So we can send multiple payload at the same time if it is necessary.
Apple recommends this approach, because if you are frequently connected and disconnected when you send each payload,APNSIt is possible to block your IP.
As described by Apple:
The native interface uses the native socket, has binary content, and uses data stream technology to generate no feedback.

Summary of the Tall man:
Apple Push Notification Service tutorial PART-1
Apple Push Notification Service tutorial PART-2
Apple Push Notification Service tutorial PART-3
APNs PHP Version:

Before IOS7, Apple generated the same devicetoken for multiple apps on a device.
IOS7 and later, Apple generates different devicetoken for multiple apps on a device.
This new change led to the creation of a new old token mapping table on APNs, if you have been using the old token, that's fine, but once the server uses the new Devicetoken, the records in the mapping table are deleted, which means that the old Devicetoken can't be used, Must send failed.
To be verified: IOS5 and Ios6,app can always get devicetoken, in addition to the system, if the user refused, or shut down the push, then can not get devicetoken, go failure callback.
Original source:

There are a few things to note about generating certificates:
The Apple developer account has several different roles
Agent: The agent, with the highest privileges, can access itunes Connect.
Admin: admin, manage members, maintain list of devices, maintain AppID and certificate list permissions.
Member: Normal member, read-only permission.

Note: 3013.9.11 After testing, I found that the previous period of time the Apple website was updated during the process of the certificate generation mechanism. Previously, using a keychain to generate a CSR file can be used all the time. However, now every time you want to generate a certificate, do generate need to regenerate a CSR file in advance, otherwise you generate the certificate is not valid, false certificate, especially push, the service side use this kind of certificate can not and APNs establish connection, this kind of weird problem is extremely difficult to track! Hope to see this passage of people can avoid detours, no thanks!

Problems are also encountered in the use of Pushmebaby. First, although the public key certificate for. CER is already used in the project, a certificate with a private key must be in the local keychain, or the connection cannot be successfully established. It is also important to note that certificates are best placed in the "logon" group, or the program cannot find the private key. Second, the original project in the scanstring when the cycle will die, need to modify the following code:
Nsuinteger count = 0;
while (![ Scanner Isatend]) {
     [scanner scanhexint:&value];
         value = htonl (value);
         [devicetokendata appendbytes:&value length:sizeof (value)];
        if (++count >= [ Self.devicetoken length]-1) {

Related Article

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: 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.