Пример #1
0
def refresh():
    tokens = []
    filename = "core/apis/quickBooks/.token"
    f = open(filename, 'r')
    for line in f:
        tokens.append(line.rstrip())
    f.close()

    auth_client = AuthClient(
        settings.QB_CLIENT_ID,
        settings.QB_CLIENT_SECRET,
        settings.QB_REDIRECT_URI,
        settings.QB_ENVIRONMENT,
        access_token=tokens[0],
        refresh_token=tokens[1],
    )
    try:
        auth_client.refresh()
    except AuthClientError as e:
        print(e.status_code)
        print(e.intuit_tid)

    print("----------")
    print([
        auth_client.access_token == tokens[0],
        auth_client.refresh_token == tokens[1]
    ])
    print("----------")

    f = open(filename, 'w')
    f.write("{0}\n".format(auth_client.access_token))
    f.write("{0}\n".format(auth_client.refresh_token))
    f.close()
    return
Пример #2
0
    def user_consent(self):
        '''Triggers the User Consent OAuth2.0 flow
        in order to retrieve an Authorization Code
        and a Realm ID.
        '''
        auth_client = AuthClient(self.config.get("client_id"),
                                 self.config.get("client_secret"),
                                 self.config.get("redirect_uri"),
                                 self.config.get("environment"))

        scopes = [Scopes.ACCOUNTING]
        auth_url = auth_client.get_authorization_url(scopes)
        webbrowser.open(auth_url)
        auth_code = input('Enter the Authorization Code: ')
        realm_id = input('Enter the Realm ID: ')
        auth_client.get_bearer_token(auth_code, realm_id=realm_id)
        self.config["realm_id"] = realm_id
        self.config["refresh_token"] = auth_client.refresh_token
        self.config[
            "refresh_token_expires_at"] = self._generate_token_expiration(
                auth_client.x_refresh_token_expires_in)

        LOGGER.info('Generating new config..')
        with open(self.args.config_path, 'r+') as f:
            json.dump(self.config, f, indent=2)
Пример #3
0
def get_access_from_refresh(request):
    refresh_token = request.session.get('refresh_token', None)

    if refresh_token is None:
        return self.refresh()
    else:
        try:
            auth_client = AuthClient(
                settings.CLIENT_ID,
                settings.CLIENT_SECRET,
                settings.REDIRECT_URI,
                settings.ENVIRONMENT,
                access_token=request.session.get('access_token', None),
                refresh_token=refresh_token,
            )
            current_refresh_token = request.session.get('refresh_token')
            print('CURRENT REFRESH TOKEN IS: ', current_refresh_token)
            auth_client.refresh(refresh_token=current_refresh_token)
            print(auth_client)
        except AuthClientError as e:
            print(e.status_code)
            print(e.intuit_tid)

        return HttpResponse(json.dumps({
            'access_token':
            auth_client.access_token,
            'refresh_token':
            auth_client.refresh_token
        }),
                            content_type='application/json')
Пример #4
0
def get_quickbooks_client():
    env = environ.Env()
    auth_client = AuthClient(
        client_id=env("QUICKBOOKS_CLIENT"),
        client_secret=env("QUICKBOOKS_SECRET"),
        environment="production",
        redirect_uri="http://localhost:8000/callback",
    )
    token_path = str(settings.ROOT_DIR / "secrets" /
                     "QUICKBOOKS_REFRESH_TOKEN")
    if os.path.exists(token_path):
        with open(token_path, "r") as refresh_token_file:
            refresh_token = refresh_token_file.read()
    else:
        print("NEED TO GENERATE REFRESH TOKEN!")
        return
    auth_client.refresh(refresh_token=refresh_token)
    with open(token_path, "w") as refresh_token_file:
        refresh_token_file.write(auth_client.refresh_token)
    client = QuickBooks(
        auth_client=auth_client,
        refresh_token=auth_client.refresh_token,
        company_id="9130348538823906",
        minorversion=62,
    )
    return client
def openid(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
    )

    url = auth_client.get_authorization_url([Scopes.OPENID, Scopes.EMAIL])
    request.session['state'] = auth_client.state_token
    return redirect(url)
