Kerblooy
Kerblooy

Reputation: 219

curl PUT request with discord API resulting bad request

I'm using php, oauth2, and curl to connect to the Discord API and add a member to a server (guild).

I have successfully authenticated the user using Oath2 with the identify, guilds, and guilds.join scope. I have the access_token & the bot token needed.

From my understanding in the Discord API docs: https://discord.com/developers/docs/resources/guild#add-guild-member

I need to use a PUT request with the access_token (with guilds.join scope) and headers with Authentication: Bot Token to the endpoint: https://discordapp.com/api/guilds/GUILDID/members/USERID

I have done this but receive a 400 Bad Request error. I am not sure what the problem could be.

Config

define('OAUTH2_CLIENT_ID', 'REDACTED');
define('OAUTH2_CLIENT_SECRET', 'REDACTED');

$guildid = REDACTED

$authorizeURL = 'https://discord.com/api/oauth2/authorize?client_id=REDACTED&permissions=0&redirect_uri=https%3A%2F%2FREDACTED%2Findex.php%3Faction%3Ddiscord&response_type=code&scope=identify%20guilds%20guilds.join%20bot';
$tokenURL = 'https://discordapp.com/api/oauth2/token';
$apiURLBase = 'https://discordapp.com/api/users/@me';
$apiURLGuilds = 'https://discordapp.com/api/users/@me/guilds';
$apiURLJoin = 'https://discordapp.com/api/guilds/'. $guildid . '/members/';

join function

function joinapiRequest($url,$userid) {
  $url = $url.$userid;

  $params = 'access_token='.session('access_token');
  


  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

  $bottoken = redacted;
  $headers[] = 'Authorization: Bot ' . $bottoken;
  $headers[] = 'Content-Type: application/json';
  $headers[] = 'Content-Length: '.strlen($params);
  
  
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $response = curl_exec($ch);

  echo 'join guild response <br />';
  var_dump($response);
  

  if($http == 201){
    return true;
  } else {
    return false;
  }


}

response

string(42) "{"message": "400: Bad Request", "code": 0}" 

Any help would be much appreciated.

Upvotes: 0

Views: 1817

Answers (1)

Kerblooy
Kerblooy

Reputation: 219

For anyone looking for an answer, I fixed this by changing the syntax on sending the access_token to:

$params = '{"access_token" : "'.session('access_token').'"}';

Upvotes: 1

Related Questions