Chris
Chris

Reputation: 136

TDAmeritrade API Authentication Error: Failed to resolve API Key variable request.header.un

I'm having difficulty obtaining an access token from the token endpoint using PHP (https://developer.tdameritrade.com/authentication/apis/post/token-0)

Particularly, I'm getting the following error:

{ "error":"Failed to resolve API Key variable request.header.un" }

My request, using PHP, is:

  $url = 'https://api.tdameritrade.com/v1/oauth2/token';

  $client_id = $customer_key ;

   $redirect_uri = $redirect_URL;
  $myvars = array("grant_type" => "authorization_code"
                  , "access_type" => "offline"
                  , "client_id" => $client_id
                   , "redirect_uri" => $redirect_URL
                  , "code" => "$code");

  $ch = curl_init( $url );
  curl_setopt( $ch, CURLOPT_POST, 1);
  curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt( $ch, CURLOPT_VERBOSE, 1);
  curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8'

          ));

  $response = curl_exec( $ch );
  echo "<br>token = '$response'\n";

}

Thanks!

Upvotes: 3

Views: 4148

Answers (2)

Chris
Chris

Reputation: 136

OK, I finally got a working PHP script that authenticates into the TD API and obtains account information. I'd like to share it with everyone because I couldn't figure out how to get it working after almost three months. A special thanks to Ninet3 for helping me out. You can direct questions to his Fiverr profile (https://www.fiverr.com/ninety3)

$redirect_URL = 'https://YourURL.com';
$redirect_URL = urlencode($redirect_URL);
$customer_key = 'XXXXXXXXXXXXXXXXXXXX';
$account_number = '1234567890';

$url_endpoint = 'https://auth.tdameritrade.com/auth?response_type=code&redirect_uri='.$redirect_URL. '&client_id='.$customer_key.'%40AMER.OAUTHAP';

if(NULL === @$_GET['code']) {
    header("Location: $url_endpoint");//open TD website to get tokens
}


if($_GET['code'] !== '') {
    $code = $_GET['code'];

    $code = urlencode($code);
    if($code){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.tdameritrade.com/v1/oauth2/token',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0, CURLOPT_HEADER  => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded',
            ),
            CURLOPT_POSTFIELDS => 'grant_type=authorization_code&refresh_token=&access_type=offline&code='.$code.'&client_id='.$customer_key.'&redirect_uri='.$redirect_URL,
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $response = (json_decode($response, true));
                echo '<pre>';
                echo 'access_token: <br>';
                print_r($response );


 //Get account information      
        if(@$response['access_token'] !== null){
            $acc = $account_number;
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.tdameritrade.com/v1/accounts/'.$acc,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Bearer '.$response['access_token'],
                ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            echo '<pre>'.$response;

        }else{
            echo 'unable to get access token'; exit;
        }
    }
    else{
        echo 'No Code Found'; exit;
    }
}else{
    echo 'No Code Found'; exit;
}

You'll need to store the token in a database and refresh to get a new one after the time expires.

Upvotes: 3

CraigT
CraigT

Reputation: 1

I found this page when I got the exact same error message. I finally figured it out after quite a few tries and stepping away a few times. The biggest change from what you've posted is that when you use the header: "Content-Type: application/x-www-form-urlencoded" which TD wants for this API, you need to make the $myvars array into a string like the following:

$myvars = "grant_type=authorization_code&access_type=offline&code=".$code."&client_id=".$client_id."&redirect_uri=".urlencode($redirect_uri);

The other note here is the urlencode function to help url encode the string. It talks about that in the 'Notes' section of this page:

https://www.php.net/manual/en/function.curl-setopt.php

Upvotes: 0

Related Questions