Write a simple script. Download of orders PHP (WooCommerce)Дописать простой скрипт. выгрузки заказов PHP (WooCommerce )
A new BD is now being created and you need to add a piece of code. When the script does not find the goods in the existing (old and exchange base)
if ($good) $goodID=$good->id; , you need to write the search in another table (search for idwp from order woocomers) compare in the new table for ID and return the value from the column goodID)
That is, the script first makes a search in one table, if it does not find, searches in the other and subjects value.
We do it from distance.
Добрый день! Нужна помощь дописать скрипт. Скрипт работает, формирует заказ в нужном формате.
Сейчас создается новая БД и нужно добавить кусок кода. Когда скрипт не находит товар в существующей(старой ь базе обмена
if ($good) $goodID=$good->id; , нужно дописать поиск в другой таблице (ищем по idwp из заказа woocomers) сравниваем в новой таблице по ID и возвращаем значение из колонки goodID)
Т.е скрипт сначала делает поиск в одной таблице, если не находит, ищет в другой и подставляет значение.
Сделаем по удаленке.
<?php
use Automattic\WooCommerce\Client;
set_error_handler("exception_error_handler");
try{
require_once 'Lib.php';
require_once 'Setting.php';
require_once 'WooCommerce/Client.php';
require_once 'OrderList.php';
require_once 'VariationList.php';
require_once 'PreventRepeatExec.php';
if(!$teFile=firstExec('TestExec.txt')) { echo "Process allredy run"; return;}
require_once 'ConnectDB.php';
$orderDB=new OrderList($dbConnect);
$goodList=new VariationList($dbConnect);
$lastOrderDate=$orderDB->getLastOrderDate();
$woocommerce = new Client( wpApiURL, wpApiUserKey, wpApiSecretKey,
array('wp_api' => true, 'version' => 'wc/v2' ));
// Доделать фильтр заказов по дате или постатусу
$wpParam=['after'=>date('Y-m-d\TH:i:s',$lastOrderDate-3600*24),
'page'=>1,
// 'per_page'=>3
// 'status'=>?
];
$orderCount=0;
for($pageN=0; count($orderList=$woocommerce->get('orders',$wpParam))>0 ;$pageN++)
{
foreach($orderList as $order)
{
//if ($orderDB->orderPresentInDb($order)) continue;
if (!$orderDB->addOrderToDB($order)) continue;
WriteOrderToFile($order);
$orderCount++;
}
$wpParam['page']=$pageN+2;
}
LogEvent('Order Export Complete. Precessed '.$orderCount.' intems.');
}catch(Exception $ex){
LogError("Error in ExportOrder.php. File:".$ex->getFile()." line:".$ex->getLine().". ".$ex->getMessage());
}
endExcec($teFile);
return;
// END OF MAIN()
function fWriteLine($file, $str)
{
return fputs($file,iconv('UTF-8','windows-1251',$str."\n"));
}
function exception_error_handler($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// Этот код ошибки не входит в error_reporting
return;
}
throw new ErrorException($message, 0, $severity, $file, $line);
}
function WriteOrderToFile(stdClass $order)
{ global $goodList;
$fName=pathOrderExport.'/'.$order->id.'_'.$order->date_created_gmt.'.sal';
$fName=str_replace(':','-',$fName);
$file=fopen($fName,'w');
if (!$file) throw new Exception('Error on create .sal file.');
$docDate=MysqlTimestampToDateTime($order->date_created);
fWriteLine($file, '[Client]');
fWriteLine($file, 'Name='[email protected]$order->billing->last_name.' '[email protected]$order->billing->first_name);
fWriteLine($file, 'MPhone='[email protected]$order->billing->phone);
fWriteLine($file, 'CPhone=');
fWriteLine($file, 'ZIP='[email protected]$order->billing->postcode);
fWriteLine($file, 'Country='[email protected]$order->billing->country);
fWriteLine($file, 'Region='[email protected]$order->billing->state);
fWriteLine($file, 'City='[email protected]$order->billing->city);
fWriteLine($file, 'Address='[email protected]$order->billing->address_1.', '[email protected]$order->billing->address_2);
fWriteLine($file, 'EMail='[email protected]$order->billing->email);
fWriteLine($file, '');
fWriteLine($file, '[Options]');
fWriteLine($file, 'SaleType=1'); //?????
fWriteLine($file, 'Comment='[email protected]$order->customer_note);
fWriteLine($file, 'OrderNumber='.$order->number); //????
fWriteLine($file, 'DeliveryCondition='[email protected]$order->shipping_lines[0]->method_title);//????
fWriteLine($file, 'ReserveDate='.date('dmY',$docDate)); //????
// fWriteLine($file, 'BonusPay=0.00');//????
// fWriteLine($file, 'GiftCertificate=');//????
fWriteLine($file, 'OrderDate='.date('Y-m-d H:i:s',$docDate));
fWriteLine($file, '');
$i=0;
foreach($order->line_items as $item)
{
$i++;
$good=$goodList->getByIdWP($item->variation_id);
if ($good) $goodID=$good->id;
else $goodID=0;
fWriteLine($file, '['.$i.']');
fWriteLine($file, 'GoodID='.$goodID);
fWriteLine($file, 'Price='.currToStr($item->price));
fWriteLine($file, 'Count='.$item->quantity);
fWriteLine($file, '');
}
fclose($file);
}
?>
-
246 2 0 Hello to you. Ready to immediately offer a piece of code to solve the task
Здравствуйте. Готов сразу предложить кусок кода для решения задачи