Search code examples
phppythonurlencodehmacgravity-forms-plugin

Gravity Forms Signature - From PHP to Python


I need to translate some existing PHP code to Python. This job connects to gravity forms and queries for certain data. In order to make the query, a signature must be calculated in order to verify the connection.

The Gravity Forms web api gives good PHP directions here.

The PHP method is as follows:

function calculate_signature( $string, $private_key ) {
    $hash = hash_hmac( 'sha1', $string, $private_key, true );
    $sig = rawurlencode( base64_encode( $hash ) );
    return $sig;
}

Based on my understanding of Python and the information about hash-hmac and rawurlencoded from php2python.com, I wrote the following:

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

However, the two signatures are not equivalent, and thus Gravity Forms returns a HTTP 403: Bad Request response.

Am I missing something within my translation?


Update (11/04/15)

I have now matched my php and python urls. However, I still receive a 403 error.


Solution

  • The reason the php and python signatures did not match had nothing to do with their calculate_signature() methods.

    The issue was caused by differing expires variables. Php used strtotime("+60 mins") which resulted in a UTC time 60 minutes from now. Whereas Python used datetime.date.now() + timedelta(minutes=60). This is also 60 minutes from now, but in your current timezone.

    I always want to calculate the expire variable in UTC so I replaced my Python calculation with datetime.datetime.utcnow() + timedelta(minutes=60).