Пример #1
0
def establish_mandate():
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)

    if jamlaApp.has_connected("gocardless") is False:
        dashboard_url = url_for("admin.dashboard")
        return """<h1>Shop not set-up yet</h1>
            The shop owner first needs to login to their
            <a href="{}">dahboard</a>, and connect GoCardless to their shop.
            Once this has been completed, you will be able to order.
        """.format(dashboard_url)

    # lookup the customer with sid and get their relevant details
    sid = session["sid"]
    db = get_db()
    res = db.execute("SELECT * FROM person p WHERE p.sid = ?",
                     (sid, )).fetchone()

    logger.info("Person lookup: %s", res)
    # validate that hasInstantPaid is true for the customer
    gocclient = gocardless_pro.Client(
        access_token=jamlaApp.get_secret("gocardless", "access_token"),
        environment=jamla["payment_providers"]["gocardless"]["environment"],
    )

    description = " ".join([jamla["company"]["name"],
                            session["package"]])[0:100]
    redirect_flow = gocclient.redirect_flows.create(
        params={
            "description": description,
            "session_token": sid,
            "success_redirect_url": current_app.config["SUCCESS_REDIRECT_URL"],
            "prefilled_customer": {
                "given_name": res["given_name"],
                "family_name": res["family_name"],
                "address_line1": res["address_line1"],
                "city": res["city"],
                "postal_code": res["postal_code"],
                "email": res["email"],
            },
        })
    # Hold on to this ID - we'll need it when we
    # "confirm" the dedirect flow later
    print("ID: {} ".format(redirect_flow.id))
    print("URL: {} ".format(redirect_flow.redirect_url))

    # Check if we're inside an iframe, if yes redirect to pop-up
    # Issue https://github.com/Subscribie/subscribie/issues/128
    if request.args.get('inside_iframe', 'False') == "True":
        inside_iframe = True
        return render_template("iframe_new_window_redirect.html",
                               redirect_url=redirect_flow.redirect_url,
                               jamla=jamla)
        return '<a href="{}" target="_blank">Continue</a>'.format(
            redirect_flow.redirect_url)
    else:
        return redirect(redirect_flow.redirect_url)
Пример #2
0
def establish_mandate():
    jamlaApp = Jamla()
    jamla = jamlaApp.load(app.config['JAMLA_PATH'])
    #lookup the customer with sid and get their relevant details
    sid = session['sid']
    con = sqlite3.connect(app.config["DB_FULL_PATH"])
    cur = con.cursor()
    cur.execute("SELECT * FROM person p WHERE p.sid = ?", (sid, ))
    res = cur.fetchone()
    print res
    con.close()

    # validate that hasInstantPaid is true for the customer
    gocclient = gocardless_pro.Client(
        access_token=jamlaApp.get_secret('gocardless', 'access_token'),
        environment=jamla['payment_providers']['gocardless']['environment'])

    description = ' '.join([jamla['company']['name'],
                            session['package']])[0:100]

    redirect_flow = gocclient.redirect_flows.create(
        params={
            "description": description,
            "session_token": sid,
            "success_redirect_url": app.config['SUCCESS_REDIRECT_URL'],
            "prefilled_customer": {
                "given_name": res[2],
                "family_name": res[3],
                "address_line1": res[4],
                "city": res[5],
                "postal_code": res[6],
                "email": res[7]
            }
        })
    # Hold on to this ID - we'll need it when we
    # "confirm" the dedirect flow later
    print("ID: {} ".format(redirect_flow.id))
    print("URL: {} ".format(redirect_flow.redirect_url))
    return redirect(redirect_flow.redirect_url)
