├── LICENSE.txt ├── README.md ├── SampleAppOAuth ├── __init__.py ├── __init__.pyc ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ ├── apps.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── services.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── views.cpython-36.pyc ├── admin.py ├── admin.pyc ├── apps.py ├── apps.pyc ├── migrations │ ├── __init__.py │ └── __pycache__ │ │ └── __init__.cpython-36.pyc ├── models.py ├── models.pyc ├── services.py ├── static │ ├── C2QB_white_btn_lg_default.png │ ├── C2QB_white_btn_lg_hover.png │ └── IntuitSignIn-lg-white@2x.jpg ├── templates │ └── index.html ├── tests.py ├── urls.py ├── urls.pyc └── views.py ├── SampleInvoiceCRUD ├── InvoiceUtils │ ├── LineDetailHelper.py │ ├── __pycache__ │ │ ├── LineDetailHelper.cpython-36.pyc │ │ ├── context.cpython-36.pyc │ │ ├── requestsQBO.cpython-36.pyc │ │ └── services.cpython-36.pyc │ └── services.py ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ ├── invoice_crud.cpython-36.pyc │ ├── lineDetail.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── views.cpython-36.pyc ├── admin.py ├── apps.py ├── invoice_crud.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ │ └── __init__.cpython-36.pyc ├── models.py ├── templates │ └── invoice.html ├── tests.py ├── urls.py └── views.py ├── SampleInvoiceCRUDUsingDict ├── InvoiceDictUtils │ ├── Services.py │ └── __pycache__ │ │ ├── Services.cpython-36.pyc │ │ ├── context.cpython-36.pyc │ │ └── requestsQBO.cpython-36.pyc ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ ├── invoice_crud.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── views.cpython-36.pyc ├── admin.py ├── apps.py ├── invoice_crud.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ │ └── __init__.cpython-36.pyc ├── models.py ├── templates │ └── invoiceUsingDict.html ├── tests.py ├── urls.py └── views.py ├── SampleWebhooks ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── services.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── views.cpython-36.pyc ├── admin.py ├── apps.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ │ └── __init__.cpython-36.pyc ├── models.py ├── services.py ├── templates │ └── webhooks.html ├── tests.py ├── urls.py └── views.py ├── __pycache__ └── invoice.cpython-36.pyc ├── db.sqlite3 ├── manage.py ├── mysite ├── __init__.py ├── __init__.pyc ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── settings.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── wsgi.cpython-36.pyc ├── settings.py ├── settings.pyc ├── urls.py ├── urls.pyc ├── utils │ ├── __pycache__ │ │ ├── context.cpython-36.pyc │ │ └── httpRequests.cpython-36.pyc │ ├── context.py │ └── httpRequests.py └── wsgi.py ├── requirements.txt └── views ├── Callout.png ├── Ratesample.png ├── Thumbdown.png └── Thumbup.png /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Intuit, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Rate your Sample](views/Ratesample.png)][ss1][![Yes](views/Thumbup.png)][ss2][![No](views/Thumbdown.png)][ss3] 2 | 3 | ## Python V3 Invoice Sample App 4 | ### Sample App in Python that implements OAuth1, Invoice CRUD and Webhooks while also provides support for OAuth2 5 | 6 | This sample app is meant to provide working example of how to make API calls to QuickBooks. Specifically, this sample application demonstrates the following: 7 | 8 | 1. Implementing OAuth1 to connect an application to a customer's QuickBooks Online company. 9 | 2. Invoicing which supports create, read, update, delete and query operations using: 10 | 1. Invoice object 11 | 2. Dictionary 12 | 3. Webhooks 13 | 14 | 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. 15 | 16 | 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. 17 | 18 | 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. 19 | 20 | Note: This app has been developed and tested for MacOS Sierra 10.12 21 | 22 | ### Table of Contents 23 | 24 | * [Getting Started](#getting-started) 25 | * [Project Structure](#project-structure) 26 | * [OAuth1 Implementation](#oauth1-implementation) 27 | * [Invoice CRUD Using Object](#invoice-crud-using-object) 28 | * [Invoice CRUD Using Dictionary](#invoice-crud-using-dictionary) 29 | * [Webhooks](#webhooks) 30 | 31 | 32 | ### Getting Started 33 | 34 | Clone the repository: 35 | ``` 36 | git clone https://github.com/IntuitDeveloper/PythonV3InvoiceSampleApp.git 37 | ``` 38 | 39 | Install Python 3.5: 40 | ``` 41 | https://www.python.org/ 42 | ``` 43 | 44 | Use requirements.txt file: 45 | ``` 46 | cd PythonV3InvoiceSampleApp/ 47 | pip install -r requirements.txt 48 | ``` 49 | 50 | Launch your app: 51 | ``` 52 | cd PythonV3InvoiceSampleApp/ 53 | python manage.py runserver 54 | ``` 55 | 56 | ### Project Structure 57 | This project is divided into 4 apps. They're mostly independent of each other (except for OAuth1 apps) so that developers can pick and choose the app they want to use. The apps are as follows: 58 | 1. SampleAppOAuth 59 | 2. SampleInvoiceCRUD 60 | 3. SampleInvoiceCRUDUsingDict 61 | 4. SampleWebhooks 62 | 63 | All app settings can be found at [settings.py](mysite/settings.py) and apps use common utility modules found in [context.py](mysite/utils/context.py) and [httpRequests.py](mysite/utils/httpRequests.py). 64 | 65 | Please go to each app to see how to configure and run it. 66 | 67 | ### OAuth1 Implementation 68 | This app shows how to use you app's consumer token and consumer secret and get OAuth access token, access secret and realm id. Skip this project if your app uses OAuth1 and go to Configure this app section to use OAuth2 access token for other features. 69 | 70 | To implement OAuth2, please refer to [OAuth2PythonSampleApp](https://github.com/IntuitDeveloper/OAuth2PythonSampleApp) 71 | 72 | #### Configure this app 73 | Please enter your app's consumer token and consumer secret in [settings.py](mysite/settings.py). Then follow the steps given above to launch the app and go to url `http://localhost:8000/oauth` 74 | 75 | ### Invoice CRUD Using Object 76 | This app shows how to create, read, update, delete and query Invoice using objects. 77 | 78 | #### Configure this app 79 | For OAuth2 apps, please go to [OAuth2 playgorund](https://developer.intuit.com/v2/ui#/playground) and follow the OAuth2 flow and then copy-paste the access token and associated realm id in [settings.py](mysite/settings.py). 80 | 81 | This app by default uses OAuth2 tokens, if your have OAuth1 app and would like to run this app, please go to [settings.py](mysite/settings.py) and change `oauth_flag` to 1, follow steps from OAuth1 implementation to run it and save access tokens and realm id to session. 82 | 83 | Then follow the steps given above to launch the app and go to url `http://localhost:8000/invoice` 84 | 85 | ### Invoice CRUD Using Dictionary 86 | This app shows how to create, read, update, delete and query Invoice using dictionary. 87 | 88 | #### Configure this app 89 | For OAuth1 and OAuth2 token configuration see the steps given in Invoice CRUD Using Object. 90 | 91 | Then follow the steps given above to launch the app and go to url `http://localhost:8000/invoiceUsingDict` 92 | 93 | ### Webhooks 94 | This app shows how to receive webhooks for authorized sandbox company for subscribed entities. 95 | 96 | #### Configure this app 97 | 1. Install ngrok and launch ngrok with command `ngrok http 8000` 98 | 2. Copy the https url you get from the ngrok server after it launches, paste it as `https:///webhooks` 99 | in app's Webhooks tab to field `Endpoint URL`, select entities and click Save. 100 | 3. Copy the webhooks verifier after clicking Save and paste it in [settings.py](mysite/settings.py) 101 | Note: For now, `webhooks_subscribed_entities` is saved for Customer and Term. It will need to be updated for other subscribed entities. 102 | 103 | After the subscribed entities are edited from the customer's point of view in sandbox company, you should see the post from Intuit's servers on the terminal. 104 | 105 | [ss1]: # 106 | [ss2]: https://customersurveys.intuit.com/jfe/form/SV_9LWgJBcyy3NAwHc?check=Yes&checkpoint=PythonV3InvoiceSampleApp&pageUrl=github 107 | [ss3]: https://customersurveys.intuit.com/jfe/form/SV_9LWgJBcyy3NAwHc?check=No&checkpoint=PythonV3InvoiceSampleApp&pageUrl=github 108 | -------------------------------------------------------------------------------- /SampleAppOAuth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__init__.py -------------------------------------------------------------------------------- /SampleAppOAuth/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__init__.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/apps.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/apps.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/services.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/services.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /SampleAppOAuth/admin.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/admin.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SampleappoauthConfig(AppConfig): 5 | name = 'SampleAppOAuth' 6 | -------------------------------------------------------------------------------- /SampleAppOAuth/apps.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/apps.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/migrations/__init__.py -------------------------------------------------------------------------------- /SampleAppOAuth/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /SampleAppOAuth/models.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/models.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/services.py: -------------------------------------------------------------------------------- 1 | from rauth import OAuth1Service 2 | from mysite import settings 3 | 4 | class QBAuth(object): 5 | qbo=OAuth1Service( 6 | name="qbo", 7 | consumer_key=settings.consumer_key, 8 | consumer_secret=settings.consumer_sec, 9 | request_token_url=settings.request_token_url, 10 | access_token_url=settings.access_token_url, 11 | authorize_url=settings.authorize_url, 12 | base_url=settings.base_url) 13 | 14 | def getRequestTokens(self): 15 | request_token, request_token_secret = self.qbo.get_request_token(params={'oauth_callback': "http://localhost:8000/oauth/authHandler"}) 16 | self.request_token = request_token 17 | self.request_token_secret = request_token_secret 18 | print(request_token) 19 | authorize_url = self.qbo.get_authorize_url(request_token) 20 | return authorize_url 21 | 22 | def getAccessTokens(self, oauth_verifier): 23 | session_obj = self.qbo.get_auth_session(self.request_token, self.request_token_secret, data={'oauth_verifier': oauth_verifier}) 24 | return session_obj 25 | 26 | # These tokens should be persisted in the database, this is just for this sample that a session is used. 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /SampleAppOAuth/static/C2QB_white_btn_lg_default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/static/C2QB_white_btn_lg_default.png -------------------------------------------------------------------------------- /SampleAppOAuth/static/C2QB_white_btn_lg_hover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/static/C2QB_white_btn_lg_hover.png -------------------------------------------------------------------------------- /SampleAppOAuth/static/IntuitSignIn-lg-white@2x.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/static/IntuitSignIn-lg-white@2x.jpg -------------------------------------------------------------------------------- /SampleAppOAuth/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Python Sample App OAuth 4 | 5 | 12 | 13 | 14 | 15 | 16 | Connect To QuickBooks
17 | 18 | 24 | 25 | 26 | 37 | 38 | -------------------------------------------------------------------------------- /SampleAppOAuth/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /SampleAppOAuth/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | url(r'^/?$', views.index, name='index'), 7 | url(r'^(?i)/connectToQuickbooks/?$', views.connectToQuickbooks, name='connectToQuickbooks'), 8 | url(r'^(?i)/authHandler/?$', views.authHandler, name='authHandler'), 9 | 10 | ] -------------------------------------------------------------------------------- /SampleAppOAuth/urls.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleAppOAuth/urls.pyc -------------------------------------------------------------------------------- /SampleAppOAuth/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse, HttpResponseRedirect 2 | from .services import QBAuth 3 | from django.shortcuts import redirect, render 4 | 5 | qb_auth = QBAuth() 6 | 7 | def index(request): 8 | return render(request, 'index.html') 9 | 10 | def connectToQuickbooks(request): 11 | authorize_url = qb_auth.getRequestTokens() 12 | return redirect(authorize_url) 13 | 14 | def authHandler(request): 15 | if request is None: 16 | return HttpResponse("Authorization denied.") 17 | request.session['realm_id'] = request.GET.get('realmId',None) 18 | oauth_verifier = request.GET.get('oauth_verifier',None) 19 | session_object = qb_auth.getAccessTokens(oauth_verifier) 20 | request.session['access_token'] = session_object.access_token 21 | request.session['access_token_secret'] = session_object.access_token_secret 22 | return redirect('index') 23 | 24 | 25 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/LineDetailHelper.py: -------------------------------------------------------------------------------- 1 | from SampleInvoiceCRUD.models import LineItem, SalesLineItem, DescriptionLineItem, DiscountLineItem, SubtotalLineItem, TaxLineItem, Ref 2 | 3 | def createSalesLineItem(txn, Amount, Id=None, Description=None, LineNum=None, ItemRef=None, ClassRef=None, UnitPrice=None, Qty=None, ItemAccountRef=None, ServiceDate=None, TaxCode=None): 4 | detailType = "SalesItemLineDetail" 5 | line = LineItem(detailType, Amount, Id=Id, LineNum=LineNum, Description=Description) 6 | 7 | salesItem = SalesLineItem() 8 | salesItem.ItemRef = createRefItem(salesItem.ItemRef, ItemRef) 9 | salesItem.ClassRef = createRefItem(salesItem.ClassRef, ClassRef) 10 | salesItem.ItemAccountRef = createRefItem(salesItem.ItemAccountRef, ItemAccountRef) 11 | salesItem.TaxCodeRef = createRefItem(salesItem.TaxCodeRef, TaxCode) 12 | salesItem.UnitPrice = UnitPrice 13 | salesItem.Qty = Qty 14 | salesItem.ServiceDate = ServiceDate 15 | 16 | line.SalesItemLineDetail = salesItem 17 | txn.Line.append(line) 18 | 19 | def createDescriptionLineItem(txn, Amount, Id=None, Description=None, LineNum=None, TaxCodeRef=None, ServiceDate=None): 20 | detailType = "DescriptionOnly" 21 | line = LineItem(detailType, Amount, Id=Id, LineNum=LineNum, Description=Description) 22 | 23 | descrItem = DescriptionLineItem() 24 | descrItem.ServiceDate = ServiceDate 25 | # descrItem.TaxCodeRef = Ref() 26 | descrItem.TaxCodeRef = createRefItem(descrItem.TaxCodeRef, TaxCodeRef) 27 | 28 | line.DescriptionLineDetail = descrItem 29 | txn.Line.append(line) 30 | 31 | def createDiscountLineItem(txn, Amount, Id=None, Description=None, LineNum=None, TaxCodeRef=None, ClassRef=None, AccountRef=None, DiscountPercent=None): 32 | detailType = "DiscountLineDetail" 33 | line = LineItem(detailType, Amount, Id=Id, LineNum=LineNum, Description=Description) 34 | 35 | dicountItem = DiscountLineItem() 36 | if DiscountPercent is not None: 37 | dicountItem.PercentBased = True 38 | dicountItem.DiscountPercent = ServiceDate 39 | dicountItem.DiscountAccountRef = createRefItem(dicountItem.DiscountAccountRef, AccountRef) 40 | dicountItem.ClassRef = createRefItem(dicountItem.ClassRef, ClassRef) 41 | dicountItem.TaxCodeRef = createRefItem(dicountItem.TaxCodeRef, TaxCodeRef) 42 | line.DiscountLineDetail = dicountItem 43 | txn.Line.append(line) 44 | 45 | def createSubtotalLineItem(txn, Amount, Id=None, Description=None, LineNum=None, ItemRef=None): 46 | detailType = "SubtotalLineDetail" 47 | line = LineItem(detailType, Amount, Id=Id, LineNum=LineNum, Description=Description) 48 | subtotalItem = SubtotalLineItem() 49 | subtotalItem.ItemRef = createRefItem(subtotalItem.ItemRef, AccountRef) 50 | line.SubtotalLineDetail = subtotalItem 51 | txn.Line.append(line) 52 | 53 | #Helper function 54 | def createRefItem(refItem, refField): 55 | if refField is not None: 56 | try: 57 | refItem=Ref(value=refField['value']) 58 | except: 59 | print('Please enter '+refItem+' as a dictionary') 60 | try: 61 | refItem.name = refField['name'] 62 | except: 63 | refItem.name = None 64 | else: 65 | return refItem 66 | return refItem 67 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/__pycache__/LineDetailHelper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/InvoiceUtils/__pycache__/LineDetailHelper.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/__pycache__/context.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/InvoiceUtils/__pycache__/context.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/__pycache__/requestsQBO.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/InvoiceUtils/__pycache__/requestsQBO.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/__pycache__/services.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/InvoiceUtils/__pycache__/services.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/InvoiceUtils/services.py: -------------------------------------------------------------------------------- 1 | import json 2 | import jsonpickle 3 | from mysite import settings 4 | from mysite.utils import httpRequests 5 | 6 | def toJson(obj): 7 | json_obj = jsonpickle.encode(obj, unpicklable=False) 8 | return json_obj 9 | 10 | def makeRequest(url, method, reqContext, invoice_obj=None): 11 | if reqContext.accessToken is None: 12 | print('OAuth1 access token not found, please run the ') 13 | if invoice_obj is not None: 14 | json_str = toJson(invoice_obj) 15 | json_obj = json.loads(json_str) 16 | res = httpRequests.requestQBO(method, url, reqContext, payload=json_obj) 17 | else: 18 | res = httpRequests.requestQBO(method, url, reqContext) 19 | return res 20 | 21 | def getExistingRef(entity, reqContext): 22 | entityName = entity.title() 23 | if settings.oauth_flag == 1: 24 | realm_id = reqContext.realmId 25 | else: 26 | realm_id = settings.realm_id 27 | url = settings.base_url+realm_id+'/query?query='+'select * from '+entity 28 | res = makeRequest(url, 'GET', reqContext) 29 | response = res.json() 30 | result = response['QueryResponse'] 31 | i=0 32 | if len(result) < 1: 33 | print("Empty query response for "+entity+".") 34 | return None 35 | else: 36 | if entity == 'item': 37 | for item in result[entityName]: 38 | try: 39 | if item["Type"] in ["Category", "Inventory"]: 40 | continue 41 | except (KeyError,NameError): 42 | return int(item["Id"]) 43 | return int(result[entityName][i]["Id"]) -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__init__.py -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/invoice_crud.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/invoice_crud.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/lineDetail.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/lineDetail.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class SampleinvoicecrudConfig(AppConfig): 7 | name = 'SampleInvoiceCRUD' 8 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/invoice_crud.py: -------------------------------------------------------------------------------- 1 | from .models import Invoice, Ref, Address 2 | from mysite import settings 3 | from mysite.utils import httpRequests, context 4 | from .InvoiceUtils import services, LineDetailHelper 5 | import json 6 | import jsonpickle 7 | from urllib.parse import quote 8 | 9 | def createInvoice(context): 10 | invoice = Invoice() 11 | invoice.CustomerRef = Ref(value=services.getExistingRef('customer', context)) 12 | invoice.TxnDate = "2017-12-12" 13 | invoice.PrivateNote = "This is a private note." 14 | invoice.LinkedTxn = None 15 | invoice.CustomerMemo = {"value":"This is a customer memo."} 16 | invoice.BillAddr = Address("111 Orange St", "Mountain view", "USA", "11231") 17 | invoice.ClassRef = Ref(value=services.getExistingRef('class', context)) 18 | invoice.Deposit = None 19 | item = {'value': services.getExistingRef('item', context)} 20 | LineDetailHelper.createSalesLineItem(invoice, 100, ItemRef=item) 21 | 22 | # get realm for OAuth1 from view session and OAuth2 from settings 23 | if settings.oauth_flag == 1: 24 | realm_id = context.realmId 25 | else: 26 | realm_id = settings.realm_id 27 | url=settings.base_url+realm_id+"/invoice?minorversion=4" 28 | request = services.makeRequest(url, 'POST', context, invoice_obj=invoice) 29 | return request.json() 30 | 31 | def queryInvoice(query, context): 32 | # get realm for OAuth1 from view session and OAuth2 from settings 33 | if settings.oauth_flag == 1: 34 | realm_id = context.realmId 35 | else: 36 | realm_id = settings.realm_id 37 | url = settings.base_url+realm_id+"/query?query="+quote(query)+"&minorversion=9" 38 | request = services.makeRequest(url, 'GET', context) 39 | queryResponse = request.json() 40 | if len(queryResponse["QueryResponse"].keys()) > 0: 41 | invoiceList = [] 42 | for each in queryResponse["QueryResponse"]['Invoice']: 43 | deserialize_obj_string = "py/object" 44 | each["py/object"] = "SampleInvoiceCRUD.models.Invoice" 45 | lines = each["Line"] 46 | for line in lines: 47 | line[deserialize_obj_string] = "SampleInvoiceCRUD.models.LineItem" 48 | invoice_json_str = json.dumps(each) 49 | invoice_obj = jsonpickle.decode(invoice_json_str) 50 | invoiceList.append(invoice_obj) 51 | return invoiceList 52 | else: 53 | message = "Your query returned empty response." 54 | return message 55 | 56 | # Similar to create, need to provide Id, SyncToken and other updated fields 57 | def updateInvoice(invoiceId, context): 58 | """ 59 | Only sparse update is shown here. For full update, please follow the create method and include required fields: SyncToken, Id and sparse: False 60 | 61 | Sparse update will update only the field provided in the request and will not change any fields not provided in the request whereas full update will change all the field and if a full update is done on an invoice and some fields are not provided, then these field will reset to default. 62 | """ 63 | # get realm for OAuth1 from view session and OAuth2 from settings 64 | if settings.oauth_flag == 1: 65 | realm_id = context.realmId 66 | else: 67 | realm_id = settings.realm_id 68 | url = settings.base_url+realm_id+'/invoice?minorversion=9' 69 | 70 | invoiceToUpdate = readInvoice(invoiceId, context) 71 | invoiceToUpdate.PrivateNote = "Updated invoice with new private note." 72 | invoiceToUpdate.sparse = True 73 | if isinstance(invoiceToUpdate, str): 74 | print('No invoice found with Id '+str(invoiceId)) 75 | else: 76 | try: 77 | request = services.makeRequest(url, 'POST', context, invoice_obj=invoiceToUpdate) 78 | return request.json() 79 | except IndexError: 80 | return 'No invoice found with Id '+str(invoiceId) 81 | 82 | def deleteInvoice(invoiceId, context): 83 | # get realm for OAuth1 from view session and OAuth2 from settings 84 | if settings.oauth_flag == 1: 85 | realm_id = context.realmId 86 | else: 87 | realm_id = settings.realm_id 88 | url = settings.base_url+realm_id+'/invoice?operation=delete&minorversion=9' 89 | invoice = readInvoice(invoiceId, context) 90 | if isinstance(invoice, str): 91 | print('No invoice found with Id '+str(invoiceId)) 92 | else: 93 | try: 94 | syncToken = invoice.SyncToken 95 | payload = { 96 | "Id": str(invoiceId), 97 | "SyncToken": str(syncToken) 98 | } 99 | res = httpRequests.requestQBO('POST', url, context, payload=payload) 100 | response = res.json() 101 | return response 102 | except IndexError: 103 | return 'No invoice found with Id '+str(invoiceId) 104 | 105 | def readInvoice(invoiceId, context): 106 | # get realm for OAuth1 from view session and OAuth2 from settings 107 | if settings.oauth_flag == 1: 108 | realm_id = context.realmId 109 | else: 110 | realm_id = settings.realm_id 111 | url=settings.base_url+realm_id+"/invoice/"+str(invoiceId)+"?minorversion=9" 112 | request = services.makeRequest(url, 'GET', context) 113 | invoice_json = request.json() 114 | if request.status_code == 200: 115 | # Add key value for jsonpickle to work 116 | deserialize_obj_string = "py/object" 117 | invoice_json["Invoice"][deserialize_obj_string] = "SampleInvoiceCRUD.models.Invoice" 118 | lines = invoice_json["Invoice"]["Line"] 119 | for line in lines: 120 | line[deserialize_obj_string] = "SampleInvoiceCRUD.models.LineItem" 121 | 122 | invoice = invoice_json["Invoice"] 123 | invoice_json_str = json.dumps(invoice) 124 | invoice_obj = jsonpickle.decode(invoice_json_str) 125 | if(type(invoice_obj)) == Invoice: 126 | return invoice_obj 127 | else: 128 | return "Could not deserialize invoice. Please use this object as a dictionary." 129 | else: 130 | return 'No invoice found with Id '+str(invoiceId) 131 | 132 | """ 133 | Please see delete operation to see how to implement void, only the URL will change, payload remains the same. 134 | url = settings.base_url+settings.realm_id+'/invoice?operation=void&minorversion=4' 135 | """ 136 | def voidInvoice(): 137 | pass 138 | 139 | 140 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/migrations/__init__.py -------------------------------------------------------------------------------- /SampleInvoiceCRUD/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUD/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUD/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | from django.db import models 3 | import json 4 | 5 | # Class that ignores class attributes with value as None 6 | class _State: 7 | def __getstate__(self): 8 | state = self.__dict__.copy() 9 | state = {key: value for key, value in state.items() if value is not None} 10 | return state 11 | 12 | def __setstate__(self, state): 13 | self.__dict__.update(state) 14 | 15 | class Invoice(_State): 16 | def __init__(self, CustomerName=None, CustomerId=None, TxnDate=None): 17 | self.Line = [] 18 | self.CustomerRef = None 19 | 20 | self.Id = None 21 | self.CustomField = None 22 | self.DocNumber = None 23 | self.TxnDate = None 24 | self.DepartmentRef = None 25 | self.PrivateNote = None 26 | self.LinkedTxn = None 27 | self.TxnTaxDetail = None 28 | 29 | self.CustomerMemo = None 30 | self.BillAddr = None 31 | self.ShipAddr = None 32 | self.ClassRef = None 33 | self.SalesTermRef = None 34 | self.DueDate = None 35 | self.GlobalTaxCalculation = "TaxExcluded" 36 | self.ShipMethodRef = None 37 | self.ShipDate = None 38 | self.TrackingNum = None 39 | self.TotalAmt = None 40 | self.CurrencyRef = None 41 | self.ExchangeRate = 1 42 | 43 | self.ApplyTaxAfterDiscount = False 44 | self.PrintStatus = "NotSet" 45 | self.EmailStatus = "NotSet" 46 | self.BillEmail = None 47 | self.BillEmailCc = None 48 | self.BillEmailBcc = None 49 | self.DeliveryInfo = None 50 | self.Balance = None 51 | self.TxnSource = None 52 | self.Deposit = None 53 | self.MetaData = None 54 | self.HomeTotalAmt = None 55 | self.HomeBalance = None 56 | 57 | # for update 58 | self.sparse = None 59 | self.SyncToken = None 60 | 61 | def printInvoice(self): 62 | print(self.Id+' '+self.DocNumber+' '+self.TxnDate) 63 | 64 | # Helper classes 65 | class LineItem(_State): 66 | lineTypeDict = { 67 | "DescriptionOnly": "DescriptionLineDetail" 68 | } 69 | def __init__(self, LineType, Amount, Id=None, LineNum=None, Description=None): 70 | self.Id = Id 71 | self.LineNum = LineNum 72 | self.Description = Description 73 | self.DetailType = LineType 74 | self.Amount = Amount 75 | if LineType == "SalesItemLineDetail": 76 | setattr(self, LineType, None) 77 | elif LineType == "DescriptionOnly": 78 | setattr(self, LineTypeDict[LineType], None) 79 | elif LineType == "DiscountLineDetail": 80 | setattr(self, LineType, None) 81 | elif LineType == "SubtotalLineDetail": 82 | setattr(self, LineType, None) 83 | 84 | class SalesLineItem(_State): 85 | def __init__(self): 86 | self.ItemRef = None 87 | self.ClassRef = None 88 | self.UnitPrice = None 89 | self.MarkupInfo = None 90 | self.Qty = None 91 | self.ItemAccountRef = None 92 | self.TaxCodeRef = None 93 | self.ServiceDate = None 94 | self.TaxInclusiveAmt = None 95 | 96 | class DescriptionLineItem(_State): 97 | def __init__(self): 98 | self.ServiceDate = None 99 | self.TaxCodeRef = None 100 | 101 | class DiscountLineItem(_State): 102 | def __init__(self): 103 | self.PercentBased = None 104 | self.DiscountPercent = None 105 | self.DiscountAccountRef = None 106 | self.ClassRef = None 107 | self.TaxCodeRef = None 108 | 109 | class SubtotalLineItem(_State): 110 | def __init__(self): 111 | self.ItemRef = None 112 | 113 | class TaxLineItem(_State): 114 | def __init__(self): 115 | self.PercentBased = None 116 | self.NetAmountTaxable = None 117 | self.TaxInclusiveAmount = None 118 | self.OverrideDeltaAmount = None 119 | self.TaxPercent = None 120 | self.TaxRateRef = None 121 | 122 | class Ref(_State): 123 | def __init__(self, value=None, name=None): 124 | self.value = value 125 | self.name = name 126 | 127 | class Address(_State): 128 | def __init__(self, Line1, City, Country, PostalCode, Line2=None, Line3=None, Line4=None, Line5=None, CountrySubDivision=None, Lat=None, Long=None): 129 | self.Line1 = Line1 130 | self.Line2 = Line2 131 | self.Line3 = Line3 132 | self.Line4 = Line4 133 | self.Line5 = Line5 134 | self.City = City 135 | self.Country = Country 136 | self.CountrySubDivisionCode = CountrySubDivision 137 | self.PostalCode = PostalCode 138 | self.Lat = Lat 139 | self.Long = Long 140 | 141 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/templates/invoice.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Invoice Python Sample 5 | 6 | 7 | 16 | 17 | 18 | 19 |

