JDBurnZ / pyminfraud

A Python library to interface with MaxMind's MinFraud web service API.
Other
2 stars 7 forks source link

Chargeback API support #15

Open radzhome opened 8 years ago

radzhome commented 8 years ago

It would be nice include a function call to the chargeback api in order to report fraud.

http://dev.maxmind.com/minfraud/chargeback/

I don't see it in here, is that a feature you would be willing to merge?

JDBurnZ commented 8 years ago

Absolutely.

radzhome commented 8 years ago

Thanks, I'll add it soon.

radzhome commented 7 years ago

Here is my function to do that

FRAUD_SCORES = ('not_fraud', 'suspected_fraud', 'known_fraud')

def minfraud_submit_chargeback(chargeback_code, fraud_score, ip_address, transaction_id):
    """
    Submits a chargeback to minFraud, to help improve their algorithm
    transaction_id: mask id
    :param transaction_id: mask id
    :param ip_address: customers ip
    :param chargeback_code: str, provided by issuer indicating the reason for the chargeback
    :param fraud_score: str, likelihood that a transaction may be fraudulent, see FRAUD_SCORES
    :return: tuple, (bool success, str message).
    A successful POST will return a 204 (No Content) status code.
    Talks to https://minfraud.maxmind.com/minfraud/chargeback
    """
    if fraud_score not in FRAUD_SCORES:
        return False, "Invalid fraud score"  # Same as APIs validation, FRAUD_SCORE_INVALID

    config = get_minfraud_config()

    user_id = config['user_id']
    license_key = config['license_key']

    host_url = "{}://{}{}".format(config['request_protocol'], config['request_host'], config['chargeback_uri'])

    auth = base64.b64encode("{}:{}".format(user_id, license_key))

    headers = {'Content-Type': 'application/json',
               'Authorization': "Basic {}".format(auth)}

    payload = {'chargeback_code': chargeback_code,
               'fraud_score': fraud_score,
               'ip_address': ip_address,
               'transaction_id': transaction_id}

    try:
        minfraud_logger.info("minFraud chargeback Request: {} {}".format(host_url, payload))
        start_time = time.time()
        result = requests.post(host_url, data=json.dumps(payload), headers=headers, timeout=RISK.REQUEST_TIMEOUT)
        run_time = round(time.time() - start_time, 3)  # s.ms
    except Exception as e:
        message = "Error sending chargeback to minFraud."
        logging.info("minfraud_api.minfraud_submit_chargeback error {}. {}: {}.".format(message, type(e).__name__, e))
        minfraud_logger.info("minFraud chargeback Response: None due to error.")
        return False, message

    minfraud_logger.info("minFraud chargeback Response: {} {}s".format(result, run_time))

    success = result.status_code == 204
    if success:
        return success, ""
    else:
        return success, result.content
JDBurnZ commented 7 years ago

I'll look out for a pull request.