Пример #6
0
def oauth():
    auth_client = AuthClient(
        client_id,
        client_secret,
        redirect_uri,
        environment,
    )

    url = auth_client.get_authorization_url([Scopes.ACCOUNTING])
    # request.session['state'] = auth_client.state_token
    return redirect(url)
Пример #7
0
def redirect():
    auth_client = AuthClient(
    cfg.qbo['QBO_CLIENT_ID'],
    cfg.qbo['QBO_CLIENT_SECRET'],
    "https://tdasu.pagekite.me/redirect",
    environment="production"
    )
    auth_client.get_bearer_token(request.args.get('code'), realm_id=request.args.get('realmId'))
    pickle.dump(auth_client.refresh_token, open( "refresh.token", "wb" ) )
    pickle.dump(request.args.get('realmId'), open( "realm.id", "wb" ) )
    return "set up"
Пример #8
0
def get_refreshed_tokens(refresh_token,
                         client_id,
                         client_secret,
                         sandbox=False):
    enviroment = 'sandbox' if sandbox else 'production'
    auth_client = AuthClient(client_id, client_secret, '', enviroment)
    auth_client.refresh(refresh_token=refresh_token)
    return RefreshTokenResponse(
        auth_client.refresh_token,
        auth_client.x_refresh_token_expires_in,
        auth_client.access_token,
        auth_client.expires_in,
    )
def revoke(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
    )
    try:
        is_revoked = auth_client.revoke()
    except AuthClientError as e:
        print(e.status_code)
        print(e.intuit_tid)
    return HttpResponse('Revoke successful')
Пример #10
0
def account(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        realm_id=request.session.get('realm_id', None),
    )
    client = QuickBooks(
        auth_client=auth_client,
        refresh_token=request.session.get('refresh_token', None),
        company_id=4620816365030839390,
    )

    from quickbooks.objects.account import Account
    accounts = Account.all(qb=client)
    print(accounts)
    if auth_client.access_token is not None:
        access_token = auth_client.access_token

    if auth_client.realm_id is None:
        raise ValueError('Realm id not specified.')
    response = get_account_info(auth_client.access_token, auth_client.realm_id)
    if not response.ok:
        return HttpResponse(' '.join([response.content, str(response.status_code)]))
    else:
        response = response.json()["QueryResponse"]
        return JsonResponse(response)
Пример #11
0
def auth_client():
    if auth_client_obj is None:
        auth_client_obj = AuthClient(client_id=QBO_CLIENT_ID,
                                     client_secret=QBO_CLIENT_SECRET,
                                     environment=QBO_ENVIRONMENT,
                                     redirect_uri=qbo_redirect_uri())
    return auth_client_obj
Пример #12
0
def get_taxcodes(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        realm_id=request.session.get('realm_id', None),
    )

    if auth_client.access_token is not None:
        access_token = auth_client.access_token

    if auth_client.realm_id is None:
        raise ValueError('Realm id not specified.')

    response = qbo_data_call(auth_client.access_token,
                             auth_client.realm_id,
                             type='get_taxcodes')

    taxcodes = json.loads(response.content)
    #print(taxcodes)
    taxrates = dict()

    for t in taxcodes['QueryResponse']['TaxCode']:
        taxrates[t['Description']] = t['Id']

    print(taxrates)
    if not response.ok:
        return HttpResponse(' '.join(
            [response.content, str(response.status_code)]))
    else:
        return HttpResponse(json.dumps(taxrates),
                            content_type='application/json')
Пример #13
0
def refresh(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
    )

    try:
        auth_client.refresh()
    except AuthClientError as e:
        print(e.status_code)
        print(e.intuit_tid)
    return HttpResponse('New refresh_token: {0}'.format(auth_client.refresh_token))
Пример #14
0
def get_qbo_auth_client(callback_url):

    return AuthClient(
        client_id=settings.QBO_CLIENT_ID,
        client_secret=settings.QBO_CLIENT_SECRET,
        environment='sandbox' if settings.DEBUG else 'production',
        redirect_uri=callback_url,
    )
Пример #15
0
    def _create_client(self):
        auth_client = AuthClient(
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET,
            environment=ENVIRONMENT,
            redirect_uri=
            'https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl',
        )

        # Refresh token endpoint
        auth_client.refresh(refresh_token=REFRESH_TOKEN)

        client = QuickBooks(auth_client=auth_client,
                            refresh_token=REFRESH_TOKEN,
                            company_id=COMPANY_ID,
                            minorversion=54)

        return client
