diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6ccb3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.DS_Store +.env +.flaskenv +*.pyc +*.pyo +env/ +env* +dist/ +.cache/ +.pytest_cache/ diff --git a/Customer.py b/Customer.py deleted file mode 100644 index 6821ac1..0000000 --- a/Customer.py +++ /dev/null @@ -1,11 +0,0 @@ -# Customer object with limited QBO fields to simplify this sample -class Customer: - def __init__(self, f_name, l_name, m_name, phone, email): - self.given_name = f_name - self.middle_name = m_name - self.family_name = l_name - self.primary_phone = phone - self.primary_email_addr = email - - def print_customer(self): - print self.given_name, self.middle_name, self.family_name, self.primary_phone, self.primary_email_addr diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..18f9993 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Intuit + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..96f6a4a --- /dev/null +++ b/NOTICE @@ -0,0 +1,5 @@ +SampleApp-QuickBooksV3API-Python +Copyright 2026 Intuit + +This product is licensed under the Apache License, Version 2.0. +See the LICENSE file for the full license text. diff --git a/QBOService.py b/QBOService.py new file mode 100644 index 0000000..1382522 --- /dev/null +++ b/QBOService.py @@ -0,0 +1,40 @@ +from flask import session +from utils import context, APICallService +import json +import config + +def create_customer(excel_customer, req_context): + """Create a customer object with customer data from a working dictionary""" + full_name = excel_customer['Full Name'] + name_list = full_name.split(' ') + first_name = name_list[0] + last_name = name_list[-1] + if len(name_list) > 2: + middle_name = str(name_list[1:len(name_list) - 1]) + else: + middle_name = '' + + # Create customer object + customer = { + 'GivenName': first_name, + 'MiddleName': middle_name, + 'FamilyName': last_name, + 'PrimaryPhone': { + 'FreeFormNumber': excel_customer['Phone'] + }, + 'PrimaryEmailAddr': { + 'Address': excel_customer['Email'] + } + } + + uri = '/customer?minorversion=' + config.API_MINORVERSION + response = APICallService.post_request(req_context, uri, customer) + return response + +def get_companyInfo(req_context): + """Get CompanyInfo of connected QBO company""" + uri = "/companyinfo/" + req_context.realm_id + "?minorversion=" + config.API_MINORVERSION + response = APICallService.get_request(req_context, uri) + return response + + diff --git a/README.md b/README.md index ea153a9..9ab7409 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,46 @@ -[][ss1] +[][ss1][][ss2][][ss3] -# Basic data import from Excel to QBO -#### Sample App in Python that implements Connect to Quickbooks button and imports customer data from Excel to QBO company +# Data import from Excel to QBO +#### Sample App in Python that implements Connect to Quickbooks button and imports customer data from Excel to QBO company. This sample app is meant to provide working example of how to make API calls to Quickbooks. Specifically, this sample application demonstrates the following: -- Implementing OAuth to connect an application to a customer's QuickBooks Online company. -- Creating a QB customer with minimal fields that are added from Excel file. +- OAuth2 sample app for a QuickBooks Online company. +- Creating a QB customer that are added from Excel file using Customer API. +- Gets company data using CompanyInfo API -Please note that while these examples work, features not called out above are not intended to be taken and used in production business applications. In other words, this is not a seed project to be taken cart blanche and deployed to your production environment. - -For example, certain concerns are not addressed at all in our samples (e.g. security, privacy, scalability). In our sample apps, we strive to strike a balance between clarity, maintainability, and performance where we can. However, clarity is ultimately the most important quality in a sample app. - -Therefore there are certain instances where we might forgo a more complicated implementation (e.g. caching a frequently used value, robust error handling, more generic domain model structure) in favor of code that is easier to read. In that light, we welcome any feedback that makes our samples apps easier to learn from. - -Note: This app has been developed and tested for MacOS Sierra 10.12 +Please note that while these examples work, features not called out above are not intended to be taken and used in production business applications. In other words, this is not a seed project to be taken cart blanche and deployed to your production environment. For example, certain concerns are not addressed at all in our samples (e.g. security, privacy, scalability). In our sample apps, we strive to strike a balance between clarity, maintainability, and performance where we can. However, clarity is ultimately the most important quality in a sample app. ## Requirements -1. Python 2.7 +1. Python 3.6 2. A [developer.intuit.com](https://developer.intuit.com/) account -3. An app on [developer.intuit.com](https://developer.intuit.com/) and the associated app token, consumer key, and consumer secret -4. This sample app uses several libraries which need to be installed including flask, flask_oauth, ConfigParser, openpyxl, requests_oauthlib +3. An app on [developer.intuit.com](https://developer.intuit.com/) and the associated app keys: + - Client Id and Client Secret for OAuth2 apps; Configure the RedirectUri[http://localhost:5000/callback] in your app's Keys tab on the Intuit developer account, only Accounting scope needed +4. This sample app uses several libraries listed in [requirements.txt](requirements.txt) which need to be installed including flask, openpyxl, requests_oauthlib ## First Time Instructions 1. Clone the GitHub repo to your computer -2. Install libraries mentioned above in Requirements 4. -3. Fill in your [config.ini](config.ini) file values (consumer key and consumer secret) by copying over from the keys section for your app +2. Fill in your [config.py](config.py) file values by copying over from the keys section for your app ## Running the code 1. cd to the project directory -2. Run the command: ```python app.py``` for MacOS/Linux -3. open a browser and enter ```http://localhost:5000``` +2. ```pip install -r requirements.txt``` +3. Run the command: ```python app.py``` for MacOS/Linux +4. open a browser and enter ```http://localhost:5000``` ## High Level Project Overview -1. [app.py](app.py) module works as the view component for the Flask web app -2. [Customer.py](Customer.py) class creates a Customer object with minimum fields. -3. [qb.py](qb.py) modules has methods such as adding customer in Quickbooks Online, handling response, etc. +1. [app.py](app.py) module contains all routes for the Flask web app +2. [QBOService.py](QBOService.py) class creates a Customer in QBO and gets QBO company info + +### Utility modules +3. [excel.py](utils/excel.py) module deals with importing data from [Leads.xlsx](Leads.xlsx) and editing it +4. [context.py](utils/context.py) class for request context object which has all tokens and realm required to make an API call +5. [APICallService.py](utils/APICallService.py) module has POST and GET methods for QBO API +6. [OAuth2Helper.py](utils/OAuth2Helper.py) module has the methos required for OAuth2 flow -##### Utility modules -4. [excel.py](utils/excel.py) module deals with importing data from [Leads.xlsx](Leads.xlsx) and editing it -5. [configRead.py](utils/configRead.py) module deals with reading from config file -6. [context.py](utils/context.py) class for request context object which has all tokens and realm required to make an API call -7. [requestMethods.py](utils/requestMethods.py) module has post method for HTTP requests +#### Note: For other OAuth2 services like Refresh token, Revoke token, etc, refer to [this](https://github.com/IntuitDeveloper/OAuth2PythonSampleApp) app -[ss1]: https://help.developer.intuit.com/s/samplefeedback?cid=9010&repoName=SampleApp-QuickBooksV3API-Python +[ss1]: # +[ss2]: https://customersurveys.intuit.com/jfe/form/SV_9LWgJBcyy3NAwHc?check=Yes&checkpoint=SampleApp-QuickBooksV3API-Python&pageUrl=github +[ss3]: https://customersurveys.intuit.com/jfe/form/SV_9LWgJBcyy3NAwHc?check=No&checkpoint=SampleApp-QuickBooksV3API-Python&pageUrl=github diff --git a/app.py b/app.py index fe69f91..aab00bf 100644 --- a/app.py +++ b/app.py @@ -1,106 +1,135 @@ -# This sample uses code from https://pythonhosted.org/Flask-OAuth/ for OAuth1 login with Twitter from flask import Flask, request, redirect, url_for, session, g, flash, render_template -from flask_oauth import OAuth -from qb import create_customer, add_customer, req_context -from utils import excel, configRead +# from flask_oauth import OAuth +import requests +import urllib +from werkzeug.exceptions import BadRequest +from QBOService import create_customer, get_companyInfo +from utils import excel, context, OAuth2Helper +import config # configuration SECRET_KEY = 'dev key' DEBUG = True -font_color = 'black' -consumerTokens = configRead.consumerTokens() -oauth_url = configRead.oauthUrl() # setup flask app = Flask(__name__) app.debug = DEBUG app.secret_key = SECRET_KEY -oauth = OAuth() -qbo = oauth.remote_app('qbo', - base_url=oauth_url.base_url, - request_token_url=oauth_url.request_token_url, - access_token_url=oauth_url.access_token_url, - authorize_url=oauth_url.authorize_url, - consumer_key=consumerTokens.consumer_key, - consumer_secret=consumerTokens.consumer_sec -) - -@qbo.tokengetter -def get_qbo_token(token=None): - if session.has_key('qbo_token'): - del session['qbo_token'] - return session.get('qbo_token') - @app.route('/') def index(): - access_token = session.get('access_token') - if access_token is None: - return redirect(url_for('auth')) - - access_token = access_token[0] + """Index route""" global customer_list customer_list = excel.load_excel() - return render_template('index.html', + return render_template( + 'index.html', customer_dict=customer_list, title="QB Customer Leads", - text_color=font_color) + ) -# Update leads in html after adding a customer to QBO handled here for simplicity @app.route('/', methods=['POST']) def update_table(): + """Update Excel file after customer is added in QBO""" customer_id = request.form['id'] + + request_context = context.RequestContext(session['realm_id'], session['access_token'], session['refresh_token']) + for customer in customer_list: if customer['Id'] == customer_id: - # Create customer object, add customer to qbo and get response - customer_obj = create_customer(customer) - response_data = add_customer(customer_obj, request_context) - status_code = response_data['status_code'] - message = response_data['message'] - global font_color - font_color = response_data['font_color'] + # Create customer object + response = create_customer(customer, request_context) + # If customer added successfully, remove them from html and excel file - if (status_code == 200): + if (response.status_code == 200): + font_color = 'green' new_customer_list = excel.remove_lead(customer_list, customer_id) - flash(message) - return render_template('index.html', - customer_dict=new_customer_list, - title="QB Customer Leads", - text_color=font_color) - flash(message) + flash('Customer successfully added!') + return render_template( + 'index.html', + customer_dict=new_customer_list, + title='QB Customer Leads', + text_color=font_color + ) + else: + font_color = 'red' + flash('Something went wrong: ' + response.text) return redirect(url_for('index')) - + +@app.route('/company-info') +def company_info(): + """Gets CompanyInfo of the connected QBO account""" + request_context = context.RequestContext(session['realm_id'], session['access_token'], session['refresh_token']) + + response = get_companyInfo(request_context) + if (response.status_code == 200): + return render_template( + 'index.html', + customer_dict=customer_list, + company_info='Company Name: ' + response.json()['CompanyInfo']['CompanyName'], + title='QB Customer Leads', + ) + else: + return render_template( + 'index.html', + customer_dict=customer_list, + company_info=response.text, + title='QB Customer Leads', + ) + @app.route('/auth') def auth(): - return qbo.authorize(callback=url_for('oauth_authorized')) - + """Initiates the Authorization flow after getting the right config value""" + params = { + 'scope': 'com.intuit.quickbooks.accounting', + 'redirect_uri': config.REDIRECT_URI, + 'response_type': 'code', + 'client_id': config.CLIENT_ID, + 'state': csrf_token() + } + url = OAuth2Helper.get_discovery_doc()['authorization_endpoint'] + '?' + urllib.parse.urlencode(params) + return redirect(url) + @app.route('/reset-session') def reset_session(): + """Resets session""" session.pop('qbo_token', None) session['is_authorized'] = False return redirect(request.referrer or url_for('index')) -# If app is authorized, it ends up here with the response -@app.route('/oauth-authorized') -@qbo.authorized_handler -def oauth_authorized(resp): - realm_id = str(request.args.get('realmId')) - next_url = url_for('index') - if resp is None: - flash(u'You denied the request to sign in.') - return redirect(next_url) - # Setting the session using flask session just for the simplicity of this Sample App. It's not the most secure way to do this. - session['is_authorized'] = True - access_token = resp['oauth_token'] - session['access_token'] = access_token - session['realm_id'] = realm_id - session['qbo_token'] = ( - resp['oauth_token'], - resp['oauth_token_secret'] - ) - global request_context - request_context = req_context() +@app.route('/callback') +def callback(): + """Handles callback only for OAuth2""" + #session['realmid'] = str(request.args.get('realmId')) + state = str(request.args.get('state')) + error = str(request.args.get('error')) + if error == 'access_denied': + return redirect(index) + if state is None: + return BadRequest() + elif state != csrf_token(): # validate against CSRF attacks + return BadRequest('unauthorized') + + auth_code = str(request.args.get('code')) + if auth_code is None: + return BadRequest() + + bearer = OAuth2Helper.get_bearer_token(auth_code) + realmId = str(request.args.get('realmId')) + + # update session here + session['is_authorized'] = True + session['realm_id'] = realmId + session['access_token'] = bearer['access_token'] + session['refresh_token'] = bearer['refresh_token'] + return redirect(url_for('index')) - + +def csrf_token(): + token = session.get('csrfToken', None) + if token is None: + token = OAuth2Helper.secret_key() + session['csrfToken'] = token + return token + if __name__ == '__main__': app.run() \ No newline at end of file diff --git a/config.ini b/config.ini deleted file mode 100644 index 206ccda..0000000 --- a/config.ini +++ /dev/null @@ -1,14 +0,0 @@ -[Tokens] -consumer_key = EnterYourConsumerKeyHere -consumer_sec = EnterYourConsumerSecretHere - -[OAuth URLs] -base_url = https://oauth.intuit.com -request_token_url = https://oauth.intuit.com/oauth/v1/get_request_token -access_token_url = https://oauth.intuit.com/oauth/v1/get_access_token -authorize_url = https://appcenter.intuit.com/Connect/Begin - -[API URL] -base_url = https://sandbox-quickbooks.api.intuit.com/v3/company/ - - diff --git a/config.py b/config.py new file mode 100644 index 0000000..698f365 --- /dev/null +++ b/config.py @@ -0,0 +1,15 @@ +DEBUG = False +SQLALCHEMY_ECHO = False + +# OAuth2 credentials +CLIENT_ID= 'EnterClientIDHere' +CLIENT_SECRET = 'EnterClientSecretHere' +REDIRECT_URI = 'http://localhost:5000/callback' + +# Choose environment; default is sandbox +ENVIRONMENT = 'Sandbox' +# ENVIRONMENT = 'Production' + +# Set to latest at the time of updating this app, can be be configured to any minor version +API_MINORVERSION = '23' + diff --git a/qb.py b/qb.py deleted file mode 100644 index b32f508..0000000 --- a/qb.py +++ /dev/null @@ -1,76 +0,0 @@ -import Customer -from utils import configRead, requestMethods -from flask import session -from utils import context -import json - -# Create a customer object with customer data from working dictionary -def create_customer(my_customer): - full_name = my_customer['Full Name'] - name_list = full_name.split(' ') - first_name = name_list[0] - last_name = name_list[-1] - if len(name_list) > 2: - middle_name = str(name_list[1:len(name_list) - 1]) - else: - middle_name = '' - customer = Customer.Customer(first_name, last_name, middle_name, my_customer['Phone'], my_customer['Email']) - return customer - -# Add selected lead as a customer to QBO -def add_customer(customer, req_context): - req_body = json_body(customer) - base_url = configRead.get_api_url() + req_context.realm_id - url = base_url + '/customer' + configRead.get_minorversion(4) - request_data = {'payload': req_body, 'url': url} - response_data = requestMethods.request(request_data, req_context, method='POST') - handled_response = handle_response(response_data) - return handled_response - -# Set the request body for create_customer -def json_body(customer): - req_body = {} - try: - req_body["GivenName"] = customer.given_name - req_body["MiddleName"] = customer.middle_name - req_body["FamilyName"] = customer.family_name - req_body["PrimaryPhone"] = {} - (req_body["PrimaryPhone"])["FreeFormNumber"] = customer.primary_phone - req_body["PrimaryEmailAddr"] = {} - (req_body["PrimaryEmailAddr"])["Address"] = customer.primary_email_addr - except AttributeError: - print 'Customer object has no attributes' - return req_body - -# Get error/success message after response -def handle_response(response_data): - new_reponse = {} - new_reponse['status_code'] = response_data['status_code'] - content = json.loads(response_data['content']) - if response_data['status_code'] != 200: - new_reponse['font_color'] = 'red' - try: - new_reponse['message'] = content['Fault']['Error'][0]['Message'] - except: - new_reponse['message'] = "Some error occurred. Error message not found." - else: - new_reponse['font_color'] = 'green' - new_reponse['message'] = "Success! Customer added to QBO" - # More data from successful response can be retrieved like customer id - return new_reponse - -# Set and get context of the request -def req_context(): - try: - access_tokens = session.get('qbo_token') - access_key = access_tokens[0] - access_sec = access_tokens[1] - realm_id = session.get('realm_id') - except (IndexError,KeyError) as e: - access_key = None - access_sec = None - realm_id = None - print 'ERROR: '+ e - - req_context = context.RequestContext(realm_id, access_key, access_sec) - return req_context diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3073da3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +requests==2.13.0 +Flask==0.12 +# Flask_OAuth==0.12 +Werkzeug==0.11.15 +openpyxl==2.4.4 +requests_oauthlib==0.8.0 diff --git a/templates/index.html b/templates/index.html index 95804d5..48b74a6 100644 --- a/templates/index.html +++ b/templates/index.html @@ -11,9 +11,7 @@
-
-
+
{% if session['is_authorized'] == True %}
+
+ {% if company_info %}
+ {{ company_info }}
+ {% endif %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %}
+
{% endif %}
{% endblock %}
diff --git a/utils/APICallService.py b/utils/APICallService.py
new file mode 100644
index 0000000..1bc4853
--- /dev/null
+++ b/utils/APICallService.py
@@ -0,0 +1,50 @@
+import requests
+from requests_oauthlib import OAuth1
+import config
+import json
+
+def get_request(req_context, uri):
+ """HTTP GET request for QBO API"""
+ headers = { 'Accept': "application/json",
+ 'User-Agent': "PythonSampleApp1"
+ }
+ if config.ENVIRONMENT == "Sandbox":
+ base_url = "https://sandbox-quickbooks.api.intuit.com/v3/company/"
+ else:
+ base_url = "https://quickbooks.api.intuit.com/v3/company/"
+ url = base_url + req_context.realm_id + uri
+ print(url)
+ if config.AUTH_TYPE == "OAuth2":
+ headers['Authorization'] = "Bearer " + req_context.access_token
+ req = requests.get(url, headers=headers)
+ else:
+ auth = OAuth1(req_context.consumer_key, req_context.consumer_secret, req_context.access_key, req_context.access_secret)
+ req = requests.get(url, auth=auth, headers=headers)
+ return req
+
+def post_request(req_context, uri, payload):
+ """HTTP POST request for QBO API"""
+ headers = { 'Accept': "application/json",
+ 'content-type': "application/json; charset=utf-8",
+ 'User-Agent': "PythonSampleApp1"
+ }
+
+ if config.ENVIRONMENT == "Sandbox":
+ base_url = "https://sandbox-quickbooks.api.intuit.com/v3/company/"
+ else:
+ base_url = "https://quickbooks.api.intuit.com/v3/company/"
+ url = base_url + req_context.realm_id + uri
+
+ if config.AUTH_TYPE == "OAuth2":
+ headers['Authorization'] = "Bearer " + req_context.access_token
+ req = requests.post(url, headers=headers, data=json.dumps(payload))
+ else:
+ auth = OAuth1(req_context.consumer_key, req_context.consumer_secret, req_context.access_key, req_context.access_secret)
+ req = requests.post(url, auth=auth, headers=headers, data=json.dumps(payload))
+ return req
+
+
+
+
+
+
diff --git a/utils/OAuth2Helper.py b/utils/OAuth2Helper.py
new file mode 100644
index 0000000..56cd653
--- /dev/null
+++ b/utils/OAuth2Helper.py
@@ -0,0 +1,47 @@
+import requests
+import base64
+import json
+import random
+import config
+
+def get_bearer_token(auth_code):
+ """Gets bearer token from authorization code"""
+ token_endpoint = get_discovery_doc()['token_endpoint']
+ auth_header = 'Basic ' + to_base64(config.CLIENT_ID + ':' + config.CLIENT_SECRET)
+ headers = {
+ 'Accept': 'application/json',
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'Authorization': auth_header
+ }
+ payload = {
+ 'code': auth_code,
+ 'redirect_uri': config.REDIRECT_URI,
+ 'grant_type': 'authorization_code'
+ }
+ r = requests.post(token_endpoint, data=payload, headers=headers)
+ if r.status_code != 200:
+ return r.text
+ bearer = json.loads(r.text)
+ return bearer
+
+def get_discovery_doc():
+ """Gets OAuth2 discover document based on configured environment"""
+ if config.ENVIRONMENT == "Sandbox":
+ req = requests.get("https://developer.intuit.com/.well-known/openid_sandbox_configuration/")
+ else:
+ req = requests.get("https://developer.intuit.com/.well-known/openid_configuration/")
+ if req.status_code >= 400:
+ return ''
+ discovery_doc = req.json()
+ return discovery_doc
+
+def to_base64(s):
+ """String to Base64"""
+ return base64.b64encode(bytes(s, 'utf-8')).decode()
+
+def random_string(length, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
+ return ''.join(random.choice(allowed_chars) for i in range(length))
+
+def secret_key():
+ chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
+ return random_string(40, chars)
\ No newline at end of file
diff --git a/utils/configRead.py b/utils/configRead.py
deleted file mode 100644
index 8026375..0000000
--- a/utils/configRead.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from ConfigParser import SafeConfigParser
-import os.path
-
-def get_filepath(relative_filepath):
- my_path = os.path.abspath(os.path.dirname(__file__))
- path = os.path.join(my_path, relative_filepath)
- return path
-
-config_file = get_filepath('../config.ini')
-
-parser = SafeConfigParser()
-parser.read(config_file)
-
-class consumerTokens:
- def __init__(self):
- self.consumer_key = parser.get('Tokens', 'consumer_key')
- self.consumer_sec = parser.get('Tokens', 'consumer_sec')
-
-class oauthUrl:
- def __init__(self):
- self.base_url = parser.get('OAuth URLs', 'base_url')
- self.request_token_url = parser.get('OAuth URLs', 'request_token_url')
- self.access_token_url = parser.get('OAuth URLs', 'access_token_url')
- self.authorize_url = parser.get('OAuth URLs', 'authorize_url')
-
-def get_api_url():
- return parser.get('API URL', 'base_url')
-
-def get_minorversion(minor_version):
- return '?minorversion='+str(minor_version)
-
-
diff --git a/utils/context.py b/utils/context.py
index 5ae118b..245ba5f 100644
--- a/utils/context.py
+++ b/utils/context.py
@@ -1,16 +1,26 @@
-from configRead import consumerTokens
-# The context class sets the realm id with the consumer tokens every time user authorizes an app for their QB company
+import config
-class RequestContext:
+class RequestContext(object):
+ """The context class sets the realm id with the app's Client tokens every time user authorizes an app for their QB company"""
+ def __init__(self, realm_id, access_token, refresh_token):
+ self.client_id = config.CLIENT_ID
+ self.client_secret = config.CLIENT_SECRET
+ self.realm_id = realm_id
+ self.access_token = access_token
+ self.refresh_token = refresh_token
+ def __str__(self):
+ return self.realm_id
+
+class RequestContextOAuth1(object):
+ """The context class sets the realm id with the app's Consumer tokens every time user authorizes an app for their QB company"""
def __init__(self, realm_id, access_key, access_secret):
- consumer_tokens = consumerTokens()
- self.consumer_key = consumer_tokens.consumer_key
- self.consumer_secret = consumer_tokens.consumer_sec
+ self.consumer_key = config.CONSUMER_KEY
+ self.consumer_secret = config.CONSUMER_SECRET
self.realm_id = realm_id
self.access_key = access_key
self.access_secret = access_secret
- def print_context(self):
- print self.consumer_key, self.consumer_secret, self.realm_id, self.access_secret, self.access_key
+ def __str__(self):
+ return self.realm_id
diff --git a/utils/excel.py b/utils/excel.py
index d7feba4..7439460 100644
--- a/utils/excel.py
+++ b/utils/excel.py
@@ -1,10 +1,13 @@
+import os
import openpyxl
-import configRead
-excel_file = configRead.get_filepath('../Leads.xlsx')
+APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top
+APP_STATIC = os.path.join(APP_ROOT, '../Leads.xlsx')
+
+excel_file = APP_STATIC
-# Excel is loaded into a list of dictionaries
def load_excel():
+ """Excel is loaded into a list of dictionaries"""
wb = openpyxl.load_workbook(filename=excel_file)
ws = wb['data']
@@ -25,9 +28,8 @@ def load_excel():
dict_list.append(d)
return dict_list
-# Update lead in excel worksheet and working dictionary
-# Removing from excel leaves a blank row in the excel
def remove_lead(customer_list, customer_id):
+ """Update lead in excel worksheet and working dictionary; Removing from excel leaves a blank row in the excel"""
wb = openpyxl.load_workbook(filename=excel_file)
ws = wb['data']
for row in ws.iter_rows(min_row=2, max_col=4):
diff --git a/utils/requestMethods.py b/utils/requestMethods.py
deleted file mode 100644
index 35c31f0..0000000
--- a/utils/requestMethods.py
+++ /dev/null
@@ -1,27 +0,0 @@
-import requests
-from requests_oauthlib import OAuth1
-
-# POST for qbo sandbox
-def do_post(url, headers, payload, auth):
- req = requests.post(url, auth=auth, headers=headers, json=payload)
- response_data = {}
- response_data['status_code'] = req.status_code
- response_data['content'] = req.content
- return response_data
-
-def get(url, headers, payload, auth):
- req = requests.get(url, auth=auth, headers=headers, data=payload)
- return req.content
-
-def request(req_data, req_context, method):
- headers = {'Accept': 'application/json', 'content-type': 'application/json; charset=utf-8', 'User-Agent': 'PythonSampleApp1'}
- payload = req_data['payload']
- url = req_data['url']
- auth = OAuth1(req_context.consumer_key, req_context.consumer_secret, req_context.access_key, req_context.access_secret)
- if method == 'POST':
- response_data = do_post(url, headers, payload, auth)
- return response_data
- # else GET method
-
-
-
diff --git a/views/Ratesample.png b/views/Ratesample.png
new file mode 100644
index 0000000..17fb7fd
Binary files /dev/null and b/views/Ratesample.png differ
diff --git a/views/Sample.png b/views/Sample.png
deleted file mode 100644
index 46a5c53..0000000
Binary files a/views/Sample.png and /dev/null differ
diff --git a/views/Thumbdown.png b/views/Thumbdown.png
new file mode 100644
index 0000000..726971a
Binary files /dev/null and b/views/Thumbdown.png differ
diff --git a/views/Thumbup.png b/views/Thumbup.png
new file mode 100644
index 0000000..b42beb6
Binary files /dev/null and b/views/Thumbup.png differ