Not able to get access_token

I am getting an error when trying to get the access_token from the auth_code using generate_access_token. I am getting the following error.

{“s”:“error”,“code”:-17,“message”:“Could not authenticate the user”}

We are using Javascript. We get the auth_code using the totp process but get this error when we try to generate access token.

Hi @yashwant.05rejtkv ,

Please follow documentation for login process : https://myapi.fyers.in/docs#tag/Authentication-and-Login-Flow-User-Apps

I am getting the following error when calling https://api.fyers.in/api/v2/validate-authcode to get the access token.

Request failed with status code 401

Please note that I am following totp process flow to get an auth_code. I am able to proceed till getting the auth_code but get an error when I try to get the access token using the auth code.

Can you please share your code @yashwant.05rejtkv

Same for me. Using postman api’s

Please follow the documentation.
First create auth token and then using auth token create access token.

Doc url : https://myapi.fyers.in/docs#tag/Authentication-and-Login-Flow-User-Apps

We need to connect directly from our backend without user intervention so we are using the totp method for getting the auth token. However when we try to use that auth token to create an access token we are getting an error.

@naresh_janagam can you help with this.

Hi @yashwant.05rejtkv ,

Kindly share your code with us so that we can check.

Here is the code we are using

const sendOtpResponse = await axios.post(URL_SEND_LOGIN_OTP, { fy_id: fy_id, app_id: app_id });
const totp = authenticator.generate(totp_secret);
const verifyOtpResponse = await axios.post(URL_VERIFY_TOTP, { request_key: sendOtpResponse.data.request_key, otp: totp });
const verifyPinResponse = await axios.post(URL_VERIFY_PIN, { request_key: verifyOtpResponse.data.request_key, identity_type: “pin”, identifier: pin, recaptcha_token: “” });
let tokenHeaders = { ‘authorization’: Bearer ${verifyPinResponse.data.data.access_token}};
const tokenResponse = await axios.post(URL_TOKEN, {fyers_id: fy_id, app_id: app_id, redirect_uri: redirect_uri, appType: app_type, code_challenge: “”, state: “None”, scope: “”, nonce: “”, response_type: “code”, create_cookie: true}, {headers: tokenHeaders});
const auth_code = tokenResponse.data.data.auth;
fyers.setAppId(app_id_with_suffix);
fyers.setRedirectUrl(redirect_uri);
const getAccessTokenResponse = await fyers.generate_access_token({“auth_code”: auth_code, “secret_key”: secret_key});

We wrote this JS code based on some sample Python code we had got for this flow. Earlier we were able to get a auth_code using this code but got an error when using that auth code to get the access token. However now we are getting a 308 error when trying to get the auth_code itself.

Hi @yashwant.05rejtkv

It is expected behaviour that you will get 308 status. As it confirms that your app is authorised. It is returning the redirect URL and you have to handle this.

And for axios , you should write in try , catch block.

However I am providing to you to code which will help you to generate AuthCode

import otplib from 'otplib';
import axios from 'axios';

const BASE_URL = "https://api-t2.fyers.in/vagator/v2"
const BASE_URL_2 = "https://api.fyers.in/api/v2"
const URL_SEND_LOGIN_OTP = BASE_URL + "/send_login_otp"
const URL_VERIFY_TOTP = BASE_URL + "/verify_otp"
const URL_VERIFY_PIN = BASE_URL + "/verify_pin"
const URL_TOKEN = BASE_URL_2 + "/token"
const URL_VALIDATE_AUTH_CODE = BASE_URL_2 + "/validate-authcode"
const SUCCESS = 1
const ERROR = -1

async function sendLoginOTP(fy_id, app_id) {
    try {
        const response = await axios.post(URL_SEND_LOGIN_OTP, { fy_id, app_id });

        if (response.status !== 200) {
            return [ERROR, response.data];
        }

        const { request_key } = response.data;
        return [SUCCESS, request_key];
    } catch (error) {
        return [ERROR, error.message];
    }
}

async function verifyTOTP(request_key, totp) {
    try {
        const response = await axios.post(URL_VERIFY_TOTP, { request_key, otp: totp });

        if (response.status !== 200) {
            return [ERROR, response.data];
        }

        const { request_key: newRequestKey } = response.data;
        return [SUCCESS, newRequestKey];
    } catch (error) {
        return [ERROR, error.message];
    }
}