Пример #3
0
def on_complete_mandate():
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)
    redirect_flow_id = request.args.get("redirect_flow_id")
    logger.info("Recieved flow ID: %s ", redirect_flow_id)

    logger.info(
        "Setting up client environment as: %s",
        jamla["payment_providers"]["gocardless"]["environment"],
    )
    gocclient = gocardless_pro.Client(
        access_token=jamlaApp.get_secret("gocardless", "access_token"),
        environment=jamla["payment_providers"]["gocardless"]["environment"],
    )
    try:
        redirect_flow = gocclient.redirect_flows.complete(
            redirect_flow_id, params={"session_token": session["sid"]})
        logger.info("Confirmation URL: %s", redirect_flow.confirmation_url)
        # Save this mandate & customer ID for the next section.
        logger.info("Mandate: %s", redirect_flow.links.mandate)
        logger.info("Customer: %s", redirect_flow.links.customer)
        session["gocardless_mandate_id"] = redirect_flow.links.mandate
        session["gocardless_customer_id"] = redirect_flow.links.customer
        # Store customer
        sid = session["sid"]
        now = datetime.datetime.now()
        mandate = redirect_flow.links.mandate
        customer = redirect_flow.links.customer
        flow = redirect_flow_id

        con = sqlite3.connect(current_app.config["DB_FULL_PATH"])
        cur = con.cursor()
        cur.execute("SELECT * FROM person WHERE sid = ?", (sid, ))
        row = cur.fetchone()
        customerName = row[2] + " " + row[3]
        customerAddress = row[4] + ", " + row[5] + ", " + row[6]
        customerEmail = row[7]
        customerPhone = row[8]
        chosenPackage = row[9]
        customerExistingLine = row[10]
        customerExistingNumber = row[11]

        logger.info(
            "Creating subscription with amount: %s",
            str(jamlaApp.sku_get_monthly_price(session["plan"])),
        )
        logger.info(
            "Creating subscription with name: %s",
            jamlaApp.sku_get_title(session["plan"]),
        )
        logger.info("Plan session is set to: %s", str(session["plan"]))
        logger.info("Mandate id is set to: %s",
                    session["gocardless_mandate_id"])

        # If days_before_first_charge is set, apply start_date adjustment
        itemIndex = jamlaApp.sku_get_index(session['plan'])
        try:
            days_before_first_charge = jamla['items'][itemIndex][
                'days_before_first_charge']
            if days_before_first_charge == 0 or days_before_first_charge == '':
                start_date = None
            else:
                today = date.today()
                enddate = today + datetime.timedelta(
                    days=int(days_before_first_charge))
                start_date = enddate.strftime('%Y-%m-%d')
        except KeyError:
            start_date = None

        # Create subscription
        print("Creating subscription")
        gocclient.subscriptions.create(
            params={
                "amount": int(jamlaApp.sku_get_monthly_price(session["plan"])),
                "currency": "GBP",
                "name": jamlaApp.sku_get_title(session["plan"]),
                "interval_unit": "monthly",
                "metadata": {
                    "sku": session["plan"]
                },
                "links": {
                    "mandate": session["gocardless_mandate_id"]
                },
                "start_date": start_date
            })
    except Exception as e:
        logger.error(e)
        if isinstance(e, gocardless_pro.errors.InvalidStateError):
            if e.error["type"] == "invalid_state":
                # Allow pass through if redirect flow already completed
                if e.errors[0]["reason"] == "redirect_flow_already_completed":
                    pass
    # Display a confirmation page to the customer, telling them
    # their Direct Debit has been set up.
    return redirect(current_app.config["THANKYOU_URL"])
Пример #4
0
def on_complete_mandate():
    jamlaApp = Jamla()
    jamla = jamlaApp.load(app.config['JAMLA_PATH'])
    redirect_flow_id = request.args.get('redirect_flow_id')
    print("Recieved flow ID: {} ".format(redirect_flow_id))

    print "Setting up client environment as: " + jamla['payment_providers'][
        'gocardless']['environment']
    gocclient = gocardless_pro.Client(
        access_token=jamlaApp.get_secret('gocardless', 'access_token'),
        environment=jamla['payment_providers']['gocardless']['environment'])
    try:
        redirect_flow = gocclient.redirect_flows.complete(
            redirect_flow_id, params={"session_token": session['sid']})
        print("Confirmation URL: {}".format(redirect_flow.confirmation_url))
        # Save this mandate & customer ID for the next section.
        print("Mandate: {}".format(redirect_flow.links.mandate))
        print("Customer: {}".format(redirect_flow.links.customer))
        session['gocardless_mandate_id'] = redirect_flow.links.mandate
        session['gocardless_customer_id'] = redirect_flow.links.customer
        # Store customer
        sid = session['sid']
        now = datetime.datetime.now()
        mandate = redirect_flow.links.mandate
        customer = redirect_flow.links.customer
        flow = redirect_flow_id

        con = sqlite3.connect(app.config['DB_FULL_PATH'])
        cur = con.cursor()
        cur.execute("SELECT * FROM person WHERE sid = ?", (sid, ))
        row = cur.fetchone()
        customerName = row[2] + " " + row[3]
        customerAddress = row[4] + ", " + row[5] + ", " + row[6]
        customerEmail = row[7]
        customerPhone = row[8]
        chosenPackage = row[9]
        customerExistingLine = row[10]
        customerExistingNumber = row[11]

        print "Creating subscription with amount: " + str(
            jamlaApp.sku_get_monthly_price(session['plan']))
        print "Creating subscription with name: " + jamlaApp.sku_get_title(
            session['plan'])
        print "Plan session is set to: " + str(session['plan'])
        print "Mandate id is set to: " + session['gocardless_mandate_id']

        # Create subscription
        gocclient.subscriptions.create(
            params={
                "amount": jamlaApp.sku_get_monthly_price(session['plan']),
                "currency": "GBP",
                "name": jamlaApp.sku_get_title(session['plan']),
                "interval_unit": "monthly",
                "metadata": {
                    "sku": session['plan']
                },
                "links": {
                    "mandate": session['gocardless_mandate_id']
                }
            })
    except Exception as e:
        print e
        if isinstance(e, gocardless_pro.errors.InvalidStateError):
            if e.error['type'] == 'invalid_state':
                # Allow pass through if redirect flow already completed
                if e.errors[0]['reason'] == "redirect_flow_already_completed":
                    pass
    # Display a confirmation page to the customer, telling them
    # their Direct Debit has been set up.
    return redirect(app.config['THANKYOU_URL'])