def callback(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        state_token=request.session.get('state', None),
    )

    state_tok = request.GET.get('state', None)
    error = request.GET.get('error', None)

    if error == 'access_denied':
        return redirect('app:index')

    if state_tok is None:
        return HttpResponseBadRequest()
    elif state_tok != auth_client.state_token:
        return HttpResponse('unauthorized', status=401)

    auth_code = request.GET.get('code', None)
    realm_id = request.GET.get('realmId', None)
    request.session['realm_id'] = realm_id

    if auth_code is None:
        return HttpResponseBadRequest()

    try:
        auth_client.get_bearer_token(auth_code, realm_id=realm_id)
        request.session['access_token'] = auth_client.access_token
        request.session['refresh_token'] = auth_client.refresh_token
        request.session['id_token'] = auth_client.id_token
        ###### ****** ######
        save_tokens(auth_client.access_token, auth_client.refresh_token,
                    realm_id)
    except AuthClientError as e:
        # just printing status_code here but it can be used for retry workflows, etc
        print(e.status_code)
        print(e.content)
        print(e.intuit_tid)
    except Exception as e:
        print(e)
    return redirect('app:connected')
Пример #17
0
def user_info(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        id_token=request.session.get('id_token', None),
    )

    try:
        response = auth_client.get_user_info()
    except ValueError:
        return HttpResponse('id_token or access_token not found.')
    except AuthClientError as e:
        print(e.status_code)
        print(e.intuit_tid)
    return HttpResponse(response.content)
Пример #18
0
def get_qbo_client(user, company):
    db = boto3.resource('dynamodb')
    table = db.Table(TABLE)
    token = get_user(user, company)['qbo_refresh_token']
    auth_client = AuthClient(CLIENT_KEY, CLIENT_SECRET, REDIRECT_URI, QBO_ENV)
    auth_client.refresh(refresh_token=token)
    client = QuickBooks(auth_client=auth_client,
                        refresh_token=auth_client.refresh_token,
                        environment=QBO_ENV,
                        company_id=company)
    response = table.update_item(
        Key={
            'company': company,
            'user': user
        },
        UpdateExpression="set #attr = :token",
        ExpressionAttributeValues={':token': auth_client.refresh_token},
        ExpressionAttributeNames={'#attr': 'qbo_refresh_token'})
    return client
Пример #19
0
def import_invoice(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        realm_id=request.session.get('realm_id', None),
    )

    print('CUSTOMER IS: ', request.GET.get('customer_ref'))
    if auth_client.access_token is not None:
        access_token = auth_client.access_token

    if auth_client.realm_id is None:
        raise ValueError('Realm id not specified.')

    payload = {
        "Line": [{
            "DetailType": "SalesItemLineDetail",
            "Amount": request.GET.get('amount'),
            "SalesItemLineDetail": {
                "ItemRef": {
                    "name": "I phone",
                    "value": "3"
                },
                "Qty": 1,
                "TaxCodeRef": {
                    "value": "14"
                }
            }
        }],
        "CustomerRef": {
            "value": "15"
        },
        "TxnDate":
        request.GET.get('txn_date'),
        "DueDate":
        "2019-03-18",
        "GlobalTaxCalculation":
        "TaxExcluded",
    }

    response = qbo_data_call(auth_client.access_token,
                             auth_client.realm_id,
                             type='import_invoice',
                             payload=payload)

    print(response.content)
    if not response.ok:
        return HttpResponse(' '.join(
            [response.content, str(response.status_code)]))
    else:
        return HttpResponse(response.content)
Пример #20
0
def refresh_session():
    s = json.loads(get_secret())

    auth_client = AuthClient(
        client_id=s["client_id"],
        client_secret=s["client_secret"],
        redirect_uri=s["redirect_url"],
        access_token=s["access_token"],
        refresh_token=s["refresh_token"],
        environment="production",
    )

    # caution! invalid requests return {"error":"invalid_grant"} quietly
    auth_client.refresh()
    s["access_token"] = auth_client.access_token
    s["refresh_token"] = auth_client.refresh_token
    put_secret(json.dumps(s))
    QuickBooks.enable_global()
    QuickBooks(auth_client=auth_client, company_id="1401432085")
    return auth_client
