woocommerce migrated logging from logfile to logger

This commit is contained in:
OpenXE 2024-09-14 12:44:21 +02:00
parent d494778fad
commit 0b807455ca

View File

@ -16,10 +16,10 @@
use Xentral\Components\Http\JsonResponse; use Xentral\Components\Http\JsonResponse;
use Xentral\Modules\Onlineshop\Data\OrderStatus; use Xentral\Modules\Onlineshop\Data\OrderStatus;
use Xentral\Modules\Onlineshop\Data\OrderStatusUpdateRequest; use Xentral\Modules\Onlineshop\Data\OrderStatusUpdateRequest;
use Xentral\Components\Logger\Logger;
class Shopimporter_Woocommerce extends ShopimporterBase class Shopimporter_Woocommerce extends ShopimporterBase
{ {
// protected $canexport = false; // protected $canexport = false;
public $intern = false; public $intern = false;
@ -55,16 +55,17 @@ class Shopimporter_Woocommerce extends ShopimporterBase
*/ */
protected $app; protected $app;
protected $dump; protected $dump;
/** @var Logger $logger */
public $logger;
public function __construct($app, $intern = false) public function __construct($app, $intern = false)
{ {
$this->app=$app; $this->app=$app;
$this->intern = true; $this->intern = true;
$this->logger = $app->Container->get('Logger');
} }
public function ImportList() public function ImportList()
{ {
$msg = $this->app->erp->base64_url_encode('<div class="info">Sie k&ouml;nnen hier die Shops einstellen</div>'); $msg = $this->app->erp->base64_url_encode('<div class="info">Sie k&ouml;nnen hier die Shops einstellen</div>');
@ -72,8 +73,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
exit; exit;
} }
/** /**
* This function returns the number of orders which have not yet been imported * This function returns the number of orders which have not yet been imported
*/ */
@ -83,7 +82,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
// We set per_page to 100 - this could lead to a situation where there are more than // We set per_page to 100 - this could lead to a situation where there are more than
// 100 new Orders, but we still only return 100. // 100 new Orders, but we still only return 100.
// Array containing additional settings, namely 'ab_nummer' (containting the next order number to get) // Array containing additional settings, namely 'ab_nummer' (containting the next order number to get)
// and 'holeallestati' (an integer) // and 'holeallestati' (an integer)
$tmp = $this->CatchRemoteCommand('data'); $tmp = $this->CatchRemoteCommand('data');
@ -97,7 +95,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
if ($number_from) { if ($number_from) {
// Number-based import is selected // Number-based import is selected
// The WooCommerce API doenst allow for a proper "greater than id n" request. // The WooCommerce API doenst allow for a proper "greater than id n" request.
// we fake this behavior by creating an array that contains 'many' (~ 1000) consecutive // we fake this behavior by creating an array that contains 'many' (~ 1000) consecutive
// ids that are greater than $from_number and use this array with the 'include' property // ids that are greater than $from_number and use this array with the 'include' property
@ -115,7 +112,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
'include' => implode(",",$fakeGreaterThanIds), 'include' => implode(",",$fakeGreaterThanIds),
]); ]);
} else { } else {
// fetch posts by status // fetch posts by status
@ -129,7 +125,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return (!empty($pendingOrders)?count($pendingOrders):0); return (!empty($pendingOrders)?count($pendingOrders):0);
} }
/** /**
* Calling this function queries the api for pending orders and returns them * Calling this function queries the api for pending orders and returns them
* as an array. * as an array.
@ -141,7 +136,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
*/ */
public function ImportGetAuftrag() public function ImportGetAuftrag()
{ {
// Array containing additional settings, namely 'ab_nummer' (containting the next order number to get) // Array containing additional settings, namely 'ab_nummer' (containting the next order number to get)
// and 'holeallestati' (an integer) // and 'holeallestati' (an integer)
$tmp = $this->CatchRemoteCommand('data'); $tmp = $this->CatchRemoteCommand('data');
@ -155,7 +149,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
if ($number_from) { if ($number_from) {
// Number-based import is selected // Number-based import is selected
// The WooCommerce API doenst allow for a proper "greater than id n" request. // The WooCommerce API doenst allow for a proper "greater than id n" request.
// we fake this behavior by creating an array that contains 'many' (~ 1000) consecutive // we fake this behavior by creating an array that contains 'many' (~ 1000) consecutive
// ids that are greater than $from_number and use this array with the 'include' property // ids that are greater than $from_number and use this array with the 'include' property
@ -175,7 +168,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
'orderby' => 'id' 'orderby' => 'id'
]); ]);
} else { } else {
// fetch posts by status // fetch posts by status
@ -188,7 +180,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
// Return an empty array in case there are no orders to import // Return an empty array in case there are no orders to import
if ((!empty($pendingOrders)?count($pendingOrders):0) === 0) { if ((!empty($pendingOrders)?count($pendingOrders):0) === 0) {
return null; return null;
@ -214,10 +205,8 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return $tmp; return $tmp;
} }
// This function searches the wcOrder for the specified WC Meta key // This function searches the wcOrder for the specified WC Meta key
// and returns it if found, null otherise // and returns it if found, null otherise
public function get_wc_meta($wcOrder, $meta_key) { public function get_wc_meta($wcOrder, $meta_key) {
@ -231,15 +220,11 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return $value; return $value;
} }
// Parse the given WooCommerce order, return a Xentral array-represented order. // Parse the given WooCommerce order, return a Xentral array-represented order.
// Overload this method whenever additional attributes are required. // Overload this method whenever additional attributes are required.
public function parseOrder($wcOrder) { public function parseOrder($wcOrder) {
$order = array(); $order = array();
$order['auftragsdaten'] = $wcOrder; $order['auftragsdaten'] = $wcOrder;
@ -273,7 +258,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
} }
if(!empty($wcOrder->subshop)){ if(!empty($wcOrder->subshop)){
$order['subshop'] = $wcOrder->subshop; $order['subshop'] = $wcOrder->subshop;
} }
@ -302,7 +286,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
// //
// //
// Coupon Codes // Coupon Codes
// //
@ -333,7 +316,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$seperateShippingAddress = !self::compareObjects( $seperateShippingAddress = !self::compareObjects(
$wcOrder->billing, $wcOrder->billing,
$wcOrder->shipping, $wcOrder->shipping,
@ -360,7 +342,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$order['lieferadresse_land'] = $wcOrder->shipping->country; $order['lieferadresse_land'] = $wcOrder->shipping->country;
} }
// VAT stuff // VAT stuff
$vatId = $this->get_wc_meta($wcOrder, "_billing_ustid"); $vatId = $this->get_wc_meta($wcOrder, "_billing_ustid");
@ -375,7 +356,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$order['zahlungsweise'] = $wcOrder->payment_method; $order['zahlungsweise'] = $wcOrder->payment_method;
$order['lieferung'] = $wcOrder->shipping_lines[0]->method_id; $order['lieferung'] = $wcOrder->shipping_lines[0]->method_id;
return $order; return $order;
} }
@ -417,7 +397,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return $orderItem; return $orderItem;
} }
/** /**
* Sets the Order status to processing, meaning we've successfully imported * Sets the Order status to processing, meaning we've successfully imported
* the order into our DB. This prevents the order from beeing imported again. * the order into our DB. This prevents the order from beeing imported again.
@ -432,7 +411,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
]); ]);
} }
return 'ok'; return 'ok';
} }
@ -455,7 +433,13 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$this->client->post('orders/'.$data->orderId.'/notes', [ $this->client->post('orders/'.$data->orderId.'/notes', [
'note' => 'Tracking Code: ' . $trackingCode 'note' => 'Tracking Code: ' . $trackingCode
]); ]);
$this->WooCommerceLog("Tracking Code Rückmeldung für Auftrag: $data->orderId", $trackingCode);
$this->logger->info("WooCommerce Tracking Code Rückmeldung für Auftrag: ".$data->orderId,
[
'orderId' => $data->orderId,
'trackingCode' => $trackingCode
]
);
} }
$updateData = [ $updateData = [
@ -472,12 +456,16 @@ class Shopimporter_Woocommerce extends ShopimporterBase
], ],
]; ];
$this->client->put('orders/'.$data->orderId, $updateData); $this->client->put('orders/'.$data->orderId, $updateData);
$this->WooCommerceLog("Statusrückmeldung 'completed' für Auftrag: $data->orderId", $this->statusCompleted );
$this->logger->info("WooCommerce Statusrückmeldung 'completed' für Auftrag: ".$data->orderId,
[
'orderId' => $data->orderId,
'status' => $this->statusCompleted
]
);
return 'ok'; return 'ok';
} }
/** /**
* This function syncs the current stock to the remote WooCommerce shop * This function syncs the current stock to the remote WooCommerce shop
* @return int * @return int
@ -524,8 +512,8 @@ class Shopimporter_Woocommerce extends ShopimporterBase
if (empty($remoteIdInformation['id'])) { if (empty($remoteIdInformation['id'])) {
// The online shop doesnt know this article, write to log and continue with next product // The online shop doesnt know this article, write to log and continue with next product
$this->WooCommerceLog("Artikel $nummer wurde im Online-Shop nicht gefunden! Falsche Artikelnummer im Shop hinterlegt?");
$this->logger->error("WooCommerce Artikel $nummer wurde im Online-Shop nicht gefunden! Falsche Artikelnummer im Shop hinterlegt?");
continue; continue;
} }
@ -541,21 +529,19 @@ class Shopimporter_Woocommerce extends ShopimporterBase
}else{ }else{
$result = $this->client->put('products/' . $remoteIdInformation['id'], $updateProductParams); $result = $this->client->put('products/' . $remoteIdInformation['id'], $updateProductParams);
} }
$this->WooCommerceLog("WooCommerce Lagerzahlenübertragung für Artikel: $nummer / $remoteIdInformation[id] - Anzahl: $lageranzahl", $result);
$this->logger->error("WooCommerce Lagerzahlenübertragung für Artikel: $nummer / $remoteIdInformation[id] - Anzahl: $lageranzahl",
[
'result' => $result
]
);
$anzahl++; $anzahl++;
} }
return $anzahl; return $anzahl;
} }
public function ImportStorniereAuftrag() { public function ImportStorniereAuftrag() {
$orderId = $this->CatchRemoteCommand('data')['auftrag']; $orderId = $this->CatchRemoteCommand('data')['auftrag'];
if (!empty($orderId)) { if (!empty($orderId)) {
$this->client->put('orders/'.$orderId, [ $this->client->put('orders/'.$orderId, [
'status' => 'cancelled', 'status' => 'cancelled',
@ -563,22 +549,13 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} else { } else {
return 'failed'; return 'failed';
} }
return 'ok'; return 'ok';
} }
public function ImportSendList() { public function ImportSendList() {
$tmp = $this->catchRemoteCommand('data'); $tmp = $this->catchRemoteCommand('data');
$anzahl = 0; $anzahl = 0;
for($i=0;$i<(!empty($tmp)?count($tmp):0);$i++){ for($i=0;$i<(!empty($tmp)?count($tmp):0);$i++){
$artikel = $tmp[$i]['artikel']; $artikel = $tmp[$i]['artikel'];
$nummer = $tmp[$i]['nummer']; $nummer = $tmp[$i]['nummer'];
if(!empty($tmp[$i]['artikelnummer_fremdnummern'][0]['nummer'])){ if(!empty($tmp[$i]['artikelnummer_fremdnummern'][0]['nummer'])){
@ -604,7 +581,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$dim_width = $tmp[$i]['breite']; $dim_width = $tmp[$i]['breite'];
$dim_height = $tmp[$i]['hoehe']; $dim_height = $tmp[$i]['hoehe'];
// Sanitize dimensions // Sanitize dimensions
if (self::emptyString($weight_kg)) if (self::emptyString($weight_kg))
$weight_kg = null; $weight_kg = null;
@ -619,11 +595,9 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$dim_height = null; $dim_height = null;
$meta_desc = $tmp[$i]['metadescription_de']; $meta_desc = $tmp[$i]['metadescription_de'];
$meta_title = $tmp[$i]['metatitle_de']; $meta_title = $tmp[$i]['metatitle_de'];
$pseudopreis = $tmp[$i]['pseudopreis'];//*1.19; $pseudopreis = $tmp[$i]['pseudopreis'];//*1.19;
if($pseudopreis <= $preis)$pseudopreis = $preis; if($pseudopreis <= $preis)$pseudopreis = $preis;
$steuersatz = $tmp[$i]['steuersatz']; $steuersatz = $tmp[$i]['steuersatz'];
@ -657,7 +631,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
]; ];
// Attributes that are used for both updating an existing product as well as creating a new one // Attributes that are used for both updating an existing product as well as creating a new one
$commonProductAtts = [ $commonProductAtts = [
'name' => $name_de, 'name' => $name_de,
@ -675,7 +648,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
'meta_data' => $commonMetaData, 'meta_data' => $commonMetaData,
]; ];
if($lageranzahl===0){ if($lageranzahl===0){
$commonProductAtts['stock_status'] = 'outofstock'; $commonProductAtts['stock_status'] = 'outofstock';
$commonProductAtts['manage_stock'] = true; $commonProductAtts['manage_stock'] = true;
@ -693,30 +665,22 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$commonProductAtts['stock_quantity'] = (int)$lageranzahl; $commonProductAtts['stock_quantity'] = (int)$lageranzahl;
} }
if(!is_null($product_id)) { if(!is_null($product_id)) {
// Such a product already appears to exist, so we update it // Such a product already appears to exist, so we update it
$this->client->put('products/'.$product_id, array_merge([ $this->client->put('products/'.$product_id, array_merge([
], $commonProductAtts)); ], $commonProductAtts));
$this->WooCommerceLog("WooCommerce Artikel geändert für Artikel: $nummer / $product_id"); $this->logger->info("WooCommerce Artikel geändert für Artikel: $nummer / $product_id");
} }
else{ else{
// create a new product // create a new product
$product_id = $this->client->post('products/', array_merge([ $product_id = $this->client->post('products/', array_merge([
'sku' => $nummer, 'sku' => $nummer,
], $commonProductAtts))->id; ], $commonProductAtts))->id;
$this->logger->info("WooCommerce neuer Artikel angelegt: $nummer");
$this->WooCommerceLog("WooCommerce neuer Artikel angelegt: $nummer");
} }
// TODO: Kategoriebaum und Bilder werden noch nicht uebertragen // TODO: Kategoriebaum und Bilder werden noch nicht uebertragen
// if(isset($tmp[$i]['kompletter_kategorienbaum'])){ // if(isset($tmp[$i]['kompletter_kategorienbaum'])){
@ -729,13 +693,10 @@ class Shopimporter_Woocommerce extends ShopimporterBase
// $this->save_images($dateien, $product_id); // $this->save_images($dateien, $product_id);
// } // }
// Update the associated product categories // Update the associated product categories
$chosenCats = array(); $chosenCats = array();
if(isset($tmp[$i]['kategorien']) || isset($tmp[$i]['kategoriename'])){ if(isset($tmp[$i]['kategorien']) || isset($tmp[$i]['kategoriename'])){
$kategorien = $tmp[$i]['kategorien']; $kategorien = $tmp[$i]['kategorien'];
if (!($kategorien) && !self::emptyString($tmp[$i]['kategoriename'])) { if (!($kategorien) && !self::emptyString($tmp[$i]['kategoriename'])) {
$kategorien = array( $kategorien = array(
@ -745,11 +706,9 @@ class Shopimporter_Woocommerce extends ShopimporterBase
); );
} }
if((!empty($kategorien)?count($kategorien):0)>0){ if((!empty($kategorien)?count($kategorien):0)>0){
// Retrive all WC categories via API // Retrive all WC categories via API
$allWooCommerceCategories = $this->client->get('products/categories', ['per_page' => '100']); $allWooCommerceCategories = $this->client->get('products/categories', ['per_page' => '100']);
$searchWpCategories = []; $searchWpCategories = [];
foreach($allWooCommerceCategories as $a){ foreach($allWooCommerceCategories as $a){
$searchWpCategories[$a->id] = $a->name; $searchWpCategories[$a->id] = $a->name;
@ -764,13 +723,10 @@ class Shopimporter_Woocommerce extends ShopimporterBase
// If WC has a matching category. We match based on name! // If WC has a matching category. We match based on name!
if(array_search($wawi_cat_name,array_values($searchWpCategories)) !== false) { if(array_search($wawi_cat_name,array_values($searchWpCategories)) !== false) {
// get id of that WC Category // get id of that WC Category
$wcCatId = array_search($wawi_cat_name,$searchWpCategories); $wcCatId = array_search($wawi_cat_name,$searchWpCategories);
} else { } else {
// No matching category exists // No matching category exists
$wcCatId = $this->client->post('products/categories', [ $wcCatId = $this->client->post('products/categories', [
'name' => $wawi_cat_name, 'name' => $wawi_cat_name,
@ -778,14 +734,12 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
if ($wcCatId) { if ($wcCatId) {
// update category. We first retrieve the product and append the new product category, not replace the entire category array. // update category. We first retrieve the product and append the new product category, not replace the entire category array.
$alreadyAssignedWCCats = $this->client->get('products/'.$product_id, [ $alreadyAssignedWCCats = $this->client->get('products/'.$product_id, [
'per_page' => 1, 'per_page' => 1,
])->categories; ])->categories;
// Get ids of existing categories // Get ids of existing categories
$existingCategoryIds = []; $existingCategoryIds = [];
foreach ($alreadyAssignedWCCats as $cat) { foreach ($alreadyAssignedWCCats as $cat) {
@ -814,16 +768,10 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$anzahl++; $anzahl++;
} }
return $anzahl; return $anzahl;
// return array($product_id,$anzahl,$nummer,$steuersatz, $preis); // return array($product_id,$anzahl,$nummer,$steuersatz, $preis);
} }
/** /**
* Checks the connection to the WooCommerce API by trying a simple API request * Checks the connection to the WooCommerce API by trying a simple API request
* *
@ -839,7 +787,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
} }
/** /**
* This is called by class.remote.php, initializes some class variables from the DB * This is called by class.remote.php, initializes some class variables from the DB
* @param [type] $shopid [description] * @param [type] $shopid [description]
@ -876,8 +823,8 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$ImportWooCommerceApiKey, $ImportWooCommerceApiKey,
//WooCommerce API Secret //WooCommerce API Secret
$ImportWooCommerceApiSecret, $ImportWooCommerceApiSecret,
["query_string_auth" => true],
["query_string_auth" => true] $this->logger
); );
} }
@ -919,8 +866,8 @@ class Shopimporter_Woocommerce extends ShopimporterBase
$ImportWooCommerceApiUrl, $ImportWooCommerceApiUrl,
$ImportWooCommerceApiKey, $ImportWooCommerceApiKey,
$ImportWooCommerceApiSecret, $ImportWooCommerceApiSecret,
['query_string_auth' => true],
['query_string_auth' => true] $this->logger
); );
$auth = $this->ImportAuth(); $auth = $this->ImportAuth();
@ -931,7 +878,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return null; return null;
} }
/** /**
* @return array[] * @return array[]
*/ */
@ -987,7 +933,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
* @throws WCHttpClientException * @throws WCHttpClientException
*/ */
private function getShopIdBySKU($sku) { private function getShopIdBySKU($sku) {
// Retrieve the product with the given sku. // Retrieve the product with the given sku.
// Note: We limit the result set to 1 (per_page=1), so this doesnt work // Note: We limit the result set to 1 (per_page=1), so this doesnt work
// if there are multiple products with the same sku. should not happen in practice anyway // if there are multiple products with the same sku. should not happen in practice anyway
@ -1005,7 +950,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return null; return null;
} }
private function getSKUByShopId($articleid, $variationid) { private function getSKUByShopId($articleid, $variationid) {
$product = $this->client->get("products/$articleid/variations/$variationid"); $product = $this->client->get("products/$articleid/variations/$variationid");
@ -1023,7 +967,7 @@ class Shopimporter_Woocommerce extends ShopimporterBase
'ausblenden'=>array('abholmodus'=>array('zeitbereich')), 'ausblenden'=>array('abholmodus'=>array('zeitbereich')),
'archiv'=>array('ab_nummer'), 'archiv'=>array('ab_nummer'),
'felder'=>array( 'felder'=>array(
'protokoll'=>array('typ'=>'checkbox','bezeichnung'=>'Protokollierung im Logfile:'), // 'protokoll'=>array('typ'=>'checkbox','bezeichnung'=>'Protokollierung im Logfile:'),
'ImportWoocommerceApiKey'=>array('typ'=>'text','bezeichnung'=>'{|API Key:','size'=>60), 'ImportWoocommerceApiKey'=>array('typ'=>'text','bezeichnung'=>'{|API Key:','size'=>60),
'ImportWoocommerceApiSecret'=>array('typ'=>'text','bezeichnung'=>'{|API Secret|}:','size'=>60), 'ImportWoocommerceApiSecret'=>array('typ'=>'text','bezeichnung'=>'{|API Secret|}:','size'=>60),
'ImportWoocommerceApiUrl'=>array('typ'=>'text','bezeichnung'=>'{|API Url|}:','size'=>40), 'ImportWoocommerceApiUrl'=>array('typ'=>'text','bezeichnung'=>'{|API Url|}:','size'=>40),
@ -1034,20 +978,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
)); ));
} }
/**
* Writes data to the syslog
* @param [type] $nachricht message that will be logged
* @param string $dump php array or object, printed using print_r
*/
public function WooCommerceLog($nachricht, $dump = '')
{
if($this->protokoll){
$this->app->erp->LogFile($nachricht, print_r($dump, true));
}
}
/** /**
* Compares two Objects and returns true if every variable in items * Compares two Objects and returns true if every variable in items
* is the same in $a and $b * is the same in $a and $b
@ -1068,8 +998,6 @@ class Shopimporter_Woocommerce extends ShopimporterBase
return true; return true;
} }
/** /**
* Returns true when the string entered is empty, after stripping whitespace * Returns true when the string entered is empty, after stripping whitespace
* @param String $string input * @param String $string input
@ -1081,11 +1009,8 @@ class Shopimporter_Woocommerce extends ShopimporterBase
} }
class WCClient class WCClient
{ {
/** /**
* WooCommerce REST API WCClient version. * WooCommerce REST API WCClient version.
*/ */
@ -1098,6 +1023,9 @@ class WCClient
*/ */
public $http; public $http;
/** @var Logger $logger */
public $logger;
/** /**
* Initialize client. * Initialize client.
* *
@ -1108,9 +1036,10 @@ class WCClient
* *
* @throws WCHttpClientException * @throws WCHttpClientException
*/ */
public function __construct($url, $consumerKey, $consumerSecret, $options = []) public function __construct($url, $consumerKey, $consumerSecret, $options = [], $logger)
{ {
$this->http = new WCHttpClient($url, $consumerKey, $consumerSecret, $options); $this->http = new WCHttpClient($url, $consumerKey, $consumerSecret, $options, $logger);
$this->logger = $logger;
} }
/** /**
@ -1190,7 +1119,6 @@ class WCClient
class WCResponse class WCResponse
{ {
/** /**
* WCResponse code. * WCResponse code.
* *
@ -1289,7 +1217,6 @@ class WCResponse
class WCOptions class WCOptions
{ {
/** /**
* Default WooCommerce REST API version. * Default WooCommerce REST API version.
*/ */
@ -1423,7 +1350,6 @@ class WCOptions
class WCRequest class WCRequest
{ {
/** /**
* WCRequest url. * WCRequest url.
* *
@ -1596,7 +1522,6 @@ class WCRequest
class WCOAuth class WCOAuth
{ {
/** /**
* OAuth signature method algorithm. * OAuth signature method algorithm.
*/ */
@ -1906,7 +1831,6 @@ class WCHttpClientException extends \Exception
class WCHttpClient class WCHttpClient
{ {
/** /**
* cURL handle. * cURL handle.
* *
@ -1963,6 +1887,9 @@ class WCHttpClient
*/ */
private $responseHeaders; private $responseHeaders;
/** @var Logger $logger */
public $logger;
/** /**
* Initialize HTTP client. * Initialize HTTP client.
* *
@ -1973,7 +1900,7 @@ class WCHttpClient
* *
* @throws WCHttpClientException * @throws WCHttpClientException
*/ */
public function __construct($url, $consumerKey, $consumerSecret, $options) public function __construct($url, $consumerKey, $consumerSecret, $options, $logger)
{ {
if (!function_exists('curl_version')) { if (!function_exists('curl_version')) {
throw new WCHttpClientException('cURL is NOT installed on this server', -1, new WCRequest(), new WCResponse()); throw new WCHttpClientException('cURL is NOT installed on this server', -1, new WCRequest(), new WCResponse());
@ -1983,6 +1910,7 @@ class WCHttpClient
$this->url = $this->buildApiUrl($url); $this->url = $this->buildApiUrl($url);
$this->consumerKey = $consumerKey; $this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret; $this->consumerSecret = $consumerSecret;
$this->logger = $logger;
} }
/** /**
@ -2171,7 +2099,6 @@ class WCHttpClient
*/ */
protected function createResponse() protected function createResponse()
{ {
// Set response headers. // Set response headers.
$this->responseHeaders = ''; $this->responseHeaders = '';
curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($_, $headers) { curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($_, $headers) {
@ -2195,7 +2122,7 @@ class WCHttpClient
*/ */
protected function setDefaultCurlSettings() protected function setDefaultCurlSettings()
{ {
$verifySsl = $this->options->verifySsl(); // $verifySsl = $this->options->verifySsl();
$timeout = $this->options->getTimeout(); $timeout = $this->options->getTimeout();
$followRedirects = $this->options->getFollowRedirects(); $followRedirects = $this->options->getFollowRedirects();
@ -2236,6 +2163,13 @@ class WCHttpClient
$errorCode = $errors->code; $errorCode = $errors->code;
} }
$this->logger->error('WooCommerce Error',
[
'request' => $this->request,
'response' => $this->response
]
);
throw new WCHttpClientException( throw new WCHttpClientException(
sprintf('Error: %s [%s]', $errorMessage, $errorCode), sprintf('Error: %s [%s]', $errorMessage, $errorCode),
$this->response->getCode(), $this->response->getCode(),
@ -2294,8 +2228,6 @@ class WCHttpClient
public function request($endpoint, $method, $data = [], $parameters = []) public function request($endpoint, $method, $data = [], $parameters = [])
{ {
// Initialize cURL. // Initialize cURL.
$this->ch = curl_init(); $this->ch = curl_init();
@ -2308,7 +2240,6 @@ class WCHttpClient
// Get response. // Get response.
$response = $this->createResponse(); $response = $this->createResponse();
// Check for cURL errors. // Check for cURL errors.
if (curl_errno($this->ch)) { if (curl_errno($this->ch)) {
throw new WCHttpClientException('cURL Error: ' . \curl_error($this->ch), 0, $request, $response); throw new WCHttpClientException('cURL Error: ' . \curl_error($this->ch), 0, $request, $response);