def get_transactions(): """Return tuple list of transactions from SSOT""" from SSOT import SSOT payment_provider = PaymentProvider.query.first() access_token = payment_provider.gocardless_access_token gc_environment = payment_provider.gocardless_environment target_gateways = ({ "name": "GoCardless", "construct": { "access_token": access_token, "environment": gc_environment } }, ) try: SSOT = SSOT(target_gateways) transactions = SSOT.transactions except gocardless_pro.errors.InvalidApiUsageError as e: logging.error(e.type) logging.error(e.message) flash("Invalid GoCardless API token. Correct your GoCardless API key.") return redirect(url_for("admin.connect_gocardless_manually")) except ValueError as e: logging.error(e.message) if e.message == "No access_token provided": flash("You must connect your GoCardless account first.") return redirect(url_for("admin.connect_gocardless_manually")) else: raise return transactions
def charge_up_front(): jamlaApp = Jamla() jamla = jamlaApp.load(src=app.config['JAMLA_PATH']) charge = {} charge['amount'] = session['upfront_cost'] charge['currency'] = "GBP" 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() con.close() try: stripe.api_key = jamla['payment_providers']['stripe']['secret_key'] customer = stripe.Customer.create(email=res[7], source=request.form['stripeToken']) charge = stripe.Charge.create(customer=customer.id, amount=charge['amount'], currency=charge['currency'], description='Subscribie') except stripe.error.AuthenticationError as e: return str(e) if jamlaApp.requires_subscription(session['package']): return redirect(url_for('establish_mandate')) else: return redirect(url_for('thankyou', _scheme='https', _external=True))
def add_jamla_item(): form = ItemsForm() jamla = get_jamla() if form.validate_on_submit(): draftItem = {} draftItem["uuid"] = str(uuid.uuid4()) draftItem["requirements"] = {} draftItem["primary_icon"] = {"src": "", "type": ""} draftItem["title"] = form.title.data[0].strip() draftItem["requirements"]["subscription"] = bool( form.subscription.data[0]) draftItem["requirements"]["note_to_seller_required"] = bool( form.note_to_seller_required.data[0]) draftItem["requirements"]["note_to_buyer_message"] = str( form.note_to_buyer_message.data[0]) try: days_before_first_charge = int( form.days_before_first_charge.data[0]) except ValueError: days_before_first_charge = 0 draftItem["days_before_first_charge"] = days_before_first_charge if form.monthly_price.data[0] is None: draftItem["monthly_price"] = False else: draftItem["monthly_price"] = float( form.monthly_price.data[0]) * 100 draftItem["requirements"]["instant_payment"] = bool( form.instant_payment.data[0]) if form.sell_price.data[0] is None: draftItem["sell_price"] = False else: draftItem["sell_price"] = float(form.sell_price.data[0]) * 100 draftItem["selling_points"] = form.selling_points.data[0] # Create SKU draftItem["sku"] = form.title.data[0].replace(" ", "").strip() # Primary icon image storage f = form.image.data[0] if f: images = UploadSet("images", IMAGES) filename = images.save(f) # symlink to active theme static directory img_src = "".join( [current_app.config["UPLOADED_IMAGES_DEST"], filename]) link = "".join([current_app.config["STATIC_FOLDER"], filename]) os.symlink(img_src, link) src = url_for("static", filename=filename) draftItem["primary_icon"] = {"src": src, "type": ""} jamla["items"].append(draftItem) fp = open(current_app.config["JAMLA_PATH"], "w") yaml.safe_dump(jamla, fp, default_flow_style=False) flash("Item added.") return redirect(url_for("admin.dashboard")) return render_template("admin/add_jamla_item.html", jamla=jamla, form=form)
def add_item(): form = ItemsForm() if form.validate_on_submit(): draftItem = Item() database.session.add(draftItem) item_requirements = ItemRequirements() draftItem.requirements.append(item_requirements) draftItem.uuid = str(uuid.uuid4()) draftItem.title = form.title.data[0].strip() item_requirements.subscription = bool(form.subscription.data[0]) item_requirements.note_to_seller_required = bool(form.note_to_seller_required.data[0]) item_requirements.note_to_buyer_message = str(form.note_to_buyer_message.data[0]) try: days_before_first_charge = int(form.days_before_first_charge.data[0]) except ValueError: days_before_first_charge = 0 draftItem.days_before_first_charge = days_before_first_charge if form.monthly_price.data[0] is None: draftItem.monthly_price = 0 else: draftItem.monthly_price = int(form.monthly_price.data[0]) * 100 item_requirements.instant_payment = bool( form.instant_payment.data[0] ) if form.sell_price.data[0] is None: draftItem.sell_price = 0 else: draftItem.sell_price = int(form.sell_price.data[0]) * 100 points = form.selling_points.data[0] for point in points: draftItem.selling_points.append(ItemSellingPoints(point=point)) # Primary icon image storage f = form.image.data[0] if f: images = UploadSet("images", IMAGES) filename = images.save(f) # symlink to active theme static directory img_src = "".join([current_app.config["UPLOADED_IMAGES_DEST"], filename]) link = "".join([current_app.config["STATIC_FOLDER"], filename]) os.symlink(img_src, link) src = url_for("static", filename=filename) draftItem.primary_icon = src database.session.commit() flash("Item added.") return redirect(url_for("admin.dashboard")) return render_template("admin/add_item.html", form=form)
def connect_gocardless_manually(): form = GocardlessConnectForm() jamla = get_jamla() jamlaApp = Jamla() jamlaApp.load(jamla=jamla) if jamlaApp.has_connected("gocardless"): gocardless_connected = True else: gocardless_connected = False if form.validate_on_submit(): access_token = form.data["access_token"] jamla["payment_providers"]["gocardless"]["access_token"] = access_token # Check if live or test api key was given if "live" in access_token: jamla["payment_providers"]["gocardless"]["environment"] = "live" else: jamla["payment_providers"]["gocardless"]["environment"] = "sandbox" fp = open(current_app.config["JAMLA_PATH"], "w") # Overwrite jamla file with gocardless access_token yaml.safe_dump(jamla, fp, default_flow_style=False) # Set users current session to store access_token for instant access session["gocardless_access_token"] = access_token return redirect(url_for("admin.dashboard")) else: return render_template( "admin/connect_gocardless_manually.html", form=form, jamla=jamla, gocardless_connected=gocardless_connected, )
def connect_gocardless_manually(): payment_provider = PaymentProvider.query.first() form = GocardlessConnectForm() if payment_provider.gocardless_active: gocardless_connected = True else: gocardless_connected = False if form.validate_on_submit(): access_token = form.data["access_token"] payment_provider.gocardless_access_token = access_token # Check if live or test api key was given if "live" in access_token: payment_provider.gocardless_environment = "live" else: payment_provider.gocardless_environment = "sandbox" payment_provider.gocardless_active = True database.session.commit() # save changes return redirect(url_for("admin.dashboard")) else: return render_template( "admin/connect_gocardless_manually.html", form=form, gocardless_connected=gocardless_connected, )
def gocardless_oauth_complete(): jamlaApp = Jamla() jamla = jamlaApp.load(src=app.config['JAMLA_PATH']) flow = OAuth2WebServerFlow( client_id=app.config['GOCARDLESS_CLIENT_ID'], client_secret=app.config['GOCARDLESS_CLIENT_SECRET'], scope="read_write", # You'll need to use exactly the same redirect URI as in the last step redirect_uri="http://127.0.0.1:5000/connect/gocardless/oauth/complete", auth_uri="https://connect-sandbox.gocardless.com/oauth/authorize", token_uri="https://connect-sandbox.gocardless.com/oauth/access_token", initial_view="signup") access_token = flow.step2_exchange(request.args.get('code')) jamla['payment_providers']['gocardless'][ 'access_token'] = access_token.access_token fp = open(app.config['JAMLA_PATH'], 'w') # Overwrite jamla file with gocardless access_token yaml.safe_dump(jamla, fp, default_flow_style=False) # Set users current session to store access_token for instant access flask_login.current_user.gocardless_access_token = access_token.access_token flask_login.current_user.gocardless_organisation_id = access_token.token_response[ 'organisation_id'] return redirect(url_for('dashboard'))
def connect_stripe_manually(): form = StripeConnectForm() jamlaApp = Jamla() jamla = jamlaApp.load(src=app.config['JAMLA_PATH']) if jamlaApp.has_connected('stripe'): stripe_connected = True else: stripe_connected = False if form.validate_on_submit(): publishable_key = form.data['publishable_key'] secret_key = form.data['secret_key'] jamla['payment_providers']['stripe'][ 'publishable_key'] = publishable_key jamla['payment_providers']['stripe']['secret_key'] = secret_key # Overwrite jamla file with gocardless access_token fp = open(app.config['JAMLA_PATH'], 'w') yaml.safe_dump(jamla, fp, default_flow_style=False) flask_login.current_user.stripe_publishable_key = publishable_key # Set stripe public key JS return redirect(url_for('dashboard')) else: return render_template('connect_stripe_manually.html', form=form, jamla=jamla, stripe_connected=stripe_connected)
def connect_gocardless_manually(): form = GocardlessConnectForm() jamlaApp = Jamla() jamla = jamlaApp.load(src=app.config['JAMLA_PATH']) if jamlaApp.has_connected('gocardless'): gocardless_connected = True else: gocardless_connected = False if form.validate_on_submit(): access_token = form.data['access_token'] jamla['payment_providers']['gocardless']['access_token'] = access_token # Check if live or test api key was given if "live" in access_token: jamla['payment_providers']['gocardless']['environment'] = 'live' else: jamla['payment_providers']['gocardless']['environment'] = 'sandbox' fp = open(app.config['JAMLA_PATH'], 'w') # Overwrite jamla file with gocardless access_token yaml.safe_dump(jamla, fp, default_flow_style=False) # Set users current session to store access_token for instant access flask_login.current_user.gocardless_access_token = access_token return redirect(url_for('dashboard')) else: return render_template('connect_gocardless_manually.html', form=form, jamla=jamla, gocardless_connected=gocardless_connected)
def gocardless_oauth_complete(): jamla = get_jamla() jamlaApp = Jamla() jamlaApp.load(jamla=jamla) flow = OAuth2WebServerFlow( client_id=current_app.config["GOCARDLESS_CLIENT_ID"], client_secret=current_app.config["GOCARDLESS_CLIENT_SECRET"], scope="read_write", # You'll need to use exactly the same redirect URI as in the last # step redirect_uri="http://127.0.0.1:5000/connect/gocardless/oauth/complete", auth_uri="https://connect-sandbox.gocardless.com/oauth/authorize", token_uri="https://connect-sandbox.gocardless.com/oauth/access_token", initial_view="signup", ) access_token = flow.step2_exchange(request.args.get("code")) jamla["payment_providers"]["gocardless"][ "access_token"] = access_token.access_token fp = open(current_app.config["JAMLA_PATH"], "w") # Overwrite jamla file with gocardless access_token yaml.safe_dump(jamla, fp, default_flow_style=False) # Set users current session to store access_token for instant access session["gocardless_access_token"] = access_token.access_token session["gocardless_organisation_id"] = access_token.token_response[ "organisation_id"] return redirect(url_for("admin.dashboard"))
def validate_login(login_token): if len(login_token) < 10: return 'Invalid token' # Try to get email from login_token con = sqlite3.connect(app.config["DB_FULL_PATH"]) con.row_factory = sqlite3.Row # Dict based result set cur = con.cursor() cur.execute('SELECT email FROM user WHERE login_token=?', (login_token, )) result = cur.fetchone() con.close() if result is None: return "Invalid token" # Invaldate previous token new_login_token = urlsafe_b64encode(os.urandom(24)) con = sqlite3.connect(app.config["DB_FULL_PATH"]) cur = con.cursor() cur.execute('UPDATE user SET login_token=? WHERE login_token=?', ( new_login_token, login_token, )) con.commit() con.close() email = result['email'] user = User() user.id = email flask_login.login_user(user) return redirect(url_for('protected')) return "Code is %s" % login_token
def upload_logo(): """Upload shop logo""" form = UploadLogoForm() company = Company.query.first() if form.validate_on_submit(): images = UploadSet("images", IMAGES) f = form.image.data if f is None: flash("File required") else: filename = images.save(f) # symlink to active theme static directory img_src = "".join( [current_app.config["UPLOADED_IMAGES_DEST"], filename]) link = "".join([current_app.config["STATIC_FOLDER"], filename]) symlink(img_src, link, overwrite=True) src = url_for("static", filename=filename) company.logo_src = src database.session.commit() flash("Logo has been uploaded") return render_template("admin/upload_logo.html", form=form, company=company)
def connect_stripe_manually(): form = StripeConnectForm() jamla = get_jamla() jamlaApp = Jamla() jamlaApp.load(jamla=jamla) if jamlaApp.has_connected("stripe"): stripe_connected = True else: stripe_connected = False if form.validate_on_submit(): publishable_key = form.data["publishable_key"].strip() secret_key = form.data["secret_key"].strip() jamla["payment_providers"]["stripe"][ "publishable_key"] = publishable_key jamla["payment_providers"]["stripe"]["secret_key"] = secret_key # Overwrite jamla file with gocardless access_token fp = open(current_app.config["JAMLA_PATH"], "w") yaml.safe_dump(jamla, fp, default_flow_style=False) session["stripe_publishable_key"] = publishable_key # Set stripe public key JS return redirect(url_for("admin.dashboard")) else: return render_template( "admin/connect_stripe_manually.html", form=form, jamla=jamla, stripe_connected=stripe_connected, )
def customers(): jamla = get_jamla() from SSOT import SSOT jamlaApp = Jamla() jamlaApp.load(jamla=jamla) target_gateways = () if jamlaApp.has_connected("gocardless"): access_token = jamla["payment_providers"]["gocardless"]["access_token"] gc_environment = jamla["payment_providers"]["gocardless"][ "environment"] target_gateways = target_gateways + ({ "name": "GoCardless", "construct": { "access_token": access_token, "environment": gc_environment } }, ) if jamlaApp.has_connected("stripe"): stripe_token = jamla["payment_providers"]["stripe"]["secret_key"] target_gateways = target_gateways + ({ "name": "Stripe", "construct": stripe_token }, ) try: SSOT = SSOT(target_gateways) partners = SSOT.partners except gocardless_pro.errors.InvalidApiUsageError as e: logging.error(e.type) logging.error(e.message) flash("Invalid GoCardless API token. Correct your GoCardless API key.") return redirect(url_for("admin.connect_gocardless_manually")) except ValueError as e: logging.error(e.message) if e.message == "No access_token provided": flash("You must connect your GoCardless account first.") return redirect(url_for("admin.connect_gocardless_manually")) else: raise return render_template("admin/customers.html", jamla=jamla, partners=partners)
def store_customer(): form = CustomerForm() if form.validate(): given_name = form.data['given_name'] family_name = form.data['family_name'] address_line_one = form.data['address_line_one'] city = form.data['city'] postcode = form.data['postcode'] email = form.data['email'] mobile = form.data['mobile'] now = datetime.datetime.now() # Store customer in session sid = session['sid'] # Store email in session session['email'] = email # Store plan in session jamlaApp = Jamla() jamla = jamlaApp.load(src=app.config['JAMLA_PATH']) if jamlaApp.sku_exists(request.args.get('plan')): wants = request.args.get('plan') session['plan'] = wants print "##################" con = sqlite3.connect(app.config["DB_FULL_PATH"]) cur = con.cursor() cur.execute( "INSERT INTO person VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (sid, now, given_name, family_name, address_line_one, city, postcode, email, mobile, wants, 'null', 'null', False)) con.commit() con.close() if jamlaApp.requires_instantpayment(session['package']): return redirect( url_for('up_front', _scheme='https', _external=True, sid=sid, package=wants, fname=given_name)) if jamlaApp.requires_subscription(session['package']): return redirect(url_for('establish_mandate')) return redirect(url_for('thankyou', _scheme='https', _external=True)) else: return "Oops, there was an error processing that form, please go back and try again."
def onboard_user_refresh(): if 'account_id' not in session: return redirect(url_for('admin.stripe_onboarding')) account_id = session['account_id'] origin = ('https://' if request.is_secure else 'http://') + request.headers['host'] account_link_url = _generate_account_link(account_id) return redirect(account_link_url)
def refresh_ssot(resource): """Refresh SSOT to fetch newest customers (aka partners) and transactions resource is either "customers" or "transactions" """ jamla = get_jamla() from SSOT import SSOT access_token = jamla["payment_providers"]["gocardless"]["access_token"] gc_environment = jamla["payment_providers"]["gocardless"]["environment"] target_gateways = ({ "name": "GoCardless", "construct": { "access_token": access_token, "environment": gc_environment } }, ) try: SSOT = SSOT(target_gateways, refresh=True) partners = SSOT.partners except gocardless_pro.errors.InvalidApiUsageError as e: logging.error(e.type) logging.error(e.message) flash("Invalid GoCardless API token. Correct your GoCardless API key.") return redirect(url_for("admin.connect_gocardless_manually")) except ValueError as e: logging.error(e.message) if e.message == "No access_token provided": flash("You must connect your GoCardless account first.") return redirect(url_for("admin.connect_gocardless_manually")) else: raise if resource == "customers": flash("Customers refreshed") return redirect(url_for('admin.customers')) if resource == "transactions": flash("Customers refreshed") return redirect(url_for('admin.transactions')) # Fallback flask("Refreshed customers & transactions") return redirect(url_for('admin.dashboard'))
def customers(): payment_provider = PaymentProvider.query.first() from SSOT import SSOT target_gateways = () if payment_provider.gocardless_active: access_token = payment_provider.gocardless_access_token, gc_environment = payment_provider.gocardless_environment, target_gateways = target_gateways + ({ "name": "GoCardless", "construct": { "access_token": access_token, "environment": gc_environment } }, ) if payment_provider.stripe_active: stripe_token = payment_provider.stripe_secret_key target_gateways = target_gateways + ({ "name": "Stripe", "construct": stripe_token }, ) try: SSOT = SSOT(target_gateways) partners = SSOT.partners except gocardless_pro.errors.InvalidApiUsageError as e: logging.error(e.type) logging.error(e.message) flash("Invalid GoCardless API token. Correct your GoCardless API key.") return redirect(url_for("admin.connect_gocardless_manually")) except ValueError as e: logging.error(e.message) if e.message == "No access_token provided": flash("You must connect your GoCardless account first.") return redirect(url_for("admin.connect_gocardless_manually")) else: raise return render_template("admin/customers.html", partners=partners)
def connect_tawk_manually(): integration = Integration.query.first() form = TawkConnectForm() if form.validate_on_submit(): property_id = form.data["property_id"] integration.tawk_property_id = property_id integration.tawk_active = True database.session.commit() return redirect(url_for("admin.dashboard")) else: return render_template("admin/connect_tawk_manually.html", form=form, integration=integration)
def _generate_account_link(account_id): ''' From the Stripe Docs: A user that is redirected to your return_url might not have completed the onboarding process. Use the /v1/accounts endpoint to retrieve the user’s account and check for charges_enabled. If the account is not fully onboarded, provide UI prompts to allow the user to continue onboarding later. The user can complete their account activation through a new account link (generated by your integration). You can check the state of the details_submitted parameter on their account to see if they’ve completed the onboarding process. ''' account_link = stripe.AccountLink.create( type='account_onboarding', account=account_id, refresh_url=url_for('admin.stripe_connect', refresh="refresh", _external=True), return_url=url_for('admin.stripe_connect', success="success", _external=True), ) return account_link.url
def connect_google_tag_manager_manually(): integration = Integration.query.first() form = GoogleTagManagerConnectForm() if form.validate_on_submit(): container_id = form.data["container_id"] integration.google_tag_manager_container_id = container_id integration.google_tag_manager_active = True database.session.commit() return redirect(url_for("admin.dashboard")) else: return render_template( "admin/connect_google_tag_manager_manually.html", form=form, integration=integration)
def transactions(): payment_provider = PaymentProvider.query.first() from SSOT import SSOT access_token = payment_provider.gocardless_access_token, target_gateways = ({"name": "GoCardless", "construct": access_token}, ) try: SSOT = SSOT(target_gateways) transactions = SSOT.transactions except gocardless_pro.errors.InvalidApiUsageError as e: logging.error(e.type) logging(e.message) flash("Invalid GoCardless API token. Correct your GoCardless API key.") return redirect(url_for("admin.connect_gocardless_manually")) except ValueError as e: logging.error(e.message) if e.message == "No access_token provided": flash("You must connect your GoCardless account first.") return redirect(url_for("admin.connect_gocardless_manually")) else: raise return render_template("admin/transactions.html", transactions=transactions)
def stripe_connect(): account = None stripe_express_dashboard_url = None stripe.api_key = current_app.config.get("STRIPE_SECRET_KEY", None) payment_provider = PaymentProvider.query.first() try: account = getStripeAccount(payment_provider.stripe_connect_account_id) if account is not None and account.charges_enabled and account.payouts_enabled: payment_provider.stripe_active = True else: payment_provider.stripe_active = False except (stripe.error.PermissionError, stripe.error.InvalidRequestError, NameError, AttributeError) as e: print(e) account = None # Setup Stripe webhook endpoint if it dosent already exist if account: try: stripe_express_dashboard_url = stripe.Account.create_login_link( account.id).url except stripe.error.InvalidRequestError: stripe_express_dashboard_url = None webhook_url = url_for('views.stripe_webhook', _external=True) if '127.0.0.1' not in request.host: # Dont create webhooks on localhost, use stripe cli for that create_stripe_webhook() else: print(f"Refusing to Stripe webhook on localhost: {webhook_url}") database.session.commit() return render_template( 'admin/settings/stripe/stripe_connect.html', stripe_onboard_path=url_for('admin.stripe_onboarding'), account=account, stripe_express_dashboard_url=stripe_express_dashboard_url)
def connect_tawk_manually(): form = TawkConnectForm() jamla = get_jamla() jamlaApp = Jamla() jamlaApp.load(jamla=jamla) if form.validate_on_submit(): property_id = form.data["property_id"] jamla["integrations"]["tawk"]["property_id"] = property_id jamla["integrations"]["tawk"]["active"] = True # Overwrite jamla file with google tag manager container_id fp = open(current_app.config["JAMLA_PATH"], "w") yaml.safe_dump(jamla, fp, default_flow_style=False) session["tawk_property_id"] = property_id return redirect(url_for("admin.dashboard")) else: return render_template("admin/connect_tawk_manually.html", form=form, jamla=jamla)
def cancel_mandates(email): """Cancel all mandates associated with a given email""" jamla = get_jamla() if "confirm" in request.args: # Get all mandates associated with <email> # Then cancel them transactions = get_transactions() partner_madates = [] for transaction in transactions: # Match email to mandates if transaction.mandate['links']['customer']['email'] == email \ and transaction.mandate['status'] == 'active': partner_madates.append(transaction.mandate) if len(partner_madates) > 0: gocclient = gocardless_pro.Client( access_token=jamla["payment_providers"]["gocardless"] ["access_token"], environment=jamla["payment_providers"]["gocardless"] ["environment"], ) for mandate in partner_madates: # Cancel each mandate for given email removed = False try: req = gocclient.mandates.cancel(mandate['id']) flash("Mandate canceled for {}".format(email)) flash("The mandate ID was: {}".format(mandate['id'])) removed = True except gocardless_pro.errors.InvalidStateError: removed = True flash("Mandate already canceled for {}".format(email)) flash("The mandate ID was: {}".format(mandate['id'])) if removed: # Remove from local mandates list refresh_ssot(resource='customers') return redirect(url_for("admin.customers")) return render_template("admin/cancel_mandates_confirm.html", email=email, jamla=jamla)
def change_password(): """Change password of existing user""" form = ChangePasswordForm() if request.method == "POST": email = session.get('user_id', None) if email is None: return "Email not found in session" if form.validate_on_submit(): user = User.query.filter_by(email=email).first() if user is None: return "User not found with that email" else: user.set_password(request.form["password"]) database.session.commit() flash("Password has been updated") else: return "Invalid password form submission" return redirect(url_for('admin.change_password')) else: return render_template("admin/change_password.html", form=form)
def connect_stripe_manually(): form = StripeConnectForm() payment_provider = PaymentProvider.query.first() if payment_provider.stripe_active: stripe_connected = True else: stripe_connected = False if form.validate_on_submit(): publishable_key = form.data["publishable_key"].strip() secret_key = form.data["secret_key"].strip() payment_provider.stripe_publishable_key = publishable_key payment_provider.stripe_secret_key = secret_key payment_provider.stripe_active = True database.session.commit() # Save changes return redirect(url_for("admin.dashboard")) else: return render_template( "admin/connect_stripe_manually.html", form=form, stripe_connected=stripe_connected, )
def add_shop_admin(): """Add another shop admin""" form = AddShopAdminForm() if request.method == "POST": if form.validate_on_submit(): # Check user dosent already exist email = request.form["email"] if User.query.filter_by(email=email).first() is not None: return f"Error, admin with email ({email}) already exists." user = User() user.email = email user.set_password(request.form["password"]) database.session.add(user) database.session.commit() flash(f"A new shop admin with email {email} has been added") else: return "Invalid add shop admin form submission" return redirect(url_for('admin.add_shop_admin')) else: return render_template("admin/add_shop_admin.html", form=form)
def change_email(): """Change email of existing user""" form = ChangeEmailForm() if request.method == "POST": email = session.get('user_id', None) if email is None: return "Email not found in session" if form.validate_on_submit(): user = User.query.filter_by(email=email).first() if user is None: return "User not found with that email" else: new_email = request.form["email"] user.email = new_email database.session.commit() flash(f"Email has been updated to {new_email}. Please re-login") else: return "Invalid email form submission" return redirect(url_for('admin.change_email')) else: return render_template("admin/change_email.html", form=form)
def create_stripe_webhook(): """ Creates a new webhook, deleting old one if present switching from test to live mode """ stripe.api_key = current_app.config.get("STRIPE_SECRET_KEY", None) webhook_url = url_for('views.stripe_webhook', _external=True) payment_provider = PaymentProvider.query.first() liveMode = False webhookIdExists = False newWebhookNeeded = True if payment_provider.stripe_webhook_endpoint_id is not None: webhookIdExists = True # Determine if in live or test mode by inspecting api keys if ("live" in current_app.config.get("STRIPE_SECRET_KEY", "") and "live" in current_app.config["STRIPE_PUBLISHABLE_KEY"]): liveMode = True else: liveMode = False # Try to get current webhook and check if its in livemode if webhookIdExists: try: current_webhook = stripe.WebhookEndpoint.retrieve( payment_provider.stripe_webhook_endpoint_id) if current_webhook.livemode == liveMode: newWebhookNeeded = False else: stripe.WebhookEndpoint.delete(current_webhook.id) newWebhookNeeded = True except stripe.error.InvalidRequestError as e: newWebhookNeeded = True if newWebhookNeeded and "127.0.0.1" not in current_app.config.get( "SERVER_NAME", ""): # Delete previous webhooks which match the webhook_url webhooks = stripe.WebhookEndpoint.list() for webhook in webhooks: if webhook.url == webhook_url: stripe.WebhookEndpoint.delete(webhook.id) # Create a new webhook try: webhook_endpoint = stripe.WebhookEndpoint.create( url=webhook_url, enabled_events=[ "*", ], description="Subscribie webhook endpoint", connect= True, # endpoint should receive events from connected accounts ) # Store the webhook secret & webhook id payment_provider.stripe_webhook_endpoint_id = webhook_endpoint.id payment_provider.stripe_webhook_endpoint_secret = webhook_endpoint.secret payment_provider.stripe_livemode = liveMode print( f"New webhook id is: {payment_provider.stripe_webhook_endpoint_id}" ) except stripe.error.InvalidRequestError as e: print(e) flash("Error trying to create Stripe webhook") payment_provider.stripe_active = False database.session.commit()