Пример #21
0
def start_up():
    auth_client = AuthClient(
    cfg.qbo['QBO_CLIENT_ID'],
    cfg.qbo['QBO_CLIENT_SECRET'],
    "https://tdasu.pagekite.me/redirect",
    environment="production"
    )

    scopes = [
        Scopes.ACCOUNTING,
        Scopes.PROFILE,
        Scopes.EMAIL,
        Scopes.OPENID,
        Scopes.ADDRESS,
        Scopes.PHONE
    ]
    auth_url = auth_client.get_authorization_url(scopes)
    print(auth_url)
    result = "<a href=\"" + auth_url + "\">" + auth_url + "</a"
    return result
Пример #22
0
    def _get_auth_client(self):
        '''Returns an OAuth2.0 Client for interacting
        with Quickbooks Reporting API.
        '''

        auth_client = AuthClient(
            self.config.get("client_id"),
            self.config.get("client_secret"),
            self.config.get("redirect_uri"),
            self.config.get("environment"),
            refresh_token=self.config.get("refresh_token"),
            realm_id=self.config.get("realm_id"))

        # Refresh to get new Access Token.
        auth_client.refresh()

        if auth_client.refresh_token == self.config.get("refresh_token"):
            LOGGER.info(
                "Config file Refresh Token and Refresh Token received from Refresh Token API are identical."
            )
        else:
            LOGGER.info(
                "Config file Refresh Token and Refresh Token received from Refresh Token API has drifted."
            )
            LOGGER.info(
                "Overwriting Config file with new Refresh Token values..")

            self.config["refresh_token"] = auth_client.refresh_token
            self.config[
                "refresh_token_expires_at"] = self._generate_token_expiration(
                    auth_client.x_refresh_token_expires_in)

            with open(self.args.config_path, 'r+') as f:
                json.dump(self.config, f, indent=2)

        # Check Refresh Token Expiry.
        self._check_token_expiry(auth_client)

        return auth_client
Пример #23
0
def refresh_token(company):

    c = company

    redirect_uri = "https://rc.royaltyclearinghouse.com/home/call-back"

    tokens_file = 'tokens.cfg'
    token_config = ConfigParser()
    token_config.read(tokens_file)

    realm_id = token_config[c]['realm_id']

    auth_client = AuthClient(
        client_id=token_config[c]['client_id'],
        client_secret=token_config[c]['client_secret'],
        redirect_uri=redirect_uri,
        environment=token_config[c]
        ['environment'],  # “sandbox” or “production”
    )

    refresh_tok = token_config[c]['refresh_token']

    try:
        auth_client.refresh(refresh_token=refresh_tok)
        rtoken = auth_client.refresh_token
        stoken = auth_client.access_token
        token_config.set(c, 'refresh_token', rtoken)
        token_config.set(c, 'access_token', stoken)
        with open(tokens_file, 'w+') as tokenfile:
            token_config.write(tokenfile)
        print(rtoken)
        print(stoken)
    except AuthClientError as e:
        print(e.status_code)
        print(e.content)
        print(e.intuit_tid)
Пример #24
0
def connected(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        id_token=request.session.get('id_token', None),
    )

    if auth_client.id_token is not None:
        return render(request, 'connected.html', context={'openid': True})
    else:
        return render(request, 'connected.html', context={'openid': False})
Пример #25
0
def init(app):
    '''
    Create global auth client that manages QuickBooks sessions.
    '''

    if not app.config["QUICKBOOKS_CLIENT_ID"]:
        app.logger.warn(
            "No QUICKBOOKS_CLIENT_ID specified, not setting up QB invoice feature."
        )
        return

    app.quickbooks_auth_client = AuthClient(
        client_id=app.config["QUICKBOOKS_CLIENT_ID"],
        client_secret=app.config["QUICKBOOKS_CLIENT_SECRET"],
        environment=app.config["QUICKBOOKS_SANDBOX"],
        redirect_uri=app.config["QUICKBOOKS_CALLBACK_URL"])
Пример #26
0
def migration(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
    )
    try:
        migrate(settings.CONSUMER_KEY, settings.CONSUMER_SECRET,
                settings.ACCESS_KEY, settings.ACCESS_SECRET, auth_client,
                [Scopes.ACCOUNTING])
    except AuthClientError as e:
        print(e.status_code)
        print(e.intuit_tid)
    return HttpResponse('OAuth2 refresh_token {0}'.format(
        auth_client.refresh_token))
