コード例 #1
0
ファイル: routes.py プロジェクト: ggorlen/python-nb-donate
def model_stripe_data(req_data):
    app.logger.info("Modelling stripe data")

    if app.config['SINGLE_CCY']:
        ccy_name = "USD"  # FIXME more generic...i mean..maybe

    to_proj = req_data['project_select']
    from_acc_name = req_data['email']
    amount = int(round(float(req_data['charge']), 2) * 100)

    # These will raise errors if not found or more than one found.  They
    # should bubble up to the route.
    project = get_one(Project, {'name': to_proj})
    ccy = get_one(Currency, {'code': ccy_name})

    # Check for user account (e.g. the account from which the spice will flow)
    app.logger.info("Finding account {}.".format(from_acc_name))
    try:
        from_acct = get_one(Account, {'name': from_acc_name, 'ccy': ccy})
    # if it doesn't exist, make it.
    except NoResultFound:
        app.logger.info("Customer Account not found, creating account"
                        " for new customer {}".format(from_acc_name))
        from_acct = Account(name=from_acc_name, ccy=ccy)

    for project_account in project.accounts:
        if project_account.ccy.code == ccy_name:
            to_acct = project_account

    try:
        to_acct
    except NameError:
        app.logger.error("No account with ccy {} "
                         "on project {}".format(ccy_name, to_proj))
        raise NoResultFound

    tx = Transaction(amount=amount, ccy=ccy, payer=from_acct, recvr=to_acct)

    return tx
コード例 #2
0
ファイル: routes.py プロジェクト: ggorlen/python-nb-donate
def donation():
    """ Processes a stripe donation. """

    app.logger.debug("Entering route /donation")
    request_data = request.get_data()
    app.logger.debug("Request Data: {}".format(request_data))

    try:
        params = get_donation_params(request.form)
    except KeyError as e:
        app.logger.debug("Params not set: {}".format(e.args[0]))
        flash("Error: required form value %s not set." % e.args[0])
        return redirect('/index#form')
    except ValueError as e:
        app.logger.debug("Params bad Value: {}".format(e.args[0]))
        flash("Error: please enter a valid amount for your donation")
        return redirect('/index#form')

    app.logger.debug("Params: {}".format(params))
    amt = int(round(float(params['charge']), 2) * 100)
    app.logger.debug("Amount: {}".format(amt))

    try:
        charge_data = create_charge(
            params['recurring'],
            params['stripe_token'],  # appended by donate.js
            amt,
            params['email'])
        app.logger.debug("Charge created: {}".format(charge_data))

    except se.CardError as error:
        if error.json_body is not None:
            err = error.json_body.get('error', {})
            msg = err.get('message', "Unknown Card Error")
            app.logger.error("CardError: {}".format(err))
        else:
            msg = "Unknown Card Error"
            app.logger.error("CardError: {}".format(error))
        flash(msg)
        return redirect('/index#form')
    except se.RateLimitError as error:
        app.logger.warning("RateLimitError hit!")
        flash("Rate limit hit, please try again in a few seconds")
        return redirect('/index#form')
    except se.StripeError as error:
        app.logger.error("StripeError: {}".format(error))
        flash("Unexpected error, please check data and try again."
              "  If the error persists, please contact Noisebridge support")
        return redirect('/index#form')
    except ValueError as error:
        app.logger.error("ValueError: {}".format(error))
        flash("Unexpected error, please check data and try again."
              "  If the error persists, please contact Noisebridge support")
        return redirect('/index#form')
        # TODO log request data, make sure charge failed

    if params['recurring']:
        app.logger.debug("Creating Subscription")

        stripe_sub = StripeSubscription(email=params['email'],
                                        customer_id=charge_data['customer_id'])

        plan_name = "{} / Month".format(amt)

        app.logger.debug("Checking for Stripe Plan {}".format(plan_name))
        try:
            stripe_plan = get_one(StripePlan, {'name': plan_name})
        except NoResultFound:
            app.logger.debug("Creating plan {}".format(plan_name))
            stripe_plan = StripePlan(name=plan_name,
                                     amount=amt,
                                     interval="M",
                                     desc="{}/{}".format(amt, "M"))
            stripe_plan.subscriptions = [stripe_sub]
        try:
            stripe_plan
        except NameError:
            app.logging.error("Something went horribly wrong with StripePlan")

        app.logger.debug("Adding Subscription to "
                         "plan {} for user {}".format(plan_name,
                                                      params['email']))
        stripe_plan.subscriptions.append(stripe_sub)

        try:
            db.session.add(stripe_plan)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    else:
        app.logger.debug("Creating Transaction")
        tx = model_stripe_data(req_data=params)

        app.logger.debug("Creating StripeDonation -  anon: {}, card_id: {}, "
                         "charge_id: {}, email: {}".format(
                             params['anonymous'], params['stripe_token'],
                             charge_data['charge_id'],
                             charge_data['customer_id']))
        sd = StripeDonation(anonymous=params['anonymous'],
                            card_id=params['stripe_token'],
                            charge_id=charge_data['charge_id'],
                            customer_id=charge_data['customer_id'])
        sd.txs = tx

        try:
            db.session.add(tx)
            db.session.add(sd)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    return redirect('/thanks')
