Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重力表单签名-从PHP到Python_Php_Python_Urlencode_Hmac_Gravity Forms Plugin - Fatal编程技术网

重力表单签名-从PHP到Python

重力表单签名-从PHP到Python,php,python,urlencode,hmac,gravity-forms-plugin,Php,Python,Urlencode,Hmac,Gravity Forms Plugin,我需要将一些现有的PHP代码翻译成Python。此作业连接到重力表单并查询某些数据。为了进行查询,必须计算签名以验证连接 Gravity Forms web api为PHP提供了很好的指导 PHP方法如下所示: function calculate_signature( $string, $private_key ) { $hash = hash_hmac( 'sha1', $string, $private_key, true ); $sig = rawurlencode( b

我需要将一些现有的PHP代码翻译成Python。此作业连接到重力表单并查询某些数据。为了进行查询,必须计算签名以验证连接

Gravity Forms web api为PHP提供了很好的指导

PHP方法如下所示:

function calculate_signature( $string, $private_key ) {
    $hash = hash_hmac( 'sha1', $string, $private_key, true );
    $sig = rawurlencode( base64_encode( $hash ) );
    return $sig;
}
基于我对Python的理解以及php2python.com中关于hash-hmac和rawurlencoded的信息,我写了以下内容:

import hmac, hashlib, urllib, base64
def calculate_signature(string, private_key):
    hash_var = hmac.new(private_key, string, hashlib.sha1).digest()
    sig = urllib.quote(base64.b64encode(hash_var))
    return sig
但是,这两个签名并不相等,因此重力表单返回HTTP 403:Bad请求响应

我的翻译中是否遗漏了什么


更新(11/04/15)

我现在已经匹配了我的php和python URL。但是,我仍然收到403错误。

您就快到了。例如,不象PHP那样对斜杠进行编码。您可以使用以实现所需的效果:

import hmac, hashlib, urllib, base64
def calculate_signature(string, private_key):
    hash_var = hmac.new(private_key, string, hashlib.sha1).digest()
    sig = urllib.quote_plus(base64.b64encode(hash_var))
    return sig

php和python签名不匹配的原因与它们的
calculate\u signature()
方法无关

该问题是由不同的
过期时间
变量引起的。Php使用了
strotime(“+60分钟”)
,这使得UTC时间从现在起60分钟。而Python使用了
datetime.date.now()+timedelta(分钟=60)
。这也是60分钟后,但在您当前的时区


我总是想计算UTC中的
expire
变量,所以我用
datetime.datetime.utcnow()+timedelta(分钟=60)

我注意到在Python代码中,您使用了
base64.b64encode()
,即使您没有导入
base64
模块。这可能是问题所在吗?@Asciithenasi,我很抱歉,我确实导入了base64,只是忘了在上面包含它。我会适当地编辑这篇文章。谢谢。我已经更新了我的函数以包含您的更改(urllib.quote_plus),但它仍然没有返回与php版本相同的签名…@dlstadther您有签名不同的示例输入吗?我终于得到了匹配的签名。它们依赖于“expires”变量。Php使用strotime(“+60分钟”),这导致UTC时间从现在起60分钟。Python使用了(datetime.date.now()+timedelta(minutes=60)),这导致当前时区中距离现在60分钟的时间。