如何用Google Apps Script正确集成KuCoin期货API并调试签名认证代码
KuCoin期货API认证失败:Google Apps Script脚本修正方案
你的脚本无法正常运行的核心问题有两个:一是muteHttpExceptions被错误放在请求头里,二是HMAC签名的字节数组处理可以更严谨以避免编码问题。以下是具体修正步骤和完整代码:
关键错误点说明
muteHttpExceptions位置错误:这个参数是UrlFetchApp请求配置的顶级参数,不属于HTTP请求头,放在headers里会导致请求头格式无效,触发API认证失败。- HMAC签名的编码处理:显式将待签名字符串转为UTF-8字节数组,能避免潜在的编码冲突(比如特殊字符或非ASCII内容引发的签名错误)。
修正后的完整代码
function KuCoinRequest(){ // GET /api/v1/transaction-history?offset=1&forward=true&maxCount=50 const key = 'xx'; // 替换为你的API Key const secret = 'xx'; // 替换为你的API Secret const passphrase = 'xx'; // 替换为你的API Passphrase const baseUrl = "https://api-futures.kucoin.com"; const endpoint = "/api/v1/transaction-history?offset=1&forward=true&maxCount=50"; const method = "GET"; // 生成毫秒级UTC时间戳(KuCoin API要求格式) const timestamp = String(Date.now()); // 构造待签名字符串:timestamp + 请求方法 + 完整端点(含查询参数) const strToSign = timestamp + method + endpoint; // 生成HMAC-SHA256签名,指定UTF-8编码 const signatureBytes = Utilities.computeHmacSignature( Utilities.MacAlgorithm.HMAC_SHA_256, strToSign, secret, Utilities.Charset.UTF_8 ); const signature = Utilities.base64Encode(signatureBytes); // 加密API Passphrase const passphraseBytes = Utilities.computeHmacSignature( Utilities.MacAlgorithm.HMAC_SHA_256, passphrase, secret, Utilities.Charset.UTF_8 ); const encodedPassphrase = Utilities.base64Encode(passphraseBytes); // 构造请求参数:muteHttpExceptions放在顶级配置中 const requestParams = { method: method, headers: { 'KC-API-SIGN': signature, 'KC-API-KEY': key, 'KC-API-TIMESTAMP': timestamp, 'KC-API-PASSPHRASE': encodedPassphrase, 'KC-API-KEY-VERSION': '2' }, muteHttpExceptions: true // 正确位置:请求配置的顶级参数 }; const fullUrl = baseUrl + endpoint; const response = UrlFetchApp.fetch(fullUrl, requestParams); const responseText = response.getContentText(); Logger.log(responseText); return responseText; }
额外排查要点
- 确认API密钥是KuCoin期货账户的有效密钥,且已开启交易历史查询权限。
- 若仍报401错误,检查时间戳是否与UTC时间偏差过大(KuCoin允许±30秒的偏差)。
- 可通过
Logger.log(response.getResponseCode())查看HTTP状态码定位问题:- 401:认证失败(密钥错误、签名错误、时间戳偏差)
- 403:权限不足(API密钥未开启对应权限)
- 429:请求频率超限(需控制请求次数)
内容的提问来源于stack exchange,提问作者kenjosimmons
相关产品推荐
相关产品推荐

