准备材料:
“aps_development .cer” ,”push.p12”
接下来我们打开终端将他们生成.pem文件
1.把aps_development .cer文件生成.pcm文件,cd到push文件夹下
openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
2.把push.p12文件生成为.pem
openssl pkcs12 -nocerts -out PushChatkey.pem -in Push.p12
.把PushChatCert.pem和PushChatKey.pem合并为一个pem文件,
cat PushChatCert.pem PushChatKey.pem >ck.pem
以上我们把需要使用的文件都准备好了
使用
telnet gateway.sandbox.push.apple.com 2195
来检测一下,如果显示
Trying 17.188.165.216…
Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape character is ‘^]’.
则表示成功了。
然后,我们使用我们生成的证书和私钥来设置一个安全的链接去链接苹果服务器
在终端输入如下命令:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pem
需要输入密码
返回一系列的数据 …… Verify return code: 0 (ok) 说明OK了
iOS端
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token{
NSLog(@"---token--%@",token);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(@"userInfo == %@",userInfo);
NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];
[alert show];
}
php端
<?php
$deviceToken = 'iOS取出token的放在这里';
$passphrase = '自己设置密码';
$message = '推送的内容';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
//php和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);
//?????????????appstore??????
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, 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);
?>