Invoice Python Sample

20 | 21 |

22 | 23 |

24 | 25 |

26 | 27 |

28 | 29 |

30 |
31 | 32 | 33 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /SampleInvoiceCRUD/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from . import views 3 | 4 | urlpatterns = [ 5 | url(r'^/?$', views.index, name='indexInvoiceObject'), 6 | url(r'^(?i)/create/?$', views.create, name='create'), 7 | url(r'^(?i)/update/?$', views.update, name='update'), 8 | url(r'^(?i)/read/?$', views.read, name='read'), 9 | url(r'^(?i)/delete/?$', views.delete, name='delete'), 10 | url(r'^(?i)/query/?$', views.query, name='query'), 11 | 12 | ] -------------------------------------------------------------------------------- /SampleInvoiceCRUD/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.http import HttpResponse, HttpResponseForbidden 3 | from .models import Invoice 4 | from .invoice_crud import createInvoice, readInvoice, queryInvoice, deleteInvoice, updateInvoice 5 | from mysite.utils import context 6 | 7 | def index(request): 8 | return render(request, 'invoice.html') 9 | 10 | def create(request): 11 | import pdb; pdb.set_trace() 12 | reqContext = contextHelper(request) 13 | response = createInvoice(reqContext) 14 | return HttpResponse(str(response['Invoice'])) 15 | 16 | def update(request): 17 | # query to get an existing invoice id 18 | reqContext = contextHelper(request) 19 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 20 | if not isinstance(query, str) and len(query) > 0: 21 | invoice = query[0] 22 | response = updateInvoice(invoice.Id, reqContext) 23 | message = str(response['Invoice']) 24 | elif isinstance(query, str): 25 | message = query 26 | else: 27 | message = 'Unable to find existing invoice to update. Please add an invoice and try again.' 28 | return HttpResponse(message) 29 | 30 | def read(request): 31 | # query to get an existing invoice id 32 | reqContext = contextHelper(request) 33 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 34 | if not isinstance(query, str) and len(query) > 0: 35 | invoice = query[0] 36 | response = readInvoice(invoice.Id, reqContext) 37 | message = str(response.__dict__) 38 | elif isinstance(query, str): 39 | message = query 40 | else: 41 | message = 'Unable to find existing invoice to read. Please add an invoice and try again.' 42 | return HttpResponse(message) 43 | 44 | def delete(request): 45 | # query to get an existing invoice id 46 | reqContext = contextHelper(request) 47 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 48 | if not isinstance(query, str) and len(query) > 0: 49 | invoice = query[0] 50 | response = deleteInvoice(invoice.Id, reqContext) 51 | message = str(response['Invoice']) 52 | elif isinstance(query, str): 53 | message = query 54 | else: 55 | message = 'Unable to find existing invoice to delete. Please add an invoice and try again.' 56 | return HttpResponse(message) 57 | 58 | def query(request): 59 | reqContext = contextHelper(request) 60 | response = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 61 | message = '' 62 | for res in response: 63 | message += str(res.__dict__) 64 | return HttpResponse(message) 65 | 66 | 67 | def contextHelper(request): 68 | reqContext = context.Context(access_token=request.session.get('access_token'),access_token_secret=request.session.get('access_token_secret'), realm_id=request.session.get('realm_id')) 69 | return reqContext 70 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/InvoiceDictUtils/Services.py: -------------------------------------------------------------------------------- 1 | from mysite import settings 2 | from mysite.utils import httpRequests, context 3 | import json 4 | 5 | def makeRequest(url, method, reqContext, invoice_obj=None): 6 | # reqContext = context.Context() 7 | if invoice_obj is not None: 8 | json_str = json.dumps(invoice_obj) 9 | json_obj = json.loads(json_str) 10 | res = httpRequests.requestQBO(method, url, reqContext, payload=json_obj) 11 | else: 12 | res = httpRequests.requestQBO(method, url, reqContext) 13 | return res 14 | 15 | def getExistingRef(entity, context): 16 | entityName = entity.title() 17 | if settings.oauth_flag == 1: 18 | realm_id = context.realmId 19 | else: 20 | realm_id = settings.realm_id 21 | url = settings.base_url+realm_id+'/query?query='+'select * from '+entity 22 | res = makeRequest(url, 'GET', context) 23 | response = res.json() 24 | result = response['QueryResponse'] 25 | i=0 26 | if len(result) < 1: 27 | print("Empty query response.") 28 | return None 29 | else: 30 | if entity == 'item': 31 | for item in result[entityName]: 32 | try: 33 | if item["Type"] in ["Category", "Inventory"]: 34 | continue 35 | except (KeyError,NameError): 36 | return int(item["Id"]) 37 | return int(result[entityName][i]["Id"]) 38 | 39 | 40 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/Services.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/Services.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/context.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/context.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/requestsQBO.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/InvoiceDictUtils/__pycache__/requestsQBO.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__init__.py -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/invoice_crud.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/invoice_crud.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SampleinvoicecrcrudusingdictConfig(AppConfig): 5 | name = 'SampleInvoiceCrCRUDUsingDict' 6 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/invoice_crud.py: -------------------------------------------------------------------------------- 1 | from mysite import settings 2 | from .InvoiceDictUtils import Services 3 | from mysite.utils import httpRequests, context 4 | import json 5 | import jsonpickle 6 | from urllib.parse import quote 7 | 8 | def createInvoice(context): 9 | # Passing a request dictionary for invoice request instead of building it like shown here will work. 10 | invoice = {} 11 | customerId = Services.getExistingRef('customer', context) 12 | invoice['CustomerRef'] = { 13 | 'value': customerId 14 | } 15 | invoice['TxnDate'] = "2017-12-12" 16 | invoice['PrivateNote'] = "This is a private note." 17 | invoice['CustomerMemo'] = { 18 | "value": "This is a customer memo." 19 | } 20 | invoice['BillAddr'] = { 21 | "Line1": "111 Orange St", 22 | "City": "Mountain view", 23 | "Country": "USA", 24 | "PostalCode":"11231" 25 | } 26 | classRefId = Services.getExistingRef('class', context) 27 | invoice['ClassRef'] = {'value': classRefId} 28 | item = Services.getExistingRef('item', context) 29 | line = [ 30 | { 31 | 'DetailType': 'SalesItemLineDetail', 32 | 'Amount': 100, 33 | 'SalesItemLineDetail': { 34 | 'ItemRef': { 35 | 'value': item 36 | } 37 | } 38 | 39 | }, 40 | { 41 | 'DetailType': 'SalesItemLineDetail', 42 | 'Amount': 50, 43 | 'SalesItemLineDetail': { 44 | 'ItemRef': { 45 | 'value': item 46 | } 47 | } 48 | 49 | }, 50 | ] 51 | invoice['Line'] = line 52 | 53 | # get realm for OAuth1 from view session and OAuth2 from settings 54 | if settings.oauth_flag == 1: 55 | realm_id = context.realmId 56 | else: 57 | realm_id = settings.realm_id 58 | url=settings.base_url+realm_id+"/invoice?minorversion=4" 59 | request = Services.makeRequest(url, 'POST', context, invoice_obj=invoice) 60 | return request.json() 61 | 62 | def queryInvoice(query, context): 63 | if settings.oauth_flag == 1: 64 | realm_id = context.realmId 65 | else: 66 | realm_id = settings.realm_id 67 | url = settings.base_url+realm_id+"/query?query="+quote(query)+"&minorversion=4" 68 | request = Services.makeRequest(url, 'GET', context) 69 | return request.json()['QueryResponse']['Invoice'] 70 | 71 | # Similar to create, need to provide Id, SyncToken and other updated fields 72 | def updateInvoice(invoiceId, context): 73 | """ 74 | Only sparse update is shown here. For full update, please follow the create method and include required fields: SyncToken, Id and sparse: False 75 | 76 | Sparse update will update only the field provided in the request and will not change any fields not provided in the request whereas full update will change all the field and if a full update is done on an invoice and some fields are not provided, then these field will reset to default. 77 | """ 78 | # get realm for OAuth1 from view session and OAuth2 from settings 79 | if settings.oauth_flag == 1: 80 | realm_id = context.realmId 81 | else: 82 | realm_id = settings.realm_id 83 | url = settings.base_url+realm_id+'/invoice?minorversion=4' 84 | invoiceToUpdate = readInvoice(invoiceId, context)['Invoice'] 85 | invoiceToUpdate['sparse'] = True 86 | invoiceToUpdate['PrivateNote'] = "Updated invoice with new private note." 87 | if isinstance(invoiceToUpdate, str): 88 | print('No invoice found with Id '+str(invoiceId)) 89 | else: 90 | try: 91 | request = Services.makeRequest(url, 'POST', context, invoice_obj=invoiceToUpdate) 92 | return request.json() 93 | except IndexError: 94 | return 'No invoice found with Id '+str(invoiceId) 95 | 96 | def deleteInvoice(invoiceId, context): 97 | # get realm for OAuth1 from view session and OAuth2 from settings 98 | if settings.oauth_flag == 1: 99 | realm_id = context.realmId 100 | else: 101 | realm_id = settings.realm_id 102 | url = settings.base_url+realm_id+'/invoice?operation=delete&minorversion=4' 103 | invoice = readInvoice(invoiceId, context) 104 | if isinstance(invoice, str): 105 | print('No invoice found with Id '+str(invoiceId)) 106 | else: 107 | try: 108 | syncToken = invoice['Invoice']['SyncToken'] 109 | payload = { 110 | "Id": str(invoiceId), 111 | "SyncToken": str(syncToken) 112 | } 113 | res = httpRequests.requestQBO('POST', url, context, payload=payload) 114 | response = res.json() 115 | return response 116 | except IndexError: 117 | return 'No invoice found with Id '+str(invoiceId) 118 | 119 | def readInvoice(invoiceId, context): 120 | # get realm for OAuth1 from view session and OAuth2 from settings 121 | if settings.oauth_flag == 1: 122 | realm_id = context.realmId 123 | else: 124 | realm_id = settings.realm_id 125 | url=settings.base_url+realm_id+"/invoice/"+str(invoiceId)+"?minorversion=9" 126 | request = Services.makeRequest(url, 'GET', context) 127 | if request.status_code == 200: 128 | return request.json() 129 | else: 130 | return 'No invoice found with Id '+str(invoiceId) 131 | 132 | """ 133 | Please see delete operation to see how to implement void, only the URL will change, payload remains the same. 134 | url = settings.base_url+settings.realm_id+'/invoice?operation=void&minorversion=4' 135 | """ 136 | def voidInvoice(): 137 | pass 138 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/migrations/__init__.py -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleInvoiceCRUDUsingDict/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/templates/invoiceUsingDict.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Invoice Python Sample 5 | 6 | 7 | 8 | 17 | 18 | 19 | 20 |

