php Woocommerce函数被 AJAX 调用时返回500

um6iljoc  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(147)

我已经创建了自定义插件,其中包括一个函数,发送一个GET调用到第三方API以获得产品列表。然后循环通过列表,并发送另一个GET请求(使用sku #)每个产品的详细信息。然后它检查现有产品并更新详细信息,如果没有现有产品,它会将产品添加到Woocommerce。
我创建的函数在我将其添加到页面时工作正常,但我将其放入一个单独的文件中,以便用 AJAX 调用它,我得到一个500错误。
我已经把它缩小到了临界点,每当Woocommerce函数被调用时(wc_get_products(),$NewProd =新的WC_Product_Simple(),等等)。
这是某种我可以调整的服务器超时的东西吗?或者我可以在WordPress配置文件中改变一些东西吗?可能是一厢情愿的想法。希望有人能帮忙。

单独文件中的自定义循环函数:

<?php
const bb_lAPI = 'https://sca1.furnguy.com/sca1web/oecgi3.exe';
const bb_tAPI = 'https://sca1.furnguy.com/sca1play/oecgi3.exe';

if (isset($_GET['sec55135'])):
    $bbwdVerify = strval($_GET['sec55135']);

     $bb_curl = curl_init();
   // OPTIONS:
   if( $bbwdVerify == 'Live'):
       $bb_url = bb_lAPI;
   else:
       $bb_url = bb_tAPI;
   endif;
   curl_setopt($bb_curl, CURLOPT_URL, $bb_url . '/inet_website_product_lookup?searchkey=Aluminum');

   curl_setopt($bb_curl, CURLOPT_HTTPHEADER, array(
      'Authorization: Bearer CannotShowThis123',
      'Content-Type: application/json'
   ));
   curl_setopt($bb_curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($bb_curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   $result = curl_exec($bb_curl);
   if(!$result){die("Connection Failure");}
    curl_close($bb_curl);
    $bbwd_json = json_decode($result);
    if($bbwd_json->errors):
        echo '<h1>API Error</h1><p class="bpAPIError">'.$bbwd_json->errors->system.'</p>';
        echo '<p>requested url = <strong>' . $bb_url . '/inet_website_product_lookup?priceslist=SCA1</strong></p>';
    else:

        echo '<h1>No errors!!!</h1>';
        echo '<p>requested url = <strong>' . $bb_url . '</strong></p><hr style="margin-bottom: 50px;">';
        $bbwdItemArr = $bbwd_json->itemlist;
        $bbwdItemArrCount = (int) $bbwd_json->totalresults;
        $bbwd_Product = array();

    for($bbwdI = 0; $bbwdI <= $bbwdItemArrCount; $bbwdI++):
        $bbwdProdSS =  $bbwd_json->itemlist[$bbwdI]->skuserial;
        if($bbwdProdSS):
            
            echo "Product ".$bbwdI." SKUSerial = ".$bbwdProdSS."<br>";
            bbwdItemApiLook($bbwdProdSS, "Live");
        endif;
        echo "<hr>";
     endfor;
    endif;//end if errors






endif; // end if isset $_GET['sec55135']



function bbwdItemApiLook($bbwdItemSS, $bbwdTest){
    

       // OPTIONS:
       if($bbwdTest == 'Live'):
           $bb_url2 = bb_lAPI;
       else:
           $bb_url2 = bb_tAPI;
       endif;

        echo $bb_zurl2.'/inet_website_item_detail?item='.$bbwdItemSS."<br>";
    //$bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS
         $bb_curl2 = curl_init();
        curl_setopt($bb_curl2, CURLOPT_URL, $bb_url2.'/inet_website_item_detail?item='.$bbwdItemSS);
    
    
       curl_setopt($bb_curl2, CURLOPT_HTTPHEADER, array(
          'Authorization: Bearer CannotShowThis123',
          'Content-Type: application/json'
       ));
       curl_setopt($bb_curl2, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($bb_curl2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
       // EXECUTE:
       $result2 = curl_exec($bb_curl2);
       if(!$result2){die("Connection Failure");}
       curl_close($bb_curl2);
        $bbwd_json2 = json_decode($result2);
        if($bbwd_json2->errors):
            echo '<h2>API Error = <u>'.$bbwd_json2->errors->system.'</u></h2>';
        else:
                $bbwdMapped = bbwdMapProduct($bbwd_json2);
                echo "<h3>".$bbwdMapped->ssku."</h3>";
                bbwdCheckProd($bbwdMapped);
            
        endif;

}

function bbwdMapProduct($bbwdArr){
        $bbwdTitle = $bbwdArr->factsrec->shortdescription[0];
        $bbwInStock;
        $bbwdSku = $bbwdArr->sku;
        $bbwdSSku = $bbwdArr->skuserial;
        $bbwdPrice = $bbwdArr->inventoryrec->retail;
        $bbwdSalePrice = $bbwdArr->inventoryrec->retail3;
        $bbwdDescription = $bbwdArr->inventoryrec->description;
        if($bbwdArr->availability == "In Stock"):
            $bbwInStock = "instock";
        else:
            $bbwInStock = "outofstock";
        endif;
        $bbwdPolishedProd = ["title"=>$bbwdTitle, "instock"=>$bbwInStock, "sku"=>$bbwdSku, "price"=>$bbwdPrice, "sale_price"=>$bbwdSalePrice, "description"=>$bbwdDescription, "ssku"=>$bbwdSSku];
        return $bbwdPolishedProd;
}

/*=====================================================================
 *                     Manage Woocommerce Products
 * ==================================================================*/
/******** Check if product exists ***********/
function bbwdCheckProd($bbwdTheProd){
        $bbwdProdName = $bbwdTheProd["title"];
        $bbwdNameAdj = strtolower($bbwdProdName);
        $bbwdProdSlug = str_replace(" ", "-", $bbwdNameAdj);
        $bbwdProdSku = $bbwdTheProd["ssku"];
        $bbwdProdPrice = $bbwdTheProd["price"];
        $bbwdProdSPrice = $bbwdTheProd["sale_price"];
        $bbwdProdDesc = $bbwdTheProd["description"];
        $bbwdProdStock = $bbwdTheProd["instock"];
        $bbwdExProds = [];

/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/

                            THIS IS WHERE THE CODE IS BREAKING!!!
if you a just leave "bbwdOurProducts2" as an empty var the code breaks at the $bbwdNewProd = new WC_Product_Simple(); function located on the ELSE half of the if statement just below.

/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/
        $bbwdOurProducts2 = wc_get_products( array('sku' => $bbwdProdSku) );

        if(!empty($bbwdOurProducts2)):
            foreach($bbwdOurProducts2 as $bbwdSProduct):

                if($bbwdSProduct->sku == $bbwdProdSku):
                    $bbwdProdID = get_the_id($bbwdProdSku);
                    $bbwdSProduct->set_name( $bbwdProdName );
                    $bbwdSProduct->set_slug( $bbwdProdSlug );
                    $bbwdSProduct->set_regular_price( $bbwdProdPrice );
                    if($bbwdProdSPrice > 0):
                        $bbwdSProduct->set_sale_price( $bbwdProdSPrice );
                    else:
                        $bbwdSProduct->set_sale_price( $bbwdProdPrice );
                    endif;

                    $bbwdSProduct->set_stock_status( $bbwdProdStock );
                    $bbwdSProduct->save();
                endif;
            endforeach;
        else:
                $bbwdNewProd = new WC_Product_Simple();
                $bbwdNewProd->set_name( $bbwdProdName );
                $bbwdNewProd->set_slug( $bbwdProdSlug );
                $bbwdNewProd->set_sku( $bbwdProdSku );
                $bbwdNewProd->set_regular_price( $bbwdProdPrice );
                $bbwdNewProd->set_sale_price( $bbwdProdSPrice );
                $bbwdNewProd->set_stock_status( $bbwdProdStock );
                $bbwdNewProd->set_short_description( 'short description here...' );
                $bbwdNewProd->set_description( 'long description here...' );
                $bbwdNewProd->set_image_id( 21 );
                $bbwdNewProd->set_category_ids( array( 30 ) );
                $bbwdNewProd->save();
        endif;
echo "Complete!!!";

}

?>

AJAX 请求

<script type="text/javascipt">
let bbwdLoader = document.createElement('img');
let resultDiv = jQuery('#bbwdResults');
bbwdLoader.src = "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/assets/img/Rhombus-Loader.gif";

/**************************************************************************************************/
/**************************************************************************************************/
          The "syncProds()" function is the "onclick" function attached to a button.

I use jQuery in place of $ because of variable errors when using jQuery with WordPress
/**************************************************************************************************/
/**************************************************************************************************/
function syncProds(){
    let resultDiv = jQuery('#bbwdResults');
    resultDiv.html(bbwdLoader);
    console.log('Script Working!!!');
    
    
    
    
    bbwdTheCall();
}

async function bbwdTheCall(){
    let bbwdRes;
    await jQuery.ajax({
        url: "https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php", 
        type: "GET",
        async: true,
        timeout: 0,
        data: {'sec55135': 'Live'},
        success:function(result){
                resultDiv.html(result);
                bbwdRes = result
                },
        error:function(error){
            resultDiv.html("<h2>There was an error!!!</h2><h4>" + error.status + " " + error.statusText + " </h4>");
            console.log(error);
        }
    });
    console.log(bbwdRes);
}
</script>
9lowa7mx

9lowa7mx1#

如果我理解正确的话,首先你在插件中添加了代码,它工作了,但是当你把代码移到一个单独的文件中时,它没有工作。正确吗?你在你的https://scanhome.brightbridgeweb.com/wp-content/plugins/bright-bridge-product-api-functions/syncAllProducts.php文件中加载了WordPress吗?可能没有。所以你可以在你的文件中加载一个WordPress,包括“path to wp-load.php”或者使用一个正确的方法在WordPress中使用ajax操作运行 AJAX 。WordPress对 AJAX 有一个真正好的支持,无论你做什么,在你运行你的自定义代码之前,WordPress和插件都必须加载并准备好使用。

相关问题