0

我正在嘗試爲Apple推送通知創建服務器端連接。 首先,我要求用戶(可能是一個ios開發人員)提供Apple提供的.cer和.p12文件,以使其成爲.pem文件。APNS證書.pem

以下是.pem證書的創建。

$dir = $this->directory.'/certificates'; 
$password = 'a_user_password'; 
$certificate = $dir.'/certificate.cer'; 
$key_password = $dir.'/key.p12'; 

exec('openssl x509 -inform der -in '.$certificate.' -out '.$dir.'/certificate.pem'); 
exec('openssl pkcs12 -nocerts -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password); 

$filename = $key_password; 
$results = array(); 
$worked = openssl_pkcs12_read(file_get_contents($filename), $results, $obj->password); 
if($worked) { 
    $current = file_get_contents($dir.'/key.pem'); 
    $current .= $results['pkey']; 
    file_put_contents($dir.'/key.pem', $current); 
} else { 
    echo openssl_error_string(); 
} 
exec('cat '.$dir.'/certificate.pem '.$dir.'/key.pem > '.$dir.'/apns_certificate.pem'); 

到目前爲止,這麼好。我已經測試,上述產生apns_certificate.pem成功與蘋果通過通過命令行:

s_client -connect gateway.sandbox.push.apple.com:2195 -cert certificate.pem -key key.pem 

然而, 當我嘗試與APNS連接通過PHP我不能。遵循我曾嘗試在過去的PHP代碼,我已經看到別人已經工作:

$this->certificate = ROOT.'/certificates/apns_certificate.pem'; 
$this->socket = 'ssl://gateway.push.apple.com:2195'; 
if (!file_exists($this->certificate)) { 
     $this->error = 'Certificate file not found'; 
     return false; 
    } 

    $this->stream_context = stream_context_create(); 
    $this->stream_options = array(
     'ssl' => array(
      'local_cert' => $this->certificate, 
      'passphrase' => 'a_user_password', //same with the one used in my previous code 
     ) 
    ); 
    $success = stream_context_set_option($this->stream_context, $this->stream_options); 
    if ($success == false) { 
     $this->error = 'Secure connection failed'; 
     return false; 
    } 

    $this->socket_client = stream_socket_client($this->socket, $con_error, $con_error_string, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context); 

    if ($this->socket_client === false) { 
     $this->error = $con_error_string; 
     return false; 
    } else { 
     return true; 
    } 

上面的代碼返回我一個錯誤: 警告:stream_socket_client():SSL操作失敗,代碼1. OpenSSL的錯誤消息:錯誤:14094416:SSL例程:SSL3_READ_BYTES:SSLV3警報證書未知 警告:stream_socket_client():無法連接到SSL://gateway.push.apple.com:2195

預先感謝您的幫助!

回答

0

上述代碼是正確的。認證.p12有錯誤。我也將.p12轉換文件的exec改爲:

exec('openssl pkcs12 -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password.' -nodes');