dionsyran2
dionsyran2

Reputation: 11

PHP Discord oauth: Trying to get property 'access_token' of non-object

I am trying to create a login page, but with discord oauth2, so users will log in using discord, The problem is that i get this error:

Notice: Trying to get property 'access_token' of non-object

Here is the part of the code with the error:

if(get('code')) {

  // Exchange the auth code for a token
  $token = apiRequest($tokenURL, array(
    "grant_type" => "authorization_code",
    'client_id' => OAUTH2_CLIENT_ID,
    'client_secret' => OAUTH2_CLIENT_SECRET,
    'redirect_uri' => 'https://site.website/login.php', //The url is changed by me as i do not want people going in the website
    'code' => get('code')
  ));
  $logout_token = $token->access_token;
  $_SESSION['access_token'] = $token->access_token;


}

And here is the function that sends the request

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $response = curl_exec($ch);


  if($post)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

  $headers[] = 'Accept: application/json';

  if(session('access_token'))
    $headers[] = 'Authorization: Bearer ' . session('access_token');

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);
  return json_decode($response);
}

I would like to say that I do not know much about php, as I am still learning

Upvotes: 0

Views: 1687

Answers (1)

Sergio Cordero Pino
Sergio Cordero Pino

Reputation: 11

the json_decode function returns false if the response is not a correctly JSON formatted string, there is nothing apparently wrong with your curl but maybe the response you are gettiing from the site is a simple string as an Error and not an error formatted as a json string

Upvotes: 1

Related Questions