MichaelAmato MichaelAmato - 5 months ago 83
PHP Question

How to authenticate with Woocommerce API using HTTPS (Basic Auth)

I am using the WooCommerce-REST-API-Client-Library-v2 and attempting a simple get orders call. I have no problem establishing a connection to my test server over http, but when I attempt to connect to a production server using https I receive an Invalid JSON returned error in the response. Secure checkout is enabled in woocommerce settings. I have tried with and without base64_encoding the credentials. Can someone please tell me what I am doing wrong or provide an example of the proper formatting to authenticate over HTTPS using WooCommerce-REST-API-Client-Library-v2. Here is my code. Thanks!

$consumer_key = base64_encode('ck_removed'); // Add your own Consumer Key here
$consumer_secret = base64_encode('cs_removed'); // Add your own Consumer Secret here
$store_url = 'https://removed.co.uk'; // Add the home URL to the store you want to connect to here
$is_ssl= TRUE;

try {
$client = new WC_API_Client( $consumer_key, $consumer_secret, $store_url);
// Get WC Orders Request
$orders=$client->orders->get();
$orders=$orders['orders'];
} catch ( WC_API_Client_Exception $e ) {
echo $e->getMessage() . PHP_EOL;
echo $e->getCode() . PHP_EOL;
if ( $e instanceof WC_API_Client_HTTP_Exception ) {
print_r( $e->get_request() );
print_r( $e->get_response() );
}
}

Answer

If there is the HTTP Status Code: 301 Moved Permanently, then the endpoint you are trying to reach is not SSL/TLS-enabled. So change the host from HTTPS to HTTP and you will be done. However, If the endpoint is SSL/TLS-enabled, you can use Key-Based(Public Key, Private Key) Basic Authentication. On SSL/TLS-enabled endpoint, OAuth does not work. Good Luck!

$options = array(
    'debug'           => true,
    'return_as_array' => false,
    'validate_url'    => false,
    'timeout'         => 30,
    'ssl_verify'      => false
);

try {
    $client = new WC_API_Client( $http_store_url, $consumer_key $consumer_secret, $options );
    $orders=$client->orders->get();
    print_r($orders);
} catch ( WC_API_Client_Exception $e ) {
   echo $e->getMessage() . PHP_EOL;
   echo $e->getCode() . PHP_EOL;
   if ( $e instanceof WC_API_Client_HTTP_Exception ) {
        print_r( $e->get_request() );
        print_r( $e->get_response() );
   }
}