Invoice Python Sample

21 | 22 |

23 | 24 |

25 | 26 |

27 | 28 |

29 | 30 |

31 |
32 | 33 | 34 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from . import views 3 | 4 | urlpatterns = [ 5 | url(r'^/?$', views.index, name='indexInvoiceDict'), 6 | url(r'^(?i)/create/?$', views.create, name='create'), 7 | url(r'^(?i)/update/?$', views.update, name='update'), 8 | url(r'^(?i)/read/?$', views.read, name='read'), 9 | url(r'^(?i)/delete/?$', views.delete, name='delete'), 10 | url(r'^(?i)/query/?$', views.query, name='query'), 11 | 12 | ] -------------------------------------------------------------------------------- /SampleInvoiceCRUDUsingDict/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from mysite.utils import context 3 | # Create your views here. 4 | 5 | from django.shortcuts import render 6 | from django.http import HttpResponse, HttpResponseForbidden 7 | from .invoice_crud import createInvoice, readInvoice, queryInvoice, deleteInvoice, updateInvoice 8 | 9 | def index(request): 10 | return render(request, 'invoiceUsingDict.html') 11 | 12 | def create(request): 13 | reqContext = contextHelper(request) 14 | response = createInvoice(reqContext) 15 | return HttpResponse(str(response['Invoice'])) 16 | 17 | def update(request): 18 | # query to get an existing invoice id 19 | reqContext = contextHelper(request) 20 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 21 | if not isinstance(query, str) and len(query) > 0: 22 | invoice = query[0] 23 | response = updateInvoice(invoice['Id'], reqContext) 24 | message = str(response['Invoice']) 25 | elif isinstance(query, str): 26 | message = query 27 | else: 28 | message = 'Unable to find existing invoice to update. Please add an invoice and try again.' 29 | return HttpResponse(message) 30 | 31 | def read(request): 32 | # query to get an existing invoice id 33 | reqContext = contextHelper(request) 34 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 35 | if not isinstance(query, str) and len(query) > 0: 36 | invoice = query[0] 37 | response = readInvoice(invoice['Id'], reqContext) 38 | message = str(response) 39 | elif isinstance(query, str): 40 | message = query 41 | else: 42 | message = 'Unable to find existing invoice to read. Please add an invoice and try again.' 43 | return HttpResponse(message) 44 | 45 | def delete(request): 46 | # query to get an existing invoice id 47 | reqContext = contextHelper(request) 48 | query = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 49 | if not isinstance(query, str) and len(query) > 0: 50 | invoice = query[0] 51 | response = deleteInvoice(invoice['Id'], reqContext) 52 | message = str(response['Invoice']) 53 | elif isinstance(query, str): 54 | message = query 55 | else: 56 | message = 'Unable to find existing invoice to delete. Please add an invoice and try again.' 57 | return HttpResponse(message) 58 | 59 | def query(request): 60 | reqContext = contextHelper(request) 61 | response = queryInvoice('select * from invoice startposition 0 maxresults 5', reqContext) 62 | return HttpResponse(response) 63 | 64 | def contextHelper(request): 65 | reqContext = context.Context(access_token=request.session.get('access_token'),access_token_secret=request.session.get('access_token_secret'), realm_id=request.session.get('realm_id')) 66 | return reqContext 67 | 68 | -------------------------------------------------------------------------------- /SampleWebhooks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__init__.py -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/services.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/services.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /SampleWebhooks/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class SamplewebhooksConfig(AppConfig): 7 | name = 'SampleWebhooks' 8 | -------------------------------------------------------------------------------- /SampleWebhooks/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/migrations/__init__.py -------------------------------------------------------------------------------- /SampleWebhooks/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/SampleWebhooks/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /SampleWebhooks/models.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /SampleWebhooks/services.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | from Crypto.Signature import PKCS1_v1_5 3 | from Crypto.Hash import SHA256 4 | from base64 import b64encode 5 | import hashlib, hmac, base64 6 | from mysite import settings 7 | 8 | 9 | def isValidPayload(signature, payload): 10 | 11 | key = settings.webhooks_verifier 12 | key_to_verify = key.encode('ascii') 13 | hashed = hmac.new(key_to_verify, payload, hashlib.sha256).digest() 14 | hashed_base64 = base64.b64encode(hashed).decode() 15 | 16 | if signature == hashed_base64: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /SampleWebhooks/templates/webhooks.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Webhooks Python Sample 5 | 6 | 7 |

