Search code examples
phpcurlcertificatepfx

Send .pfx file with the api request


This is my first time working on something this complex. I'm working on a project where the service that provides the API requests authentication using certificate. The certificate is in .pfx file.

Below is the code that's I'm currently working with

$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);

With the above code, I'm getting the error message

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?)

I have test the request using Postman and everything works great. Please advise what am I doing wrong over here.


Solution

  • You need convert your file to a PEM file:

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

    see Converting pfx to pem using openssl