async function verifyPIN(request_key_2, PIN) {
    try {
        const ses = axios.create();

        const payload_pin = {
            "request_key": request_key_2,
            "identity_type": "pin",
            "identifier": PIN,
            "recaptcha_token": ""
        };

        const res_pin = await ses.post(URL_VERIFY_PIN, payload_pin);
        return [SUCCESS, res_pin.data];
    } catch (error) {
        return [ERROR, error.message];
    }
}

async function GenAuthcode(FY_ID, TOTP_KEY, PIN, APP_ID, REDIRECT_URI,APP_TYPE) {
    const APP_ID_TYPE = "2"
    const send_otp_result = await sendLoginOTP(FY_ID, APP_ID_TYPE);

    if (send_otp_result[0] !== SUCCESS) {
        console.log(`send_login_otp failure - ${send_otp_result[1]}`);
        process.exit(1);
    } else {
        console.log("send_login_otp success");
    }

    let verify_totp_result;

    for (let i = 1; i  setTimeout(resolve, 1000)); // Wait for 1 second before retrying
        } else {
            break;
        }
    }

    const request_key_2 = verify_totp_result[1];
    const ses = axios.create();
    const payload_pin = {
        "request_key": request_key_2,
        "identity_type": "pin",
        "identifier": PIN,
        "recaptcha_token": ""
    };
    const res_pin = await ses.post(URL_VERIFY_PIN, payload_pin);
    const ses1 = axios.create({
        headers: {
          'authorization': `Bearer ${res_pin.data['data']['access_token']}`
        },
        maxRedirects: 10,
      });
    const authParam = {
        "fyers_id": FY_ID,
        "app_id": APP_ID,
        "redirect_uri": REDIRECT_URI,
        "appType": APP_TYPE,
        "code_challenge": "",
        "state": "None",
        "scope": "",
        "nonce": "",
        "response_type": "code",
        "create_cookie": true
    };
    let authres
    try {
         authres = await ses1.post('https://api.fyers.in/api/v2/token', authParam);
    } catch (error) {
        if(error.response.status==308){
         authres = error.response
        }else{
            console.log("Manual login requried for authorizing the app")
            process.exit(0)
        }
    }
    const url = authres.data['Url'];
    const parsed = new URL(url);
    const auth_code = parsed.searchParams.get('auth_code');

    return auth_code;
}

var resp=await GenAuthcode("FYID","TOTPKEY","PIN","APPID without app type(without-100)","RedirectURL","apptype ie(100,102)")
var token=resp
console.log(token)

Hi Pankaj,

Thanks for sharing the code. I am able to get a token using this code. However when I use that token to send a request, for eg to get a quote, I am getting an error that Request failed with status code 500.

Here is the code I using to try and get the quote after getting the token using your code. Let me know if there is any issue with it.

try {
let headers = { ‘Authorization’: ${app_id_with_suffix}:${token} };
const quoteResponse = await axios.get(BASE_URL_2 + ‘/data/quotes?symbols=NSE:SBIN-EQ’, { headers: headers });
console.log(JSON.stringify(quoteResponse.data));
} catch (error) {
console.log('Error - ’ + error.message);
}

Regards,
Yashwant

Hi @yashwant.05rejtkv ,

The code which I provided you, that is creating for auth token not for access token.
Auth token and access token both are different. So whenever you are requesting any APIs , you have to send the access token not auth code.

So Using the auth code(which you got from my code), generate the access token. then using the access token hit the request. It will work.

Hope , it will help you. If you stuck again , Please let me know I will help you.

Thank you.

Hi Pankaj,

We were able to get it working now by using the fyers js library to get the access token from the auth_code and then using the access token to make a service request for quotes (using both the fyers js library and a direct axios call).

Had one more query. As mentioned above we are using the fyers js library to get the access token from the auth_code. Can you also share what is the code or logic to get this directly without using the library?

Thanks for all your help.

Regards,
Yashwant

Hi @yashwant.05rejtkv ,

Please refer this part of documentation. Link .
Refer the part “Request Parameters for Step 2”
Hope it will help. Thanks