Webhooks Python Sample

8 | 9 | -------------------------------------------------------------------------------- /SampleWebhooks/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /SampleWebhooks/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | url(r'^/?$', views.index, name='indexWebhooks'), 7 | ] -------------------------------------------------------------------------------- /SampleWebhooks/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from django.template import Context, Template 3 | from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest 4 | from .services import isValidPayload 5 | from django.views.decorators.csrf import csrf_exempt 6 | from django.views.decorators.http import require_POST 7 | import json 8 | 9 | # Create your views here. 10 | #from .models import WebhooksContext 11 | @csrf_exempt 12 | @require_POST 13 | def index(request): 14 | payload = request.body 15 | signature = request.META.get('HTTP_INTUIT_SIGNATURE') 16 | 17 | if signature is None: 18 | return HttpResponseForbidden('Permission denied.') 19 | 20 | if isValidPayload(signature, payload): 21 | print(payload.decode()) 22 | request.session['WebhooksPayload'] = (payload.decode(), None) 23 | return HttpResponse(payload.decode()) 24 | 25 | else: 26 | return HttpResponseBadRequest('Payload not validated.') 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /__pycache__/invoice.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/__pycache__/invoice.cpython-36.pyc -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/db.sqlite3 -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__init__.py -------------------------------------------------------------------------------- /mysite/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__init__.pyc -------------------------------------------------------------------------------- /mysite/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.10. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.10/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'sdp_zb!t3nwx9j6s2vre_oihj%md#d4*kbfoejwg+%e+pk33%4' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'SampleWebhooks', 35 | 'SampleInvoiceCRUD', 36 | 'SampleInvoiceCRUDUsingDict', 37 | 'SampleAppOAuth', 38 | 'django.contrib.admin', 39 | 'django.contrib.auth', 40 | 'django.contrib.contenttypes', 41 | 'django.contrib.sessions', 42 | 'django.contrib.messages', 43 | 'django.contrib.staticfiles', 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | ] 55 | 56 | ROOT_URLCONF = 'mysite.urls' 57 | 58 | TEMPLATES = [ 59 | { 60 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 61 | 'DIRS': [], 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'mysite.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/1.10/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'en-us' 111 | 112 | TIME_ZONE = 'UTC' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | STATIC_URL = '/static/' 122 | 123 | # OAuth1 tokens 124 | consumer_key = "" 125 | consumer_sec = "" 126 | 127 | #OAuth1 config 128 | request_token_url = "https://oauth.intuit.com/oauth/v1/get_request_token" 129 | access_token_url = "https://oauth.intuit.com/oauth/v1/get_access_token" 130 | authorize_url = "https://appcenter.intuit.com/Connect/Begin" 131 | base_url = "https://sandbox-quickbooks.api.intuit.com/v3/company/" 132 | 133 | #change oauth_flag to 1 for OAuth1 apps and fill in valid OAuth1 tokens above. Get oauth2 access token from OAuth2 playground: https://developer.intuit.com/v2/ui#/playground 134 | oauth_flag = 2 135 | access_token_oauth2 = "" 136 | 137 | # OAuth2 app realm ID 138 | realm_id = "" 139 | 140 | # Webhooks config 141 | webhooks_verifier = "" 142 | # Subscribed webhooks entities can be changed here 143 | webhooks_subscribed_entities = "Customer,Term" 144 | -------------------------------------------------------------------------------- /mysite/settings.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/settings.pyc -------------------------------------------------------------------------------- /mysite/urls.py: -------------------------------------------------------------------------------- 1 | """mysite URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import include, url 17 | 18 | urlpatterns = [ 19 | url(r'^(?i)oauth', include('SampleAppOAuth.urls')), 20 | url(r'^(?i)webhooks', include('SampleWebhooks.urls')), 21 | url(r'^(?i)invoice', include('SampleInvoiceCRUD.urls')), 22 | url(r'^(?i)invoiceUsingDict', include('SampleInvoiceCRUDUsingDict.urls')), 23 | 24 | ] 25 | -------------------------------------------------------------------------------- /mysite/urls.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/urls.pyc -------------------------------------------------------------------------------- /mysite/utils/__pycache__/context.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/utils/__pycache__/context.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/utils/__pycache__/httpRequests.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/mysite/utils/__pycache__/httpRequests.cpython-36.pyc -------------------------------------------------------------------------------- /mysite/utils/context.py: -------------------------------------------------------------------------------- 1 | # Get from settings 2 | # The context class sets the realm id with the consumer tokens every time user authorizes an app for their QB company 3 | from mysite import settings 4 | 5 | # In production app, context is set after getting access tokens and realm ID along with app's consumer token and secret. Here, Context is just for demo purposes, it's getting hard coded tokens from settings.py 6 | class Context: 7 | # For OAuth1 only 8 | def __init__(self, access_token=None, access_token_secret=None, realm_id=None): 9 | self.consumerToken = settings.consumer_key 10 | self.consumerSecret = settings.consumer_sec 11 | self.accessToken = access_token 12 | self.accessSecret = access_token_secret 13 | self.realmId = realm_id 14 | 15 | -------------------------------------------------------------------------------- /mysite/utils/httpRequests.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from requests_oauthlib import OAuth1 3 | 4 | # POST for qbo sandbox 5 | from mysite import settings 6 | 7 | def requestQBO(method, url, context, payload=None): 8 | 9 | if settings.oauth_flag == 2: 10 | headers = {'Accept': 'application/json', 'User-Agent': 'PythonSampleApp2.0', 'Authorization': 'Bearer '+settings.access_token_oauth2} 11 | req = requests.request(method,url, headers=headers, json=payload) 12 | else: 13 | headers = {'Accept': 'application/json', 'content-type': 'application/json; charset=utf-8', 'User-Agent': 'PythonSampleApp2.0'} 14 | auth=OAuth1(context.consumerToken, context.consumerSecret, 15 | context.accessToken, context.accessSecret) 16 | req = requests.request(method,url, auth=auth, headers=headers, json=payload) 17 | return req 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests_oauthlib==0.8.0 2 | requests==2.13.0 3 | Django==1.10 4 | rauth==0.7.3 5 | jsonpickle==0.9.5 6 | pycrypto==2.6.1 7 | -------------------------------------------------------------------------------- /views/Callout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/views/Callout.png -------------------------------------------------------------------------------- /views/Ratesample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/views/Ratesample.png -------------------------------------------------------------------------------- /views/Thumbdown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/views/Thumbdown.png -------------------------------------------------------------------------------- /views/Thumbup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IntuitDeveloper/PythonV3InvoiceSampleApp/9dadc55e9b0fe315d243cd75597caf423a027c1f/views/Thumbup.png --------------------------------------------------------------------------------