通过 AJAX 调用 BigCommerce API 时出现 401 错误

Getting 401 error while calling BigCommerce API through AJAX

我们希望通过调用 API 到 jQuery/AJAX 来实现快速搜索结果的最低购买数量。我们正在尝试调用 API 但没有得到响应。我们收到以下错误消息:

NetworkError: 401 Unauthorized - https://mystore.mybigcommerce.com/api/v2/products/product_id

以下是我们在 quicksearch.js 文件中添加的代码。

var key = 'API key';
var auth = 'Basic ' + btoa('username:'+key);
var url = 'https://mystore.mybigcommerce.com/api/v2/products/product_id';

$.ajax({
    url : url,
    method : 'GET',
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    async: false,
    crossDomain: true,
    beforeSend : function(req) {
        req.setRequestHeader('Authorization', auth);
    },
    success: function(result) {
        alert('done');
        console.log(result);
    },
    error: function (request, textStatus, errorThrown) {
        console.log(request.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
});

谁能指导解决错误?

我们不支持 CORS。尝试在浏览器中直接从 javascript 调用 API 是非常不安全的。这会公开一个 API 令牌,使某人能够通过基本身份验证访问商店中可用的任何数据。这将包括 PII。

如果您确实需要从 API 调用信息,请使用安全的 Web 服务,该服务 returns 为您的脚本提供非常具体的值,而不是直接调用它。

您可以在实时服务器上创建单独的 PHP 应用程序来调用 Big-commerce API。

您可以从 BigCommerce 商店创建旧版 API 帐户 - 管理面板 -> 高级设置 -> 旧版 API 设置并可以获得 API url、用户名, 令牌.

您可以执行以下代码来获取最低购买数量。

文件名为 getproductinfo.php.

    <?php
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

    $product_id = $_GET['prod_id'];

    $username='username';
    $password='API token';
    $URL='https://mystoreurl.mybigcommerce.com/api/v2/products/'.$product_id;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$URL);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:UTF-8','Accept: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
    $result=curl_exec ($ch);
    curl_close ($ch); 


    $data = json_decode($result,true);
    $minimimOrder = $data['order_quantity_minimum'];
    echo $minimimOrder;die();

    ?>

响应(最小购买数量)--> 您可以使用以下代码作为 result.

进入 quicksearch.js 文件
 var url = 'http://liveserveripaddress/foldername/getproductinfo.php';
        $.ajax({
            url : url,
            type : 'GET',
            data : {prod_id:productid},
            dataType: "json",
            crossDomain: true,

            success: function(result) {
                console.log(result);
                },
            error: function (request, textStatus, errorThrown) {
                console.log(request.responseText);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });