kount util

kount.util.address module

kount.util.cartitem module

kount.util.khash module

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the Kount python sdk project
# https://github.com/Kount/kount-ris-python-sdk/)
# Copyright (C) 2017 Kount Inc. All Rights Reserved.
"class Khash"

from __future__ import (absolute_import, unicode_literals,
                        division, print_function)

import hashlib
import logging
import re
import string

from kount.resources.correct_key_cryp import correct_key_cryp
from kount.version import VERSION
from .a85 import a85decode
from kount.config import SDKConfig

__author__ = SDKConfig.SDK_AUTHOR
__version__ = VERSION
__maintainer__ = SDKConfig.SDK_MAINTAINER
__email__ = SDKConfig.MAINTAINER_EMAIL
__status__ = SDKConfig.STATUS

LOG = logging.getLogger('kount.khash')


def validator(*args):
    """check is list with arguments is valid -
    positive integer or length of the string
    Args: list with integers or strings
    returns: list with args as strings
    """
    for current in args:
        try:
            str(current)
            is_string = True
        except ValueError:
            is_string = False
        curr_len = len(str(current))
        invalid = curr_len < 6 or curr_len > 100 or current is None
        try:
            current = int(current)
            is_digit = True
        except (TypeError, ValueError):
            is_digit = False
        if is_digit and int(current) <= 0:
            raise ValueError("incorrect arg: [%s]" % current)
        elif invalid or not is_string:
            raise ValueError("incorrect arg: [%s]" % current)
    return [str(i) for i in args]


class Khash(object):

    re_khashed = re.compile(r"^[0-9a-zA-Z]{6}[0-9A-Z]{14}$")
    __instance = None

    @staticmethod
    def get():
        """ Static access method. """
        SDKConfig.setup(SDKConfig._CONFIGURATION_KEY)
    
        return Khash.__instance

    """
    Class for creating Kount RIS KHASH encoding payment tokens.
    """
    def __init__(self, key):
        """ Virtually private constructor. """
        hash_salt_key = a85decode(key)
        self.config_key = hash_salt_key.decode("utf-8")
        self.verify()
        self.salt_key = hash_salt_key
        Khash.__instance = self

    def verify(self):
        key = self.config_key.encode('utf-8')
        sha_key = hashlib.sha256(key).hexdigest()
        if sha_key != correct_key_cryp:
            mesg = "Configured config_key key is incorrect"
            LOG.error(mesg)
            raise ValueError(mesg)
        
        LOG.info("Configured config_key is correct.")
        return True

    def hash_payment_token(self, token):
        """Create a Kount hash of a provided payment token. Payment tokens
        that can be hashed via this method include: credit card numbers,
        Paypal payment IDs, Check numbers, Google Checkout IDs, Bill Me
        Later IDs, and Green Dot MoneyPak IDs.

        Args: token - String to be hashed
        returns: String hashed
        if len(token) < 6 - need to clarify the expected behaviour
        """
        token_valid = validator(token)[0]
        return "%s%s" % (token_valid[:6], self.hash(plain_text=token_valid))

    def hash_gift_card(self, merchant_id, card_number):
        """ Hash a gift card payment token using the Kount hashing algorithm.
        Args: merchant_id - Merchant ID number
        card_number - Card number to be hashed
        returns: String hashed
        """
        merchant_id, card_number = validator(merchant_id, card_number)
        return "%s%s" % (merchant_id, self.hash(plain_text=card_number))

    def hash(self, plain_text):
        """
        Compute a Kount hash of a given plain text string.
        Preserves the first six characters of the input
        so that hashed tokens can be categorized
        by Bank Identification Number (BIN).
        Args: plain_text - String to be hashed
        returns: String hashed
        """
        if isinstance(plain_text, int):
            plain_text = str(plain_text)
        if validator(plain_text):
            legal_chars = string.digits + string.ascii_uppercase
            loop_max = 28
            hex_chunk = 7
            length = len(legal_chars)
            hashed = []
            plain_text_bytes = plain_text.encode('utf-8')  # Python 3.x
            sha1 = hashlib.sha1(plain_text_bytes + ".".encode('utf-8') +
                                self.salt_key).hexdigest()
            for i in range(0, loop_max, 2):
                hashed.append(legal_chars[int(sha1[i: i + hex_chunk], 16)
                                          % length])
            return ''.join(hashed)
        else:
            raise ValueError("incorrect arg: [%s]" % plain_text)

    @classmethod
    def khashed(cls, val):
        """ Arg: val - String, Token that may or may not be khashed
         return: Boolean, True if token is already khashed
        """
        return cls.re_khashed.match(val)

