将Python代码转换为PHP/Laravel(Gate.io签名)

Convert Python code to PHP/Laravel (Gate.io signature)

我正在合并 gate,io rest api,目前正在尝试将签名函数从 python 转换为 php(laravel) .

显然转换中隐藏了一个错误。

有人可以看一下并告诉我这是否全部正确或者这里是否遗漏了什么?

如有改进建议,我将不胜感激

Python代码:

def gen_sign(method, url, query_string=None, payload_string=None):
    key = ''        # api_key
    secret = ''     # api_secret

    t = time.time()
    m = hashlib.sha512()
    m.update((payload_string or "").encode('utf-8'))
    hashed_payload = m.hexdigest()
    s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
    sign = hmac.new(secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
    return {'KEY': key, 'Timestamp': str(t), 'SIGN': sign}

来源:Gate.io API Signature string generation

Php代码:

public function createSignature($method, $url, $query=null, $payload=null, $algo = 'sha256'){
        $key = 'xxx';
        $secret= 'xxx';

        $time = microtime(true);

        $hashed_payload = hash_hmac($algo,$query ?? '');

        $string = "{$methode}\n{$url}\n{$query ?? ''}\n{$hashed_payload}\n{$time}"
        
        $sign = hash_hmac($algo,$string,$secret)
       
        return ['KEY' => $key, 'Timestamp' => "{$time}", 'SIGN' => $sign]
    
}

我得到答案了,希望对你有帮助:

public function buildSignHeaders($method, $resourcePath, $queryParams = [], $payload = null)
    {
        $fullPath = parse_url(config('gate-io.host'), PHP_URL_PATH) . $resourcePath;
        $fmt = "%s\n%s\n%s\n%s\n%s";
        $timestamp = time();
        $hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
        $signatureString = sprintf(
            $fmt,
            $method,
            $fullPath,
            GuzzleHttp\Psr7\build_query($queryParams, false),
            $hashedPayload,
            $timestamp
        );
        $signature = hash_hmac("sha512", $signatureString, config('gate-io.apiSecretKey'));
        return [
            "KEY" => config('gate-io.apiKey'),
            "SIGN" => $signature,
            "Timestamp" => $timestamp
        ];
    }