如何将“ node.js脚本”转换为“应用程序脚本”

时间:2019-12-20 09:56:12

标签: node.js google-apps-script

node.js脚本

hmacGenerator.js

const crypto = require('crypto');
const moment = require('moment');

module.exports = {

generateHmac: (method, url, secretKey, accessKey) => {

    const parts = url.split(/\?/);
    const [path, query = ''] = parts;

    const datetime = moment.utc().format('YYMMDD[T]HHmmss[Z]');
    const message = datetime + method + path + query;

    const signature = crypto.createHmac('sha256', secretKey)
        .update(message)
        .digest('hex');

    return `CEA algorithm=HmacSHA256, access-key=${accessKey}, signed-date=${datetime}, signature=${signature}`;
}
};

在发送HTTP信号之前,必须使用Authorization标头设置HMAC签名。

app.js

const axios = require('axios');
const { generateHmac } = require('./hmacGenerator');

const REQUEST_METHOD = "POST";
const DOMAIN = "https://api-gateway.coupang.com";
const URL = "/v2/providers/affiliate_open_api/apis/openapi/v1/deeplink";

// Replace with your own ACCESS_KEY and SECRET_KEY
const ACCESS_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
const SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

const REQUEST = { "coupangUrls": [
        "https://www.coupang.com/np/search?component=&q=good&channel=user", 
        "https://www.coupang.com/np/coupangglobal"
]};

(async () => {
    const authorization = generateHmac(REQUEST_METHOD, URL, SECRET_KEY, ACCESS_KEY);
    axios.defaults.baseURL = DOMAIN;

    try {       
        const response = await axios.request({
            method: REQUEST_METHOD,
            url: URL,
            headers: { Authorization: authorization },
            data: REQUEST
        });
        console.log(response.data);
    } catch (err) {
        console.error(err.response.data);
    }    
})();

如何将“ node.js脚本”转换为“应用程序脚本” 正确访问api连接哈希消息身份验证代码

0 个答案:

没有答案