Пример #27
0
def add_endpoints(app):

    auth_client = AuthClient(
        os.environ.get('QB_ID'),
        os.environ.get('QB_SECRET'),
        os.environ.get('QB_REDIRECTURL'),
        os.environ.get('QB_ENVIRONMENT'),
    )

    @app.route('/quickbooks/connect', methods=['GET'])
    def get_quickbooks_credentials():
        token = request.args.get("token")
        decoded_payload = decode_jwt(token)

        url = auth_client.get_authorization_url(
            [Scopes.ACCOUNTING], state_token=decoded_payload["sub"])

        return redirect(url), 200

    @app.route('/quickbooks/callback', methods=['GET'])
    def quickbooks_callback():
        url = "https://appcenter.intuit.com/connect/oauth2"
        code = request.args.get('code')
        user_id = request.args.get('state')
        realmId = request.args.get('realmId')
        print(
            f"These are your quickbooks credentials: code: {code} realm: {realmId}"
        )
        user1 = User.query.get(user_id)
        user1.qb_code = code
        user1.qb_realmID = realmId
        db.session.commit()

        sync_token(user_id)
        return jsonify(
            f"Hello {user1.name}!! Redirecting to private view."), 200

    def sync_token(user):
        url = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"

        auth_client.get_bearer_token(user.qb_code, realm_id=user.qb_realmID)
        user.qb_token = auth_client.access_token
        db.session.commit()

        return auth_client.access_token

    return app
Пример #28
0
    def setUp(self):
        super(QuickbooksTestCase, self).setUp()

        self.auth_client = AuthClient(
            client_id=os.environ.get('CLIENT_ID'),
            client_secret=os.environ.get('CLIENT_SECRET'),
            environment=Environments.SANDBOX,
            redirect_uri='http://localhost:8000/callback',
        )

        self.qb_client = QuickBooks(
            auth_client=self.auth_client,
            refresh_token=os.environ.get('REFRESH_TOKEN'),
            company_id=os.environ.get('COMPANY_ID'),
        )

        self.qb_client.sandbox = True
Пример #29
0
def send_vend_sales(request):
    auth_client = AuthClient(
        settings.CLIENT_ID,
        settings.CLIENT_SECRET,
        settings.REDIRECT_URI,
        settings.ENVIRONMENT,
        access_token=request.session.get('access_token', None),
        refresh_token=request.session.get('refresh_token', None),
        realm_id=request.session.get('realm_id', None),
    )

    if auth_client.access_token is not None:
        access_token = auth_client.access_token

    if auth_client.realm_id is None:
        raise ValueError('Realm id not specified.')

    response = retrieve_vend_sales()
    if not response.ok:
        return HttpResponse(' '.join(
            [str(response.content),
             str(response.status_code)]))

    sales_body = json.loads(response.content)

    response = post_sale_invoice(auth_client.access_token,
                                 auth_client.realm_id,
                                 sales=sales_body["register_sales"])
    if not response.ok:
        return HttpResponse(' '.join(
            [str(response.content),
             str(response.status_code)]))

    body = json.loads(response.content)
    external_invoice_id = body["Invoice"]["Id"]

    payment_response = post_invoice_payment(auth_client.access_token,
                                            auth_client.realm_id,
                                            external_invoice_id,
                                            sales=sales_body["register_sales"])
    if not payment_response.ok:
        return HttpResponse(' '.join(
            [str(payment_response.content),
             str(payment_response.status_code)]))

    return HttpResponse(payment_response.content)
Пример #30
0
def create_qbc():


    refresh_token = pickle.load( open( "refresh.token", "rb" ) )
    realm_id = pickle.load( open( "realm.id", "rb" ) )
    auth_client = AuthClient(
    cfg.qbo['QBO_CLIENT_ID'],
    cfg.qbo['QBO_CLIENT_SECRET'],
    "https://tdasu.pagekite.me/redirect",
    environment="production"
    )
    client = QuickBooks(
        auth_client=auth_client,
        refresh_token=refresh_token,
        company_id=realm_id,
    )
    return client