1.打开mac的钥匙串,生成证书请求文件
2.登录Apple dev账号,编辑对应APP ID
点击创建证书,使用步骤1生成的证书请求创建推送证书,开发证书和推送证书可以用同一个证书请求生成证书
3.下载步骤2中生成的推送证书并导入到系统中
4.导出证书私钥,点击证书打开,导出对应的专用秘钥
设置私钥保护密码,这个密码一定要记住后面有用
5.转换证书格式
转换推送证书为pem格式(这里的推送证书是从苹果官网直接下载下来的证书)
openssl x509 -in aps.cer -inform der -out aps.pem
转换证书私钥为pem格式,这里需要输入三次秘钥,第一次为步骤4中导出私钥时设置的秘钥,第二和三次为pem设置私钥,这里设置的私钥需要保留
openssl pkcs12 -nocerts -out key.pem -in key.p12
合成证书
cat key.pem aps.pem > push.pem
6.验证证书
iOS的推送证书分为两种,开发证书和发布证书。开发证书用于平时测试用,只有导出的ipa文件为开发模式时才能使用;发布证书,需要导出的ipa文件为ad hoc模式,或者是发布到APP store中的安装包。
验证开发证书方式
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert dev_cert.pem -key dev_key.pem
验证发布证书的方式
openssl s_client -connect gateway.push.apple.com:2195 -cert aps.pem -key key.pem
以验证开发证书的方式示例。
输入如下内容说明证书验证通过
7.提交证书给服务器
最终提交给服务器的为步骤5中 生成的push.pem和转换私钥过程中新设置的秘钥。开发证书也是按照这个步骤来生成。
8.特别提示
过程中生成的 .p12文件记得保留,我们在其他Mac上使用一些推送测试工具时,不仅要导入推送证书还需要导入key.p12才能推送出消息。
9.验证证书的PHP代码
array( 'title' => "You have a notification", 'body' => "Body of the message", ), 'badge' => 1, 'sound' => 'default', ); // Create the payload body$ctx = stream_context_create();stream_context_set_option($ctx, 'ssl', 'local_cert', $pemfilename);stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);$fp = stream_socket_client( 'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // Open a connection to the APNS serverif (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL);echo 'Connected to APNS' . PHP_EOL;$payload = json_encode($body); // Encode the payload as JSON$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Build the binary notification$result = fwrite($fp, $msg, strlen($msg)); // Send it to the serverif (!$result) echo 'Message not delivered' . PHP_EOL;else echo 'Message successfully delivered' . PHP_EOL;fclose($fp); // Close the connection to the server?>