コード例 #3
0
def donation():
    genericerrmsg = 'Something went wrong. Please try a different <a href="https://www.noisebridge.net/wiki/Donate_or_Pay_Dues">payment method</a>.'
    app.logger.debug("Entering route /donation")
    request_data = request.get_data()
    app.logger.debug("Request Data: {}".format(request_data))
    """ Verify recaptcha """
    recaptcha_resp_json = None
    try:
        recaptcha_resp_json = get_recaptcha_resp(request)
        app.logger.debug(
            "recaptcha response data: {}".format(recaptcha_resp_json))
    except json.decoder.JSONDecodeError:
        app.logger.debug("failed to json decode request body")
    except Exception as e:
        app.logger.exception("Exception during recaptha")
    if recaptcha_resp_json is None or "score" not in recaptcha_resp_json.keys(
    ) or recaptcha_resp_json["score"] < 0.5:
        app.logger.info(
            "recaptcha score below threshold, stopping payment attempt")
        flash(wrap_err_msg(genericerrmsg))
        return redirect('/index#form')
    """ Processes a stripe donation. """
    try:
        params = get_donation_params(request.form)
    except KeyError as e:
        app.logger.debug("Params not set: {}".format(e.args[0]))
        flash(
            wrap_err_msg("Error: required form value %s not set." % e.args[0]))
        return redirect('/index#form')
    except ValueError as e:
        app.logger.debug("Params bad Value: {}".format(e.args[0]))
        flash(
            wrap_err_msg(
                "Error: please enter a valid amount for your donation"))
        return redirect('/index#form')

    app.logger.debug("Params: {}".format(params))
    amt = int(round(float(params['charge']), 2) * 100)
    app.logger.debug("Amount: {}".format(amt))

    try:
        charge_data = create_charge(
            params['recurring'],
            params['stripe_token'],  # appended by donate.js
            amt,
            params['email'])
        app.logger.debug("Charge created: {}".format(charge_data))

    except se.CardError as error:
        if error.json_body is not None:
            err = error.json_body.get('error', {})
            app.logger.error("CardError: {}".format(err))
        else:
            app.logger.error("CardError: {}".format(error))
        flash(wrap_err_msg(genericerrmsg))
        return redirect('/index#form')
    except se.RateLimitError as error:
        app.logger.warning("RateLimitError hit!")
        flash(wrap_err_msg(genericerrmsg))
        return redirect('/index#form')
    except se.StripeError as error:
        app.logger.error("StripeError: {}".format(error))
        flash(wrap_err_msg(genericerrmsg))
        return redirect('/index#form')
    except ValueError as error:
        app.logger.error("ValueError: {}".format(error))
        flash(wrap_err_msg(genericerrmsg))
        return redirect('/index#form')
        # TODO log request data, make sure charge failed

    if params['recurring']:
        app.logger.debug("Creating Subscription")

        stripe_sub = StripeSubscription(email=params['email'],
                                        customer_id=charge_data['customer_id'])

        plan_name = "{} / Month".format(amt)

        app.logger.debug("Checking for Stripe Plan {}".format(plan_name))
        try:
            stripe_plan = get_one(StripePlan, {'name': plan_name})
        except NoResultFound:
            app.logger.debug("Creating plan {}".format(plan_name))
            stripe_plan = StripePlan(name=plan_name,
                                     amount=amt,
                                     interval="M",
                                     desc="{}/{}".format(amt, "M"))
            stripe_plan.subscriptions = [stripe_sub]
        try:
            stripe_plan
        except NameError:
            app.logging.error("Something went horribly wrong with StripePlan")

        app.logger.debug("Adding Subscription to "
                         "plan {} for user {}".format(plan_name,
                                                      params['email']))
        stripe_plan.subscriptions.append(stripe_sub)

        try:
            db.session.add(stripe_plan)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    else:
        app.logger.debug("Creating Transaction")
        tx = model_stripe_data(req_data=params)

        app.logger.debug("Creating StripeDonation -  anon: {}, card_id: {}, "
                         "charge_id: {}, email: {}".format(
                             params['anonymous'], params['stripe_token'],
                             charge_data['charge_id'],
                             charge_data['customer_id']))
        sd = StripeDonation(anonymous=params['anonymous'],
                            card_id=params['stripe_token'],
                            charge_id=charge_data['charge_id'],
                            customer_id=charge_data['customer_id'])
        sd.txs = tx

        try:
            db.session.add(tx)
            db.session.add(sd)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    return redirect('/thanks')