Beispiel #1
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"])
Beispiel #2
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'])