How to get access_token from fyers API? - python-3.x

I'm looking to get access_token from fyers API
I'm able to get authorization_code and build authorization_url to open it in browser to enter user credentials. access_token is displayed in browser's address when user enters credentials but my program is unable to retrieve the access_code.
Your help is much appreciable.
My code is as follows:
from fyers_api import accessToken
from fyers_api import fyersModel
import requests
import webbrowser
import urllib.request as ur
app_id = "XXXXXXXXX"
app_secret = "XXXXXXXXX"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
if response['code'] != 200:
print('CODE=' + str(response['code']))
print('MESSAGE=' + str(response['message']))
print('Exiting program...')
exit(0)
authorization_code = response['data']['authorization_code']
app_session.set_token(authorization_code)
authorization_url=app_session.generate_token('XXXXXX')
token = webbrowser.open(authorization_url)
#Following authorization url is opened in browser:
#https://api.fyers.in/api/v1/genrateToken?authorization_code=xxxxxxxxxxxxx&appId=xxxxxxxxx&user_id=xxxxxx
#User is redirected to following url after successful log-in:
#https://trade.fyers.in/?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=&user_id=xxxxxx
print(token)
#token=”your_access_token”
#is_async = False #(By default False, Change to True for asnyc API calls.)
#fyers = fyersModel.FyersModel(is_async)
#fyers. get_profile(token = token)

Instead of writing the mentioned code, it is better to directly call Fyers Api.
import requests
url = 'https://api.fyers.in/api/v1/token'
requestParams = {
"fyers_id":"Your Client ID",
"password":"Your Password",
"pan_dob":"Your PAN card or DOB(DD-MM-YYYY)",
"appId":"YOur APP ID",
"create_cookie":False}
response = requests.post(url, json = requestParams )
print (response.text)

