Push messages for IOS using php as push Server

Source: Internet
Author: User
Tags key string openssl x509 ssl certificate

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 your paid account and create an App ID. For details about this process, see:. The following record is generated:

 
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::
$ TelnetGateway.sandbox.push.apple.com2195
Trying 17.172.232.226...
ConnectedGateway.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-connectGateway.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 that OpenSSL is in the background
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:

<? Php

// 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

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

$ Fp = stream_socket_client (
'Ssl: // gateway. ', $ 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;
}

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