iOS message push certificate generation and push messages

Source: Internet
Author: User
Tags openssl x509 what openssl ssl certificate

The working mechanism of iOS message push can be simply summed up:

Provider refers to the push server for an iphone application, APNs is the Apple push Notification service abbreviation and is the MAC server.

Can be divided into three stages:

Phase one: The application packages the message to be sent, the identity of the iphone, and sends it to APNS.

Phase II: APNs in its own list of iphone's registered push services, look for an iphone with a corresponding identity and send the message to the iphone.

The third stage: The iphone sends the message to the appropriate application and follows the settings to eject the push notification.

From what we can see:

1. Application registration message push.

2. iOS obtains device token from APNs server and the application receives device token.

3. The application sends device token to the push server program.

4. The service-side program sends messages to the APNS service.

5. The APNs service sends the message to the iphone app.

Both the iphone client and APNs, provider and APNs, need to be connected via a certificate.

Let me introduce some of the certificates used.

I. CSR documents

1. Generate Certificate Signing Request (CSR)

2, fill in your mailbox and common name, and choose to save to the hard disk.

Click Continue:

This generates a Certificatesigningrequest.certsigningrequest file locally.

Ii.. P12 Documents

1. Export the key.

2. Enter your password.

This generates a PUSH.P12 file.

Third, SSL certificate file

1. Log in to iOS Provisioning Portal with your paid account number and create a new app ID (you'll need to select Push notificationswhen creating) and click on the app ID to generate the following record:

2. Click Edit

3. Click Create Certificate ... :

4, click Continue, select the previous generated good certificatesigningrequest.certsigningrequest file, click Generate:

7. Click Download, and name the file aps_development.cer.

8. Click Done and you will notice that the status becomes enabled:

So far, we have generated three files:

1, Certificatesigningrequest.certsigningrequest

2, PUSH.P12

3, Aps_development.cer

Double-click Aps_developer_dientity.cer to register in your keychain, so your keychain will have

Second, prepare the profile certificate, because the push message can only be tested on the real machine, so to build a profile certificate

Click "New Profile" to create a profile for the new app ID above and download *_dev_profile.mobileprovision after successful

Double-click to add it to Xcode's provisioning Profiles, here's one thing to note, before adding this to Xcode, if you've already joined before, make sure to delete the previous addition, and if there are more than one, it will go wrong.

Third, the project code

Here the certificate is ready, Next, we create a new test project in Xcode, note that the bundle identifier of the project must be the same as the app ID built above

Add code to Didfinishlaunchingwithoptions

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions

{

[Self.window makekeyandvisible];

[[uiapplication sharedapplication] registerforremotenotificationtypes:uiremotenotificationtypebadge | Uiremotenotificationtypesound | Uiremotenotificationtypealert];

return YES;

}

-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) PToken {

NSLog (@ "Regisger success:%@", PToken);

Successful registration, saving Devicetoken to the application server database

}

-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) userInfo{

Handling Push messages

Uialertview *alert=[[uialertview alloc]initwithtitle:@ "notice" message:@ "My Info" delegate:self cancelbuttontitle:@ "Cancel" Otherbuttontitles:nil, nil];

[Alert show];

[Alert release];

NSLog (@ "%@", userInfo);

}

-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (NSError *) error {

NSLog (@ "Regist fail%@", error);

}

If everything goes well, we'll be able to run it on the real machine, and we'll get the iphone devicetoken.

My token is:

<740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad>

Four, the application server in the way of PHP to push the message to APNs,

1, PHP connection APNs also need a certificate, remember how many of the certificates we obtained? Open the terminal, the above certificate to do the following processing,

CD into the directory where the certificate is located

Convert. cer files to. pem Files:

$ OpenSSL x509-in Aps_developer_identity.cer-inform der -out Pushchatcert.pem

Convert private key PUSH.P12 file to. pem file:

$ OpenSSL pkcs12-nocerts-out pushchatkey.pem-in PUSH.P12

Enter Import Password:

MAC verified OK

Enter PEM Pass phrase: (PHP Keys for reading time )

Verifying–enter PEM Pass phrase: ( Confirm Key )

You first need to enter the passphrase passphrase for the. p12 file so that OpenSSL can read it. Then you need to type a new passphrase to encrypt the Pem file. or use "Pushchat" as the passphrase for the PEM. You need to choose some more secure passphrase.

Note: If you do not type a PEM Passphrase,openssl will not return an error message, but the resulting. pem file will not contain the private key.

At last. Integrate the private key and certificate into a. Pem file:

$ cat Pushchatcert.pem Pushchatkey.pem > Ck.pem

To test whether the certificate is working, execute the following command :

$ telnet gateway.sandbox.push.apple.com 2195

Trying 17.172.232.226 ...

Connected to Gateway.sandbox.push-apple.com.akadns.net.

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 gateway.sandbox.push.apple.com:2195 -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 establishing the connection, OpenSSL will give you an error message,

Ck.pem file is that we need to get PHP connection APNs file, Ck.pem and push.php into the same directory to the server, push.php code as follows:

<?php

Here is the devicetoken we got above, copy it directly (remember to remove the space).

$deviceToken = '740f4707bebcf74f 9b7c25d4 8e3358945f6aa01da5ddb387462c7eaf 61bb78ad';

Put your private key ' s passphrase here:

$passphrase = ' abc123456 ';

Put your alert message here:

$message = ' My first push test! ';

////////////////////////////////////////////////////////////////////////////////

$ctx = Stream_context_create ();

Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Ck.pem ');

Stream_context_set_option ($ctx, ' SSL ', ' passphrase ', $passphrase);

Open a connection to the APNS server

This is exactly the address of the publication

$fp = Stream_socket_client ("ssl://gateway.push.apple.com:2195", $err, $errstr, A,//stream_client_connect, $ctx);

This is the sandbox test address, after posting to AppStore remember to modify OH

$fp = Stream_socket_client (

' ssl://gateway.sandbox.push.apple.com:2195 ', $err,

$errstr, stream_client_connect|. Stream_client_persistent, $ctx);

if (! $fp)

Exit ("Failed to connect: $err $errstr". PHP_EOL);

Echo ' Connected to APNS '. Php_eol;

Create the payload body

$body [' aps '] = Array (

' Alert ' = $message,

' Sound ' = ' default '

);

Encode the payload as JSON

$payload = Json_encode ($body);

Build the binary notification

$msg = Chr (0). Pack (' n ', 32). Pack (' h* ', $deviceToken). Pack (' n ', strlen ($payload)). $payload;

Send it to the server

$result = fwrite ($fp, $msg, strlen ($msg));

if (! $result)

Echo ' Message not delivered '. Php_eol;

Else

Echo ' Message successfully delivered '. Php_eol;

Close the connection to the server

Fclose ($FP);

?>

Next we visit http://localhost/push/push.php

iphone will receive a push message, if there is a problem, check the above procedure, especially the accents part

In addition, the method of removing marks is to add in Viewdidapper

int badge = [UIApplication sharedapplication].applicationiconbadgenumber;

if (Badge > 0)

{

badge--;

[UIApplication sharedapplication].applicationiconbadgenumber = badge;

}

Original address: http://www.cnblogs.com/riasky/p/3469143.html

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.