from fyers_api import accessToken
from fyers_api import fyersModel
app_id = "xxxxxxxxxx"
app_secret = "xxxxxxxxxx"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
print(app_session)
print(response)
authorization_code = response['data']['authorization_code']
app_session.set_token(authorization_code)
gen_token = app_session.generate_token()
print("token url is copy paste this url in browser and copy access
token excluding your id at Last ")
print(gen_token)
print("tokent printed thanks")
token="gAAAAABeTWk7AnufuuQQx0D0NkgABinWk7AnufuuQQx0DQ3ctAFWk7AnufuuQQx0DMQQwacJ-
_xUVnrTu2Pk5K5QCLF0SZmw7nlpaWk7AnufuuQQx0DG4_3EGCYw92-iAh8="
is_async = False
fyers = fyersModel.FyersModel(is_async)
print(fyers. get_profile(token = token))
fyers.funds(token = token)
print(fyers.funds(token = token))

Related

often redirected to login page rather than authorization page

import random
import urllib.parse as urllibparse
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# credentials
Client_Id = <CLIENT_ID>
Client_Secret = <CLIENT_SECRET>
redirect_uri = 'http://localhost:5500/'
scope = "playlist-modify-private playlist-modify-public"
response_type = 'code'
username = <USERNAME>
randomNum =str(random.getrandbits(128))
hash = int(randomNum,36)
state = hex(hash)
spotifyToken = SpotifyOAuth(Client_Id,Client_Secret,redirect_uri,state,scope)
auth_url = spotifyToken.get_authorize_url()
print(auth_url)
spotifyObject = spotipy.Spotify(auth_manager=spotifyToken)
print(spotifyObject)
playlistName = "random"
playlistDescription = "just to check"
spotifyObject.user_playlist_create(user=username,name=playlistName,public=True,description=playlistDescription)
suggestions required
often redirected to login page rather than authorization page pls suggest some solution to resolve this problem or suggest any other way.

How to use the Google Sign In access token instead of authorization code for getting the data from the Google Search Console?

I want to access the listed websites data in the Google Search Console using the Google Sign-In access_token (that one can get as the response when using Google Sign-In).
But, the thing is I can access that data only by using the authorization_code that can be copied from the OAuth2-Consent screen by going to the generated authorize_url and signing in using the registered Google account.
Here's the minimum reproducible version of the code:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
Consider that I'll be provided with the Google Sign-In access-token as the request-parameter from another server which has implemented Google Sign-In feature.
So, again my question is how can I access the same data using that token instead of manually getting the auth_code from the OAuth2 consent screen ?
I have followed the documentation shared by DaImTo in the comments above. And modified the code as shown below:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client import tools, file
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Acquire and store oauth token.
storage = file.Storage('token.json')
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
credentials = tools.run_flow(flow, storage)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
It's working fine now, without any manual interaction for copying and pasting the authorization_code from the OAuth2-Consent screen.

Can t upload reports from QBO

I m trying to fetch QBO reports with python I have this error:
intuitlib.exceptions.AuthClientError: HTTP status 400, error message: b'{"error_description":"The token is not an authorization code: actualTokenType=RefreshToken","error":"invalid_grant"}',
I tried to change auth code to refresh token and it is not working. I was able to connect to QBO for objects like invoices,...
from intuitlib.client import AuthClient
from intuitlib.enums import Scopes
import requests
import QBOConnector
REDIRECT_URI = 'https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl'
auth_client = AuthClient(QBOConnector.CLIENT_ID, QBOConnector.CLIENT_SECRET, REDIRECT_URI, QBOConnector.environment )
url = auth_client.get_authorization_url([Scopes.ACCOUNTING])
auth_client.get_bearer_token(QBOConnector.TOKEN, realm_id=QBOConnector.CLIENT_ID)
auth_header = 'Bearer {0}'.format(auth_client.access_token)
headers = {
'Authorization': auth_header,
'Accept': 'application/json'
}
base_url = 'https://sandbox-quickbooks.api.intuit.com'
url = '{0}//v3/company/{1}/query?query=ProfitAndLoss?&minorversion=4'.format(base_url,auth_client.realm_id)
print('Url')
print(url)
response = requests.get(url, headers=headers)
print profil and loss report for a specific period of time
REDIRECT_URI = 'https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl' # not using the redirection at the moment
ENV = QBOConnector.PROD_environment
REFRESH_TOKEN = QBOConnector.PROD_TOKEN # Refresh token needs to be added here (which will be generated from https://developer.intuit.com/app/developer/playground)
COMPANY_ID = QBOConnector.PROD_COMPANY_ID #id of the company that we use in the example
# auth credentials to connect to the QBO account
auth_client = AuthClient(
client_id = QBOConnector.PROD_CLIENT_ID,
client_secret = QBOConnector.PROD_CLIENT_SECRET,
environment = ENV,
redirect_uri = REDIRECT_URI,
)
# creating the client object to access the QBO account
client = QuickBooks(
auth_client= auth_client,
refresh_token= REFRESH_TOKEN,
company_id= COMPANY_ID,
)
# retrieving all customers for the above client object
customers = Customer.all(qb=client)
# printing all customer names on the console/shell
for customer in customers:
print (customer)
# request authorization
auth_header = 'Bearer {0}'.format(auth_client.access_token)
headers = {
'Authorization': auth_header,
'Accept': 'application/json'
}
base_url = 'https://quickbooks.api.intuit.com'
# --- trial Balance
url = '{0}//v3/company/{1}/reports/TrialBalance?end_date=2019-09-30&minorversion=4'.format(base_url,
QBOConnector.PROD_COMPANY_ID)
response = requests.get(url, headers=headers)

Paylocity API Access Token

I have been trying to retreive the access token for the paylocity API. I am able to get it through postman with the client id and client secret however when I try and retrieve it with Python I get the message {"error":"invalid_client"}. This is the code that I am using
import json
import base64
import requests
url = "https://api.paylocity.com/IdentityServer/connect/token"
client_id = ''
client_secret = ''
auth = (f'{client_id}:{client_secret}')
headers = {
'content-type': "application/x-www-form-urlencoded",
'Authorization': f"Basic {auth}"
}
body = "grant_type=client_credentials&scope=WebLinkAPI"
response = requests.request("POST", url, data=body, headers=headers)
print (response.text)
In case someone else stumbles on this response, since there are not many search hits for this:
To get the token from Paylocity and call their API:
client_id = {your client id string}
client_secret = {your client secret}
company_id = {your company id from Paylocity dashboard, without leading 'CS'}
prod_auth_url = 'https://api.paylocity.com/IdentityServer/connect/token'
body_params = urllib.parse.urlencode({'grant_type': 'client_credentials','scope':'WebLinkAPI'})
# Requests can use auth= for basic authentication
auth_response = requests.post(prod_auth_url,auth=(client_id, client_secret), data=urllib.parse.urlencode(body_params))
response = json.loads(auth_response.content)
api_call_headers = {'Authorization': 'Bearer ' + response['access_token']}
# Get all employees for a company
empl_response = requests.get(f"https://api.paylocity.com/api/v2/companies/{company_id}/employees/",headers=api_call_headers, verify=False)
pd.DataFrame(json.loads(empl_response.text))
Make sure you're using the client_id and client_secret for your token call, not the company id. It is not necessary to use any OAuth2 libraries to access the API.
for only the token I do:
import requests, json
token_url = "https://apisandbox.paylocity.com/IdentityServer/connect/token"
#client credentials
client_id = 'XXXX'
client_secret = 'XXXXXX'
#step A, B - single call with client credentials as the basic auth header - will return access_token
data = {'grant_type': 'client_credentials', 'scope':'WebLinkAPI'}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print(access_token_response.headers)
print (access_token_response.text)
And after that code I recived the Token the same as the PostMan.
you can check: https://developer.byu.edu/docs/consume-api/use-api/oauth-20/oauth-20-python-sample-code
for more information/options.
Try the following with the same variables:
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=url, client_id=client_id, client_secret=client_secret, body=body, headers=headers)

How to convert Postman OAuth 2.0 to Python

I have been getting the issue when I'm trying to convert Postman OAuth 2.0 to Python3. I tried to research but seems unfortunate for me, I did not find any example
Here is my code:
from rauth import OAuth2Service
import json
def get_token(client_id, client_secret):
access_token = None
service = OAuth2Service(
name="Viafoura",
client_id=client_id,
client_secret=client_secret,
access_token_url='https://auth.viafoura.io/authorize_client'
)
data = {
'scope': 'xxxxx-xxxx-xxxx-xxxx-xxxxx',
'grant_type': 'client_credentials'
}
session = service.get_auth_session(data=data)
access_token = session
Here is OAuth 2.0 on Postman and it's working:
I want to get the access_token via Python3. Could anyone please help me on it?
Maybe it can help you, an example with the basic algorithm of OAuth2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from requests import post, auth, exceptions
from json import loads
if __name__ == '__main__':
client_id = ''
client_secret = ''
user = ''
password = ''
access_point = 'https://account.lab.fiware.org/oauth2/token'
grant_type = 'password'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
auth = auth.HTTPBasicAuth(client_id, client_secret)
data = {'grant_type': grant_type,
'username': user,
'password': password}
resp = None
try:
resp = post(access_point, auth=auth, data=data, headers=headers, timeout=5)
except exceptions.ConnectionError:
exit(1)
if resp.status_code == 200:
resp = loads(resp.text)
if 'access_token' in resp:
print(resp['access_token'])
exit(0)
exit(1)
You need to fix access point, grant type. This source code can be found here
Sorry, I can't help directly with Viafoura and OAuth2Service library.

Resources