kount.util.payment module

#!/usr/bin/env python
"class Payment - RIS payment type object"
# -*- coding: utf-8 -*-
# This file is part of the Kount python sdk project
# https://github.com/Kount/kount-ris-python-sdk/)
# Copyright (C) 2017 Kount Inc. All Rights Reserved.

from kount.util.khash import Khash
from kount.version import VERSION
from kount.config import SDKConfig

__author__ = SDKConfig.SDK_AUTHOR
__version__ = VERSION
__maintainer__ = SDKConfig.SDK_MAINTAINER
__email__ = SDKConfig.MAINTAINER_EMAIL
__status__ = SDKConfig.STATUS


class Payment(object):
    """RIS payment type object.
    Args:
    payment_type - Payment type.
    payment_token - Payment token
    khashed - Indicates whether payment token is khashed.
    True if payment token is khashed.
    """
    def __init__(self, payment_type=None, payment_token=None, khashed=True):
        """Constructor for a payment that accepts the payment ID.
        Calculate and set the payment token LAST4 value.
        last4 - Last 4 characters of payment token"""
        self.last4 = "NONE"
        self.payment_token = None
        if payment_type is not None:
            self._payment_type = str(payment_type)
        else:
            self._payment_type = "NONE"

        if payment_token is not None:
            self.payment_token = str(payment_token)
            if len(self.payment_token) >= 4:
                self.last4 = self.payment_token[-4:]
            if khashed:
                self.khashed = self.khash_token()
        self.khashed = khashed and Khash.khashed(self.payment_token)

    @property
    def payment_type(self):
        return self._payment_type

    def khash_token(self):
        "hash the payment_token, return True if khashed, else raise ValueError"
        k = Khash.get()
        self.payment_token = k.hash_payment_token(
            token=self.payment_token)
        if k.khashed(self.payment_token):
            return True
        raise ValueError("payment_token [%s] is not khashed" %
                         self.payment_token)


class GiftCardPayment(Payment):
    """Sets the PTYP parameter to GIFT,
    params: gift_card_number,
     khashed - boolean"""
    def __init__(self, gift_card_number, khashed=True):
        super(GiftCardPayment, self).__init__(
            payment_type="GIFT",
            payment_token=gift_card_number,
            khashed=khashed)


class GooglePayment(Payment):
    """Sets the PTYP parameter to "GIFT".
    params: google_payment_id - Google payment ID
                khashed - boolean"""
    def __init__(self, google_payment_id, khashed=True):
        super(GooglePayment, self).__init__(
            payment_type="GOOG",
            payment_token=google_payment_id,
            khashed=khashed)


class GreenDotMoneyPakPayment(Payment):
    """Sets the PTYP parameter to "GDMP".
    params: green_dot_mp_payment - Green Dot MoneyPak payment ID number
            khashed - boolean"""
    def __init__(self, green_dot_mp_payment, khashed=True):
        super(GreenDotMoneyPakPayment, self).__init__(
            payment_type="GDMP",
            payment_token=green_dot_mp_payment,
            khashed=khashed)


class NoPayment(Payment):
    """No payment type. Sets the PTYP parameter to "NONE", not khashed"""
    def __init__(self, *args, **kwargs):
        super(NoPayment, self).__init__(
            payment_type=None,
            payment_token=None,
            khashed=False)


class CheckPayment(Payment):
    """Sets the PTYP parameter to "CHEK".
    params: micr - The MICR (Magnetic Ink Character Recognition)
                line on the check.
            khashed - boolean
    """
    def __init__(self, micr, khashed=True):
        super(CheckPayment, self).__init__(
            payment_type="CHEK",
            payment_token=micr,
            khashed=khashed)


class PaypalPayment(Payment):
    """paypal payment - accepts the paypal payment ID.
    Sets the PTYP parameter to "PYPL".
    params: paypal_payment_id - Paypal payment ID
            khashed - boolean
    """
    def __init__(self, paypal_payment_id, khashed=True):
        super(PaypalPayment, self).__init__(
            payment_type="PYPL",
            payment_token=paypal_payment_id,
            khashed=khashed)


