Authorization Flow

 1# This is an example where we run through the OAuth flow,
 2# select a business, and display a client from that business.
 3
 4from types import SimpleNamespace
 5from freshbooks import Client as FreshBooksClient
 6
 7FB_CLIENT_ID = "<your client id>"
 8SECRET = "<your client secret>"
 9REDIRECT_URI = "<your redirect uri>"
10
11freshBooksClient = FreshBooksClient(
12    client_id=FB_CLIENT_ID,
13    client_secret=SECRET,
14    redirect_uri=REDIRECT_URI
15)
16
17authorization_url = freshBooksClient.get_auth_request_url(
18    scopes=['user:profile:read', 'user:clients:read']
19)
20print(f"Go to this URL to authorize: {authorization_url}")
21
22# Going to that URL will prompt the user to log into FreshBooks and authorize the application.
23# Once authorized, FreshBooks will redirect the user to your `redirect_uri` with the authorization
24# code will be a parameter in the URL.
25auth_code = input("Enter the code you get after authorization: ")
26
27# This will exchange the authorization code for an access token
28token_response = freshBooksClient.get_access_token(auth_code)
29print(f"This is the access token the client is now configurated with: {token_response.access_token}")
30print(f"It is good until {token_response.access_token_expires_at}")
31print()
32
33# Get the current user's identity
34identity = freshBooksClient.current_user()
35businesses = []
36
37# Display all of the businesses the user has access to
38for num, business_membership in enumerate(identity.business_memberships, start=1):
39    business = business_membership.business
40    businesses.append(
41        SimpleNamespace(name=business.name, business_id=business.id, account_id=business.account_id)
42    )
43    print(f"{num}: {business.name}")
44business_index = int(input("Which business do you want to use? ")) - 1
45print()
46
47business_id = businesses[business_index].business_id  # Used for project-related calls
48account_id = businesses[business_index].account_id  # Used for accounting-related calls
49
50# Get a client for the business to show successful access
51client = freshBooksClient.clients.list(account_id)[0]
52print(f"'{client.organization}' is a client of {businesses[business_index].name}")