標籤:
博主原來是一名PHPer,當轉向iOS後看到PHP感到格外的興奮。
目前有一個項目需要自己構建iOS推送的服務端代碼。於是搜尋了一下網上的代碼,帶式在執行的時候總是會報錯,錯誤為:
Warning: stream_socket_client(): SSL operation failed with code 1.
本以為是openssl沒有開啟或者產生的秘鑰ck.pem有問題。後來發現不是這些個問題。現在貼出正確的代碼,以備不時之需:
<?phpset_time_limit(0);sleep(5);// 這裡是我們上面得到的deviceToken,直接複製過來(記得去掉空格)$deviceToken = ‘f2f66dbc7e3477df31cb32e1d56903efeec73d904b603bab9ba5a72948e1023b‘;// Put your private key‘s passphrase here:$passphrase = ‘123456‘;// Put your alert message here:$message = ‘My first push test!‘;////////////////////////////////////////////////////////////////////////////////$ctx = stream_context_create();stream_context_set_option($ctx, ‘ssl‘, ‘allow_self_signed‘, true);stream_context_set_option($ctx, ‘ssl‘, ‘verify_peer‘, false);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);//這個是沙箱測試地址,發布到appstore後記得修改哦 $fp = stream_socket_client(‘ssl://gateway.sandbox.push.apple.com:2195‘, $err,$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);//$fp=stream_socket_client("udp://127.0.0.1:1113", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $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;elseecho ‘Message successfully delivered‘ . PHP_EOL;// Close the connection to the serverfclose($fp);?>
iOS Push服務端PHP代碼