Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How do I get access token from url

##This is the code I have issues with 
import
fitbit
from selenium import webdriver
import gather_keys_oauth2 as oauth
import requests
import base64

driver = webdriver.Chrome()
url = "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=22D3D5&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2F&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"

driver.get(url)
consumer_key = "22D3D5"
consumer_secret = "2fd6fe11f582f60a570fdcb34232c5b1"
server = oauth.OAuth2Server
server = oauth.OAuth2Server(consumer_key, consumer_secret)
server.browser_authorize()
access_token = str(server.fitbit.client.session.token['access_token'])
refresh_token = str(server.fitbit.client.session.token['refresh_token'])
auth2_client = fitbit.Fitbit(consumer_key, consumer_secret, oauth2=True, access_token=access_token, refresh_token=refresh_token)


##This is gather_keys_oauth2.py, no issues with this code, included just in case
import
cherrypy
import os
import sys
import threading
import traceback
import webbrowser

from base64 import b64encode
from fitbit.api import Fitbit
from oauthlib.oauth2.rfc6749.errors import MismatchingStateError, MissingTokenError


class OAuth2Server:
def __init__(self, client_id, client_secret,
redirect_uri='http://127.0.0.1:8080/'):
""" Initialize the FitbitOauth2Client """
self.success_html = """
<h1>You are now authorized to access the Fitbit API!</h1>
<br/><h3>You can close this window</h3>"""
self.failure_html = """
<h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s"""

self.fitbit = Fitbit(
client_id,
client_secret,
redirect_uri=redirect_uri,
timeout=10,
)

def browser_authorize(self):
"""
Open a browser to the authorization url and spool up a CherryPy
server to accept the response
"""
url, _ = self.fitbit.client.authorize_token_url()
# Open the web browser in a new thread for command-line browser support
threading.Timer(1, webbrowser.open, args=(url,)).start()
cherrypy.config.update({'server.shutdown_timeout': 1})
cherrypy.quickstart(self)

@cherrypy.expose
def index(self, state, code=None, error=None):
"""
Receive a Fitbit response containing a verification code. Use the code
to fetch the access_token.
"""
error = None
if code:
try:
self.fitbit.client.fetch_access_token(code)
except MissingTokenError:
error = self._fmt_failure(
'Missing access token parameter.</br>Please check that '
'you are using the correct client_secret')
except MismatchingStateError:
error = self._fmt_failure('CSRF Warning! Mismatching state')
else:
error = self._fmt_failure('Unknown error while authenticating')
# Use a thread to shutdown cherrypy so we can return HTML first
self._shutdown_cherrypy()
return error if error else self.success_html

def _fmt_failure(self, message):
tb = traceback.format_tb(sys.exc_info()[2])
tb_html = '<pre>%s</pre>' % ('\n'.join(tb)) if tb else ''
return self.failure_html % (message, tb_html)

def _shutdown_cherrypy(self):
""" Shutdown cherrypy in one second, if it's running """
if cherrypy.engine.state == cherrypy.engine.states.STARTED:
threading.Timer(1, cherrypy.engine.exit).start()


if __name__ == '__main__':

if not (len(sys.argv) == 3):
print("Arguments: client_id and client_secret")
sys.exit(1)

server = OAuth2Server(*sys.argv[1:])
server.browser_authorize()

profile = server.fitbit.user_profile_get()
print('You are authorized to access data for the user: {}'.format(
profile['user']['fullName']))

print('TOKEN\n=====\n')
for key, value in server.fitbit.client.session.token.items():
print('{} = {}'.format(key, value))

When you run the first block of code, it authorizes you to use the API and then redirects you to a login page. After you log in, it takes you to the callback URI, which is the localhost. The localhost refuses to connect, I'm not sure why. Additionally, how do I get the access token from the end of the callback URI after the client signs in? Thanks
Best Answer
0 Votes
0 REPLIES 0