Passing .pem and .key files in cURL doesn’t work in WordPress

I’m building a payment gateway plugin for woocommerce which requires sending an XML request via cURL, encrypted with private key.

I’m using the following code:

$xml_request="<?xml version="1.0" encoding="utf-8"?>";

$test_URL       = 'https://my-gateway.com';
// Here is where I change the file paths
$certfile="/clientcert.pem";
$keyfile="/clientkey.key";

$ch = curl_init();

curl_setopt( $ch, CURLOPT_URL, $test_URL );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); 
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_SSLCERT, getcwd() . $certfile );
curl_setopt( $ch, CURLOPT_SSLKEY, getcwd() . $keyfile );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: text/xml' ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $xml_request );
$ch_result = curl_exec( $ch );


// Check for errors
if ( curl_errno($ch) ) {
    $ch_result="cURL ERROR -> " . curl_errno($ch) . ': ' . curl_error($ch);
} else {
    $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    switch($returnCode){
        case 200:
            break;
        default:
            $ch_result="HTTP ERROR -> " . $returnCode;
            break;
    }
}

curl_close( $ch );

echo $ch_result;

The problem is that curl can’t find the certificate or key files no matter what path I use – I’ve tried absolute, and relative paths.
I’ve changed the .pem and .key file locations (tried theme directory, plugin directory, and root).
I’ve changed permissions to full.

But still I get the error
58: unable to use client certificate (no key found or wrong pass phrase?)

Which means the file is not found or corrupt, while I’m sure it isn’t, since when I copy this code to a php file outside WordPress and run it, it works.

I can overcome this issue by redirecting the user to a page outside WordPress, but I’d prefer to run it all from one place.
How can this be done?

1 Answer
1

Based on @Mamaduka comment; the following changes resolve it:

Use plugin_dir_path() to get the filesystem directory path:

$certfile = plugin_dir_path(__FILE__) . '/clientcert.pem';
$keyfile = plugin_dir_path(__FILE__) . '/clientkey.key';

Then remove getcwd().

If you want to use it in your theme use TEMPLATEPATH

I also want to mention that using the following paths previously did not work:

WP_PLUGIN_URL . "https://wordpress.stackexchange.com/" . plugin_basename( dirname(__FILE__) ) . '/clientkey.key'

nor:

get_bloginfo('template_directory') . '/lib/cert/clientcert.pem'

nor:

'http://my-web-site.com/clientcert.pem'

Leave a Comment