使用 api 请求发送 .pfx 文件

Send .pfx file with the api request

这是我第一次从事如此复杂的工作。我正在开发一个项目,其中提供 API 的服务请求使用证书进行身份验证。证书在 .pfx 文件中。

下面是我目前正在使用的代码

$url = 'https://api.example.com/sign';
$json = '{  
    "DateAndTimeOfIssue":"2017-08-31T13:28:02.433Z",
    "CashierName":"John",
    "TransType":"Sale",
    "PaymentType":"Card",
    "InvoiceNumber":"31082017-2",
    "ReferentDocumentNumber":null,
    "PAC":"KJ9UG3"
 }';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLCERT, dirname(__FILE__) . '/cert/9SSZJACN.pfx');
curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'KJ9UG3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_POST, True);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
if( !$result ){
    echo "Curl Error: " . curl_error($ch);
} else {
    echo "Success: ". $result;
}
curl_close($ch);

使用上面的代码,我收到了错误消息

Curl Error: could not load PEM client certificate, OpenSSL error error:0906D06C:PEM routines:PEM_read_bio:no start line, (no key found, wrong pass phrase, or wrong file format?)

我已经使用 Postman 测试了请求,一切正常。请告诉我我做错了什么。

您需要将文件转换为 PEM 文件:

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

Converting pfx to pem using openssl