import json
import requests
import pyotp
import hashlib
from urllib import parse
import sys
# This script will only work if TOTP is enabled.
# You can enable TOTP using this link: https://myaccount.fyers.in/ManageAccount >> External 2FA TOTP >> click on "Enable".
# Client Information (ENTER YOUR OWN INFO HERE! Data varies from users and app types)
CLIENT_ID = "" # Your Fyers Client ID
PIN = "" # User pin for Fyers account
APP_ID = "" # App ID from MyAPI dashboard (https://myapi.fyers.in/dashboard). The format is appId-appType.
APP_TYPE = "100"
APP_SECRET = "" # App Secret from myapi dashboard
TOTP_SECRET_KEY = "" # TOTP secret key
REDIRECT_URI = "https://trade.fyers.in/api-login/redirect-uri/index.html" # Redirect URL from the app
# API endpoints
BASE_URL = "https://api-t2.fyers.in/vagator/v2"
BASE_URL_2 = "https://api-t1.fyers.in/api/v3"
URL_VERIFY_CLIENT_ID = BASE_URL + "/send_login_otp"
URL_VERIFY_TOTP = BASE_URL + "/verify_otp"
URL_VERIFY_PIN = BASE_URL + "/verify_pin"
URL_TOKEN = BASE_URL_2 + "/token"
URL_VALIDATE_AUTH_CODE = BASE_URL_2 + "/validate-authcode"
SUCCESS = 1
ERROR = -1
def verify_client_id(client_id):
try:
payload = {
"fy_id": client_id,
"app_id": "2"
}
resp = requests.post(url=URL_VERIFY_CLIENT_ID, json=payload)
if resp.status_code != 200:
return [ERROR, resp.text]
data = resp.json()
return [SUCCESS, data["request_key"]]
except Exception as e:
return [ERROR, str(e)]
def generate_totp(secret):
try:
return [SUCCESS, pyotp.TOTP(secret).now()]
except Exception as e:
return [ERROR, str(e)]
def verify_totp(request_key, totp):
try:
payload = {
"request_key": request_key,
"otp": totp
}
resp = requests.post(url=URL_VERIFY_TOTP, json=payload)
if resp.status_code != 200:
return [ERROR, resp.text]
data = resp.json()
return [SUCCESS, data["request_key"]]
except Exception as e:
return [ERROR, str(e)]
def verify_PIN(request_key, pin):
try:
payload = {
"request_key": request_key,
"identity_type": "pin",
"identifier": pin
}
resp = requests.post(url=URL_VERIFY_PIN, json=payload)
if resp.status_code != 200:
return [ERROR, resp.text]
data = resp.json()
return [SUCCESS, data["data"]["access_token"]]
except Exception as e:
return [ERROR, str(e)]
def token(client_id, app_id, redirect_uri, app_type, access_token):
try:
payload = {
"fyers_id": client_id,
"app_id": app_id,
"redirect_uri": redirect_uri,
"appType": app_type,
"code_challenge": "",
"state": "sample_state",
"scope": "",
"nonce": "",
"response_type": "code",
"create_cookie": True
}
headers = {'Authorization': f'Bearer {access_token}'}
resp = requests.post(url=URL_TOKEN, json=payload, headers=headers)
if resp.status_code != 308:
return [ERROR, resp.text]
data = resp.json()
url = data["Url"]
auth_code = parse.parse_qs(parse.urlparse(url).query)['auth_code'][0]
return [SUCCESS, auth_code]
except Exception as e:
return [ERROR, str(e)]
def sha256_hash(appId, appType, appSecret):
msg = f"{appId}-{appType}:{appSecret}".encode()
return hashlib.sha256(msg).hexdigest()
def validate_authcode(auth_code):
try:
app_id_hash = sha256_hash(appId=APP_ID, appType=APP_TYPE, appSecret=APP_SECRET)
payload = {
"grant_type": "authorization_code",
"appIdHash": app_id_hash,
"code": auth_code,
}
resp = requests.post(url=URL_VALIDATE_AUTH_CODE, json=payload)
if resp.status_code != 200:
return [ERROR, resp.text]
data = resp.json()
return [SUCCESS, data["access_token"]]
except Exception as e:
return [ERROR, str(e)]
def main():
# 1) Verify client ID
status, request_key = verify_client_id(CLIENT_ID)
if status != SUCCESS:
print(f"verify_client_id failure - {request_key}")
sys.exit(1)
print("verify_client_id success")
# 2) Generate TOTP
status, totp = generate_totp(TOTP_SECRET_KEY)
if status != SUCCESS:
print(f"generate_totp failure - {totp}")
sys.exit(1)
print("generate_totp success")
# 3) Verify TOTP
status, request_key = verify_totp(request_key, totp)
if status != SUCCESS:
print(f"verify_totp failure - {request_key}")
sys.exit(1)
print("verify_totp success")
# 4) Verify PIN
status, fyers_access_token = verify_PIN(request_key, PIN)
if status != SUCCESS:
print(f"verify_pin failure - {fyers_access_token}")
sys.exit(1)
print("verify_pin success")
# 5) Exchange for auth code
status, auth_code = token(CLIENT_ID, APP_ID, REDIRECT_URI, APP_TYPE, fyers_access_token)
if status != SUCCESS:
print(f"token failure - {auth_code}")
sys.exit(1)
print("token success")
# 6) Validate auth code to get final V3 token
status, v3_access = validate_authcode(auth_code)
if status != SUCCESS:
print(f"validate_authcode failure - {v3_access}")
sys.exit(1)
print("validate_authcode success")
# Build the composite access token
final_token = f"{APP_ID}-{APP_TYPE}:{v3_access}"
print(f"\nAccess Token: {final_token}\n")
# --- SAVE ONLY THE ACCESS TOKEN ---
wit
h open("access_token.log", "a") as log_file:
log_file.write(final_token + "\n")
print("Access token appended to access_token.log")
if __name__ == "__main__":
main()