import requests


def authenticate_with_refresh_token(client_id, redirect_uri, refresh_token):
    """Get an access token with the existing refresh token."""

    try:
        url = 'https://api.tdameritrade.com/v1/oauth2/token'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        payload='grant_type=refresh_token&refresh_token='+refresh_token+'&client_id='+client_id+'&redirect_uri='+redirect_uri
        response = requests.request("POST", url, headers=headers, data = payload)
        data = response.json()
        return data['access_token']
    except:
        # Exception occurred, refresh token is invalid
        print('Invalid refresh token.')
        return ''