Push messages for IOS using php as push Server

Source: Internet
Author: User
Tags key string openssl x509 what openssl ssl certificate
Zxs19861202.iteye. comblog1532460IOS message push is a function provided by many IOS apps. Recently, this function is also being studied. I have finally finished it by referring to a lot of materials. I will share the steps below: iOS message Push mechanism can be simply used to summarize: Provider refers to the Push server of an iPhone software.

Http://zxs19861202.iteye.com/blog/1532460 IOS push message is a function that many IOS applications have recently studied this function, refer to a lot of information to finally get it done, the following steps are taken out to share: iOS message Push mechanism can be simply used to summarize: Provider refers to the Push server of an iPhone software.

Http://zxs19861202.iteye.com/blog/1532460


Pushing messages to IOS is a function available in many IOS apps. I have recently studied this function. I have finally finished it by referring to a lot of materials. I will share the steps below:

The working mechanism of iOS message push can be summarized as follows:


Provider refers to the Push server of an iPhone software. APNS is the abbreviation of Apple Push Notification Service and is the server of Apple.

There are three phases:

Phase 1: The application packs the message to be sent and the identifier of the target iPhone and sends it to APNS.

Stage 2: APNS searches for the iPhone with the corresponding identifier in its registered Push Service iPhone list and sends the message to the iPhone.

Stage 3: The iPhone transmits the sent message to the corresponding application, and a Push notification is displayed according to the settings.

We can see that:

1. The application registers for message push.

2. iOS obtains the device token from the APNS Server, and the application receives the device token.

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

4. The server program sends a message to the APNS service.

5. The APNS Service sends messages to the iPhone application.

Both the iPhone client and APNS, Provider and APNS, must be connected through a certificate.

Below I will introduce several certificates used.

1. CSR File

1. Generate a Certificate Signing Request (CSR)


2. Enter your email address and common name, and save it to the hard disk.


Click to continue:


In this way, a Push. certSigningRequest file is generated in the response.

Ii. p12 files

1. Export the key.



2. enter your password.

In this way, a Push. p12 file is generated.

Iii. SSL certificate file

1. log on to the iOS Provisioning Portal with the account you paid, and create an App ID. For details about this process, refer to debugging the iOS App's real machine, this will generate the following record:


2. Click Configure on the right:


3. Click the Configure next to the SSL Certificate row pushed by Development:

4. Click "Continue:


5. Select the previously generated Push. certSigningRequest file and click Generate. The following page is displayed:


6. Click "Continue:


7. Click Download and name the file aps_developer_identity.cer.

8. Click Done and you will find that the status has changed to Enabled:


So far, we have generated three files:

1. Push. certSigningRequest

2. Push. p12

3. aps_developer_identity.cer

Double-click aps_developer_dientity.cer and register it with your key string.


2. Prepare the profile certificate. Because the PUSH message can only be tested on a real machine, you must create a profile certificate.



Click "new profile" to create a profile for the newly created app id. Then, download * _ Dev_Profile.mobileprovision.

Double-click to add it to xcode's Provisioning Profiles. Note that if you add this file to xcode before, you must delete the previously added files, if there are multiple errors.

Iii. Engineering Code

Now the certificate is ready. Next, create a test project in xcode. Note that the Bundle Identifier of the project must be the same as the one in the app id created above.


Add the code to didfinishlaunchingwitexceptions.

-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions

{

[Self. window makeKeyAndVisible];

[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | uiremotenotiftypetypesound | UIRemoteNotificationTypeAlert];

Return YES;

}

-(Void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) pToken {


NSLog (@ "regisger success: % @", pToken );

// Register successfully. Save the deviceToken to the Application Server database.

}


-(Void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {

// Process push messages

UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "notification" message: @ "My information" delegate: selfcancelButtonTitle: @ "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 here, we can run it on the real machine. After successful registration, we will get the deviceToken of the iphone,

My token is:

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

4. Use php to push messages to APNS on the application server,

1. the php connection to APNS also requires a certificate. Do you still remember the certificates we obtained above? Open the terminal and process the above certificate as follows,

Cd to enter the certificate directory

Convert the. cer file to a. pem file:

$ Openssl x509-in aps_developer_identity.cer-inform der

-Out PushChatCert. pem

Convert the private key Push. p12 file to the. pem file:

$ Openssl pkcs12-nocerts-out PushChatKey. pem-in Push. p12

Enter Import Password:

MAC verified OK

Enter PEM pass phrase:

Verifying-Enter PEM pass phrase:

First, enter the passphrase phrase for the. p12 file so that OpenSSL can read it. Then you need to enter a new phrase to encrypt the PEM file. Or use "pushchat" as the PEM password phrase. You need to select some safer password phrases.

Note: If you do not type a pem passphrase, OpenSSL will not return an error message, but the generated. pem file will not contain a private key.

Last. Integrate the private key and certificate into A. pem file:

$ Cat PushChatCert. pem PushChatKey. pem> ck. pem

To test whether the certificate works, run 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 try to send a rule that is not encrypted to connect to the APNS service. If you see the above feedback, it means that your MAC can reach APNS. Press Ctrl + C to close the connection. If you get an error message, make sure that your firewall allows port 2195.

Then connect again. This time, we use our SSL Certificate and private key to set 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 will see a complete output, let 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 will be disconnected. If there is a problem when establishing a connection, OpenSSL will give you an error message,

The ck. pem file is the file for connecting php to APNS. Put ck. pem and push. php in the same directory and upload them to the server. The code for pushing. php is as follows:


// Here is the deviceToken we obtained 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 the correct publishing address.

// $ Fp = stream_socket_client ("ssl: // gateway.push.apple.com: 2195", $ err, $ errstr, 60, // STREAM_CLIENT_CONNECT, $ ctx );

// This is the sandbox test address. Remember to modify it after publishing it to the appstore.

$ Fp = stream_socket_client (

'Ssl: // gateway.sandbox.push.apple.com: 8080', $ err,

$ Errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ ctx );


If (! $ Fp)

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


Echo 'connectedto 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 will access http: // localhost/push. php


The iphone will receive a push message. If there is any problem, check the above operation steps, especially the red part.

In addition, the method for removing the tag is to add it to viewDidApper.

Int badge = [UIApplication sharedApplication]. applicationIconBadgeNumber;

If (badge> 0)

{

Badge --;

[UIApplication sharedApplication]. applicationIconBadgeNumber = badge;

}

Give a reference address: http://article.ityran.com/archives/194

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.