예제 #1
0
def test_create_charge(once, monthly, customer):

    customer.create().id = 10
    recurring = True
    cc_token = 'tok'
    amt = 10000
    email = "*****@*****.**"

    stripe_utils.create_charge(recurring, cc_token, amt, email)
    assert monthly.called

    stripe_utils.create_charge(not recurring, cc_token, amt, email)
    assert once.called
예제 #2
0
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')