Help with PHP/cURL to handle OAUTH2

Heya, a while ago someone helped me by giving me the below function to get the token for OAUTH2. Up until January it was working fine & I’ve come back to it this week and it doesn’t work now. Does someone know if something has changed with the API and I need to amend the code or does the following code work for them & it’s something I’m now doing wrong/up with my new Apache server?

<?PHP

// OAUTH2 Log in
 function getToken() {
   //curl -u {client_id}:{client_secret} -d grant_type=client_credentials https://us.battle.net/oauth/token
   $client_id = 'YOUR_ID';
  $client_secret = 'YOUR_SECRET';
  $url = "https://eu.battle.net/oauth/token";
  $params = ['grant_type'=>'client_credentials'];
   $curl = curl_init();
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  curl_setopt($curl, CURLOPT_USERPWD, $client_id.':'.$client_secret);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
   $result = json_decode(curl_exec($curl));
   curl_close($curl);
  return $result->access_token;
}

// Download JSON function	
function gzipGet($url) {
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,   // Fetch this URL
        CURLOPT_FOLLOWLOCATION => true,   // Follow redirects
        CURLOPT_MAXREDIRS      => 3,      // Follow this many redirects at most
        CURLOPT_RETURNTRANSFER => true,   // CURL exec returns data into variable
        CURLOPT_SSLVERSION     => 6,      // Use TLSv1.2 for SSL connections, required by battle.net
        CURLOPT_TIMEOUT        => 20,     // Seconds
        CURLOPT_ENCODING       => 'gzip', // Use gzip transfer encoding, if available
    ]);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}


//call OAUTH2 function and set it to $token var
$token = getToken();

echo $token;
?>

Hello.

Perhaps this topic might help you out.

It looks like your code is ok, in January a new data policy was applied. Probably all you need to do is manage your client credentials and accept the new terms of service.

1 Like

Hi Schiller thank you for taking the time to reply. You were correct, the new data policy & accepting the new ToS has solved it!