具有Google UrlFetchApp标头授权的WooCommerce REST API不起作用

时间:2020-04-17 21:02:44

标签: wordpress google-apps-script woocommerce http-status-code-401 woocommerce-rest-api

当前

我正在通过以下工作代码在Google脚本中使用WooCommerce REST API:


    var ck = "ck_longstringlongstringlongstringlongstring";
    var cs = "cs_longstringlongstringlongstringlongstring";
    var website = "https://www.mywebsite.com.au";

    var url = website + "/wp-json/wc/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs; 

    var options =
        {
          "method": "GET",
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          "muteHttpExceptions": true,
        };

    var result = UrlFetchApp.fetch(url, options);

问题

为了提高安全性,我想将使用者密钥和机密信息放入标头中,但无法使用以下脚本

   var url = website + "/wp-json/wc/v3/orders; 

   let authHeader = 'Basic ' + Utilities.base64Encode(ck + ':' + cs);

    var options =
        {
          "method": "GET",
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          "muteHttpExceptions": true,
          "headers": {"Authorization": authHeader},
        };

    var result = UrlFetchApp.fetch(url, options);

当前结果= {"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}

预期结果=订单的JSON

我的代码有问题吗?还是使用WooCommerce API或Google脚本?

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。

对于UrlFetchApp.fetch(),您需要使用contentType而不是Content-Type

但是,在这种情况下,您甚至不需要设置它,因为application/x-www-form-urlencoded是默认设置。 method属性也是如此;它默认为GET

此外,如果您要谨慎行事,请使用Utilities.base64EncodeWebSafe(data, charset)对您的凭据进行base64编码,而不要使用非网络安全版本。

let url = website + "/wp-json/wc/v3/orders"; 
let encoded = Utilities.base64EncodeWebSafe(ck + ':' + cs, Utilities.Charset.UTF_8);

let options = {
    "muteHttpExceptions":true,
    "headers": {
        "Authorization": "Basic " + encoded
    }
};

let result = UrlFetchApp.fetch(url, options);
result = JSON.parse(result);