【发布时间】:2013-09-18 21:46:00
【问题描述】:
已尝试使用 Google Apps Script UrlFetchApp.fetch() put 方法在 ECWID 中更新产品的许多选项,但均未成功。以下是我编写代码和测试的不同方式,但会遇到不同类型的错误。
我想,我错过了一些小东西,无法弄清楚。请帮我解决这个问题。
API:ECWID 产品 API (http://kb.ecwid.com/w/page/25285101/Product%20API#RESTAPIMethodupdateaproduct) 方法:PUT(更新产品详情)
示例代码 1:-
function updateProducts(){
var products_authkey = "xxxxxxxx";
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var options ={method:"put",ContentType:"application/json",payload:payload};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
}catch(e){
Browser.msgBox(e);
}
}
错误:- "{ "error": "OTHER", "errorMessage": "解析 JSON 时出错:JSONObject 文本必须在字符 0 处以 '{' 开头" }"
版本 2:- 尝试将对象转换为json stringify,但同样的错误。
function updateProducts_version2(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = Utilities.jsonStringify(payload);
var options ={method:"put",ContentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
错误:- "{ "error": "OTHER", "errorMessage": "解析 JSON 时出错:JSONObject 文本必须在字符 0 处以 '{' 开头" }"
版本 3:-(尝试在标头中使用 Authorization 传递 secure_auth_key)
function updateProducts_version3(){
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxx";
var payload = {price:62755};
var headers = {Authorization: 'xxxxxxx'};
var options = {headers:headers,method:"put",ContentType:"application/json",payload:payload};
var options ={method:"put",ContentType:"application/json",payload:payload,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
错误:- { "error": "OTHER", "errorMessage": "API key not found in request parameters" }
还要注意,我尝试使用 DevHttpClient chrome 插件,它正在正确更新。 这意味着我们使用 UrlFetch 的方式存在一些问题。请帮我解决这个问题...
提前谢谢...
【问题讨论】:
-
只是需要将有效载荷放在引号中吗?
-
您是否尝试过使用“调试”选项(您可能必须删除您的尝试)?然后您将能够准确地看到有效载荷的样子。我很好奇哪条线抛出了错误。我没有对该服务的信任,但我在
UrlFetchApp.fetch行上收到了预期的 400 错误。 -
@patto: 尝试将对象放在下面的引号中,然后也得到与以前相同的错误:var payload = "{price:62758}";
-
@fobby: 以下是调试模式下的内容:payload Object (207294512) ({price:62758}) price number 62758 .. 它在 URLFetchApp.fetch 失败并出现上述错误跨度>
-
为什么在 v4 中有两个“选项”?第二个省略了标题...
标签: javascript json rest google-apps-script