comnpay.py 2.59 KB
Newer Older
1 2 3 4 5
"""cotisations.payment_utils.comnpay
The module in charge of handling the negociation with Comnpay
for online payment
"""

6 7 8 9 10 11
import time
from random import randrange
import base64
import hashlib
from collections import OrderedDict

12

13
class Transaction():
14 15 16
    """ The class representing a transaction with all the functions
    used during the negociation
    """
17

18 19
    def __init__(self, vad_number="", secret_key="", urlRetourOK="",
                 urlRetourNOK="", urlIPN="", source="", typeTr="D"):
20 21 22 23 24 25 26
        self.vad_number = vad_number
        self.secret_key = secret_key
        self.urlRetourOK = urlRetourOK
        self.urlRetourNOK = urlRetourNOK
        self.urlIPN = urlIPN
        self.source = source
        self.typeTr = typeTr
27
        self.idTransaction = ""
28

29 30
    def buildSecretHTML(self, produit="Produit", montant="0.00",
                        idTransaction=""):
31 32 33
        """ Build an HTML hidden form with the different parameters for the
        transaction
        """
34
        if idTransaction == "":
35 36 37
            self.idTransaction = str(time.time())
            self.idTransaction += self.vad_number
            self.idTransaction += str(randrange(999))
38 39 40
        else:
            self.idTransaction = idTransaction

41
        array_tpe = OrderedDict(
42 43 44 45 46 47 48 49 50 51
            montant=str(montant),
            idTPE=self.vad_number,
            idTransaction=self.idTransaction,
            devise="EUR",
            lang='fr',
            nom_produit=produit,
            source=self.source,
            urlRetourOK=self.urlRetourOK,
            urlRetourNOK=self.urlRetourNOK,
            typeTr=str(self.typeTr)
52 53
        )

54
        if self.urlIPN != "":
55 56
            array_tpe['urlIPN'] = self.urlIPN

57 58 59 60 61
        array_tpe['key'] = self.secret_key
        strWithKey = base64.b64encode(bytes(
            '|'.join(array_tpe.values()),
            'utf-8'
        ))
62 63 64 65 66
        del array_tpe["key"]
        array_tpe['sec'] = hashlib.sha512(strWithKey).hexdigest()

        ret = ""
        for key in array_tpe:
67
            ret += '<input type="hidden" name="{k}" value="{v}"/>'.format(
Maël Kervella's avatar
Maël Kervella committed
68
                k=key,
69
                v=array_tpe[key]
70
            )
71 72 73

        return ret

74 75 76
    @staticmethod
    def validSec(values, secret_key):
        """ Check if the secret value is correct """
77 78 79
        if "sec" in values:
            sec = values['sec']
            del values["sec"]
80 81 82 83
            strWithKey = hashlib.sha512(base64.b64encode(bytes(
                '|'.join(values.values()) + "|" + secret_key,
                'utf-8'
            ))).hexdigest()
84 85 86
            return strWithKey.upper() == sec.upper()
        else:
            return False