[Python] PayFast signature (python): generated signature does not match submitted signature

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to submit a PayFast payment using the API tools, in python rather than php (the docs recommended approach).

    I am generating a signature like so:

    import hashlib
    import urllib.parse


    def generate_signature(data: dict, passphrase: str) -> str:
    """
    Generates an MD5 signature for PayFast API request.

    - Assumes data is already in the correct order.
    - URL encodes values with uppercase encoding.
    - Uses '+' for spaces.
    - Encodes passphrase before appending.
    """
    encoded_params = []

    for key, value in data.items():
    if value: # Ignore empty values
    encoded_value = urllib.parse.quote_plus(str(value)).upper() # URL encode & uppercase
    encoded_params.append(f"{key.upper()}={encoded_value}")

    # URL-encode the passphrase as well
    encoded_passphrase = urllib.parse.quote_plus(passphrase).upper()

    # Concatenate parameters
    param_string = "&".join(encoded_params)

    # Append encoded passphrase
    param_string += f"&PASSPHRASE={encoded_passphrase}"

    print(f"String before hashing: {param_string}")

    # Generate MD5 hash
    signature = hashlib.md5(param_string.encode("utf-8")).hexdigest()

    print(f"Generated Signature: {signature}")
    return signature



    Following the docs for the signature generation, it looks like the parameter keys and values are meant to be upper case, and in order as specified by the optional form fields.

    As far as I can tell, this is what I am doing, but I am still getting the error:

    400 signature: Generated signature does not match submitted signature.


    Here is what my generated signature looks like:

    String before hashing:

    MERCHANT_ID=11111111&MERCHANT_KEY=UAAAAAAAAAAHA&RETURN_URL=HTTPS%3A%2F%2AAAAAAAA.EXECUTE-API.AF-SOUTH-1.AMAZONAWS.COM%2FDEV%2FPAYFAST-REDIRECT&CANCEL_URL=HTTPS%3A%2F%2AAAAAAAAA6.EXECUTE-API.AF-SOUTH-1.AMAZONAWS.COM%2FDEV%2FPAYFAST-REDIRECT%3FSTATUS%3DFAILED&NOTIFY_URL=HTTPS%3A%2F%2AAAAAAAAA6.EXECUTE-API.AF-SOUTH-1.AMAZONAWS.COM%2FDEV%2FPAYMENTS%2FPAYFAST-NOTIFY&EMAIL_ADDRESS=JOHN.DOE%40GMAIL.COM&AMOUNT=300&ITEM_NAME=COOL&THING&ITEM_DESCRIPTION=BLAH&BLAH&BLAH&passphrase=PHRASEFROMSANDBOX


    ...which I've redacted of personal information.

    I've tried different orders of the parameters, using lower case for the keys, lowercase for the keys and values. I cannot think of any other reasons why this format is incorrect.

    Any help would be really appreciated!

    Continue reading...

Compartilhe esta Página