如何在VBA中实现FTX API要求的HMAC-SHA256签名认证
VBA实现FTX API签名生成的完整方案
核心实现代码
无需额外安装组件,直接复制以下代码到VBA模块即可使用:
Function GetFTXSignature(ts As String, httpMethod As String, pathUrl As String, apiSecret As String) As String ' 1. 拼接签名原文,对应Python逻辑:f'{ts}{prepared.method}{prepared.path_url}' Dim signaturePayload As String signaturePayload = ts & UCase(httpMethod) & pathUrl ' 2. 字符串转UTF-8字节数组,对应Python逻辑:.encode() Dim utf8 As Object Set utf8 = CreateObject("System.Text.UTF8Encoding") Dim payloadBytes() As Byte, secretBytes() As Byte payloadBytes = utf8.GetBytes_4(signaturePayload) secretBytes = utf8.GetBytes_4(apiSecret) ' 3. 执行HMAC SHA256哈希运算 Dim hmac As Object Set hmac = CreateObject("System.Security.Cryptography.HMACSHA256") hmac.Key = secretBytes Dim hashBytes() As Byte hashBytes = hmac.ComputeHash_2(payloadBytes) ' 4. 哈希结果转小写十六进制字符串,对应Python逻辑:.hexdigest() Dim i As Long, hexStr As String For i = LBound(hashBytes) To UBound(hashBytes) hexStr = hexStr & LCase(Right("0" & Hex(hashBytes(i)), 2)) Next i GetFTXSignature = hexStr End Function
调用示例
Sub TestSignGenerate() ' 实际使用时替换为对应参数 Dim ts As String: ts = "1620000000000" ' 13位毫秒级时间戳,需和请求头FTX-TS完全一致 Dim method As String: method = "GET" ' 请求方法统一用大写 Dim path As String: path = "/api/account" ' 完整请求路径,包含查询参数 Dim apiSecret As String: apiSecret = "你的FTX API Secret" Dim sign As String sign = GetFTXSignature(ts, method, path, apiSecret) Debug.Print "生成签名:" & sign ' 可在VBA立即窗口查看输出 End Sub
校验注意事项
- 路径必须包含完整查询参数,例如分页请求时要把
?limit=100&start_time=xxx拼接在路径末尾 - 时间戳必须和请求头
FTX-TS的取值完全相同,否则会返回签名校验失败错误
内容的提问来源于stack exchange,提问作者Gnad
相关产品推荐
相关产品推荐

