2013-12-18 73 views
0

我需要将一些C#代码转换为与PHP Web API等效的PHP代码。他们的所有例子都在C#中。我认为我有相同的PHP函数,但是我的SOAP请求返回'错误请求'或'未经授权 - 无效的API密钥' - 而API页面上的示例页面与我的密钥一起工作,并且请求URL看起来与摘要消息正在传递。 API和客户端ID绝对正确。将C#sha256 hashing转换为PHP等效

下面是C#代码:

private string GenerateDigest(long currentTime) 
    { 
     SHA256Managed hashString = new SHA256Managed(); 
     StringBuilder hex = new StringBuilder(); 
     byte[] hashValue = hashString.ComputeHash(Encoding.UTF8.GetBytes(String.Format("{0}{1}", currentTime, txtApiKey.Text))); 

     foreach (byte x in hashValue) 
     { 
      hex.AppendFormat("{0:x2}", x); 
     } 

     return hex.ToString(); 
    } 

这里是我写的尝试做C#是做PHP函数:

public static function generateDigest($api_key) { 
    return hash('sha256', time() . mb_convert_encoding($api_key, 'UTF-8')); 
} 

我不是很精通C#,所以我承担我出错的地方是它在做hex.AppendFormat()。我不知道这应该是在PHP中。最终的结果是被附加到URL,以生成SOAP请求的散列,例如:

https://payments.homeaway.com/tokens?time=1387385872013 &消化= 1bd70217d02ecc1398a1c90b2be733ff686b13489d9d5b1229461c8aab6e6844 &的clientId = [删除]

编辑:

这是在C#中传递的currentTime变量。

// Request validation setup 
TimeSpan timeSinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1); 
long currentTime = (long)timeSinceEpoch.TotalMilliseconds; 
string digest = GenerateDigest(currentTime); 
+0

为什么'currentTime'是'long'?它是一个时间戳,例如'time()'产生的时间戳? – Jon

+0

用currentTime更新答案。 – Kevin

回答

0

我在这里同样的问题coverting这PHP代码是我的代码来解决这个问题:如果有人正在寻找这个答案有时间做

function generateDigest($time, $api_key) { 
    $hash = hash('sha256', $time . mb_convert_encoding($api_key, 'UTF-8'), true); 
    return $this->hexToStr($hash); 
} 

function hexToStr($string){ 
    //return bin2hex($string); 
    $hex=""; 
    for ($i=0; $i < strlen($string); $i++) 
    { 
     if (ord($string[$i])<16) 
      $hex .= "0"; 
     $hex .= dechex(ord($string[$i])); 
    } 
    return ($hex); 
} 
0

。 PHP的time()函数返回C#中的调用返回毫秒数的时间,以秒为单位。

因此,为了得到$currentTime正确的做法是

$currentTime = time() * 1000; 

这已经与API测试。