Getting :- Error exchanging code for token: invalid_request
So I have been trying to make an extension using MyAnimeList API to fetch user data and upon callback after authorization of the user. It seems there seem to be some problem with my access token
def mal_callback(request):
code = request.GET.get('code')
# Exchange the code for an access token
token_response = post(
'https://myanimelist.net/v1/oauth2/token',
data={
'client_id': settings.MAL_CLIENT_ID,
'client_secret': settings.MAL_CLIENT_SECRET,
'code': code,
'grant_type': 'authorization_code',
'redirect_uri': settings.REDIRECT_URI,
}
).json()
if 'access_token' not in token_response:
error_message = token_response.get('error', 'Unknown error')
logger.error("Error exchanging code for token: %s", error_message)
return redirect('/error/')
logger.error("Token response: %s", token_response)
access_token = token_response['access_token']
# Retrieve user information
user_info_response = get(
'https://api.myanimelist.net/v2/users/@me',
headers={'Authorization': f'Bearer {access_token}'}
).json()
# Log the user info response
# Make sure user_info_response is valid
if 'name' not in user_info_response:
# Handle error
error_message = user_info_response.get('error', 'Unknown error')
logger.error("Error retrieving user info: %s", error_message)
return redirect('/error/') # Redirect to an error page or handle as needed
username = user_info_response['name']
# Create or get the user
user, created = User.objects.get_or_create(username=username)
# Create or update the ExternalUser model
external_user, _ = ExternalUser.objects.update_or_create(
user=user,
defaults={
'provider': 'MAL',
'access_token': access_token,
'refresh_token': token_response.get('refresh_token'),
'token_expires_at': token_response.get('expires_at'),
}
)
# Log the user in
login(request, user)
return redirect('/')
I rechecked all variable and constant values and all of them seem to be correct, I have recheck all of them multiple times and also after many logging and debugging I found out that the error seems to be in token response and access token