class CardPayment(Payment):
    """credit card payment
    Sets the PTYP parameter to "CARD".
    params: card_number - The card number
            khashed - boolean
    """

    def __init__(self, card_number, khashed=True):
        super(CardPayment, self).__init__(
            payment_type="CARD",
            payment_token=card_number,
            khashed=khashed)


class BillMeLaterPayment(Payment):
    """bill me later payment
    Sets the PTYP parameter to "BLML".
    params: payment_id - The payment ID,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(BillMeLaterPayment, self).__init__(
            payment_type="BLML",
            payment_token=payment_id,
            khashed=khashed)


class ApplePay(Payment):
    """Apple Pay
    Sets the PTYP parameter to "APAY".
    params: payment_id - apay,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(ApplePay, self).__init__(
            payment_type="APAY",
            payment_token=payment_id,
            khashed=khashed)


class BPayPayment(Payment):
    """BPay Payment
    Sets the PTYP parameter to "BPAY".
    params: payment_id - bpay,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(BPayPayment, self).__init__(
            payment_type="BPAY",
            payment_token=payment_id,
            khashed=khashed)


class CarteBleuePayment(Payment):
    """Carte Bleue Payment
    Sets the PTYP parameter to "CARTE_BLEUE".
    params: payment_id - Carte Bleue id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(CarteBleuePayment, self).__init__(
            payment_type="CARTE_BLEUE",
            payment_token=payment_id,
            khashed=khashed)


class ELVPayment(Payment):
    """ELV Payment
    Sets the PTYP parameter to "ELV".
    params: payment_id - ELV id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(ELVPayment, self).__init__(
            payment_type="ELV",
            payment_token=payment_id,
            khashed=khashed)


class GiroPayPayment(Payment):
    """GIROPAY Payment
    Sets the PTYP parameter to "GIROPAY".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(GiroPayPayment, self).__init__(
            payment_type="GIROPAY",
            payment_token=payment_id,
            khashed=khashed)


class InteracPayment(Payment):
    """Interac Payment
    Sets the PTYP parameter to "INTERAC".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(InteracPayment, self).__init__(
            payment_type="INTERAC",
            payment_token=payment_id,
            khashed=khashed)


class MercadoPagoPayment(Payment):
    """Mercado Pago Payment
    Sets the PTYP parameter to "MERCADE_PAGO".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(MercadoPagoPayment, self).__init__(
            payment_type="MERCADE_PAGO",
            payment_token=payment_id,
            khashed=khashed)


class NetellerPayment(Payment):
    """Neteller Payment
    Sets the PTYP parameter to "NETELLER".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(NetellerPayment, self).__init__(
            payment_type="NETELLER",
            payment_token=payment_id,
            khashed=khashed)


class PoliPayment(Payment):
    """POLi Payment
    Sets the PTYP parameter to "POLI".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(PoliPayment, self).__init__(
            payment_type="POLI",
            payment_token=payment_id,
            khashed=khashed)


class SEPAPayment(Payment):
    """Single Euro Payments Area Payment
    Sets the PTYP parameter to "SEPA".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(SEPAPayment, self).__init__(
            payment_type="SEPA",
            payment_token=payment_id,
            khashed=khashed)


class SofortPayment(Payment):
    """Sofort Payment
    Sets the PTYP parameter to "SOFORT".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(SofortPayment, self).__init__(
            payment_type="SOFORT",
            payment_token=payment_id,
            khashed=khashed)


class TokenPayment(Payment):
    """Token Payment
    Sets the PTYP parameter to "TOKEN".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(TokenPayment, self).__init__(
            payment_type="TOKEN",
            payment_token=payment_id,
            khashed=khashed)


class SkrillPayment(Payment):
    """Skrill/Moneybookers Payment
    Sets the PTYP parameter to "SKRILL".
    params: payment_id - id,
            khashed - boolean
    """
    def __init__(self, payment_id, khashed=True):
        super(SkrillPayment, self).__init__(
            payment_type="SKRILL",
            payment_token=str(payment_id),
            khashed=khashed)


def NewPayment(payment_type, payment_token, khashed=True):
    """User-defined payment type
    Sets the PTYP parameter to desired parameter.
    params: payment_type
            payment_token
            khashed - boolean
    """
    return Payment(payment_type, payment_token, khashed=khashed)

kount.util.risexception module

kount.util.validation_error module

kount.util.xmlparser module