1

我正在尝试使用 ETSY api 进行 api 调用以更新列表库存。

我收到此错误:oauth_problem=signature_invalid&debug_sbs=PUT

我的代码是:

const request = require('request')
const OAuth = require('oauth-1.0a')
const crypto = require('crypto')

let data ='produts data';


// Initialize
const oauth = OAuth({
    consumer: {
        key: api_key,
        secret: secret
    },
    signature_method: 'HMAC-SHA1',
    hash_function(base_string, key) {
        return crypto
            .createHmac('sha1', key)
            .update(base_string)
            .digest('base64')
    },
})
const request_data = {
    url: url,
    method: 'PUT',
    data: {
        products: data.products,
        price_on_property: [513],
        quantity_on_property: [513],
        sku_on_property: [513]
    },
}

// Note: The token is optional for some requests
const token = {
    key: access_token,
    secret: access_token_secret,
}
request({
    url: request_data.url,
    method: request_data.method,
    form: request_data.data,
    headers: oauth.toHeader(oauth.authorize(request_data, token)),
},
    function (error, response, body) {
        console.log(response.body)
    });

我的代码中是否缺少任何内容?

4

1 回答 1

1

Etsy API 要求 oauth 参数包含在帖子正文中,而不是标题中。文档不是很清楚,但有点暗示它(https://www.etsy.com/developers/documentation/getting_started/oauth#section_authorized_put_post_requests

因此,您的请求调用应如下所示:

request({
    url: request_data.url,
    method: request_data.method,
    form: oauth.authorize(request_data, token)
},
function (error, response, body) {
    console.log(response.body)
});

Postman ( https://www.postman.com/ )是调试此类问题的好工具。这就是我能够追踪到这个问题的方式。

编辑:

如果请求在 Postman 中运行,但您仍然无法在您的代码中运行,那么您可以稍微分解一下该过程。通过调用 oauth 对象上的 nonce、timestamp 和 signature 方法手动构建 oauth 参数。

let oauth_data = {
    oauth_consumer_key: api_key,
    oauth_nonce: oauth.getNonce(),
    oauth_signature_method: "HMAC-SHA1",
    oauth_timestamp: oauth.getTimeStamp(),
    oauth_version: "1.0",
    oauth_token: access_token
 };
 //now generate the signature using the request data and the oauth object
 //you've just created above
 let signature = oauth.getSignature(request_data,token_secret,oauth_data);
 //now add the signature to the oauth_data paramater object
 oauth_data.oauth_signature = signature;


 //merge two objects into one
 let formData = Object.assign({},oauth_data,request_data.params);

 request({
    url: request_data.url,
    method: request_data.method,
    form: formData
 },
 function (error, response, body) {
    console.log(response.body)
 });

我在我的代码中发现我在启动 oauth 对象时错误地命名了 consumer.secret 变量。所以消费者的秘密是空的,因此签名是错误的。

此外,尝试更简单的 PUT 调用,以测试您的基本 PUT 请求是否有效。我正在updateShop更新商店名称(您实际上可以将其更新为现有标题,因此不会更改任何内容),这只需要您的商店 ID 和标题字符串。

于 2021-01-24T09:12:38.680 回答