How to get guild info using discord oauth? - javascript

How can i get a particular guild info? It's working if i remove guilds.id, but then it only return list of all guilds i am in.
what is the correct method to get and update guild information using discord api?
This is how i'm getting my access_token:
const key = req.query.code,
options = {
href:`https://discordapp.com/api/oauth2/token`,
code : `code=${key}`,
grant_type : grant_type=authorization_code`,
redirect_uri :`redirect_uri=${redirect}`
};
request({
uri: `${options.href}?${options.grant_type}&${options.code}&${options.redirect_uri}`,
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
}
}, (err,response, body) => {
if(err) return console.log(err);
console.log(body) // console log access_token
})
Using access_token to make request
//My get request options
const options = {
url: `https://discordapp.com/api/guilds/${guilds.id}`,
method: 'GET',
json: true,
headers: {
authorization: `${token_type} ${access_token}`}
}
//Both of these options arent working
//token_type = bot
//token_type = Bearer
Gives me 401: Unauthorized.
My access_token scope is:
`identify email guilds guilds.join gdm.join rpc connections`

Related

'API Unauthorized Request' when trying to withdraw funds using Celsius SDK

I'm currently working on integrating Celsius Network into our app. I got a partner token from partners#celsius, however, the support told me this token was "read-only". With this token, I'm able to call most API endpoints such as getBalance, gethealth, getInterestedRates, txSummaries. But I'm unable to call send/withdraw or create a new user.
When I try to withdraw my funds I get an 'API Unauthorized Request' error. I tried contacting partners support multiple times, but no one has answered me. Has anyone dealt with this error before?
My Code:
const { Celsius, AUTH_METHODS, ENVIRONMENT } = require('celsius-sdk');
const partnerKey: string = ****;
const apiKey: string = ****;
Celsius({
authMethod: AUTH_METHODS.USER_TOKEN
authMethod: AUTH_METHODS.API_KEY,
partnerKey: partnerKey,
environment: ENVIRONMENT.PRODUCTION
> }).then(celsius => {
const axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('address', aValidEthAddress);
data.append('amount', '0.00007');
let config = {
method: 'post',
url: 'https://wallet-api.celsius.network/wallet/ETH/withdraw',
headers: {
'X-Cel-Partner-Token': partnerKey,
'X-Cel-Api-Key': apiKey,
...data.getHeaders(),
},
data: data,
};
axios(config)
> .then(function (response) {
console.log(JSON.stringify(response.data));
> })
> .catch(function (error) {
console.log(error);
> });
> });
I tried sending a post request to https://wallet-api.celsius.network/wallet/ETH/withdraw' with the following headers:
headers: {
'X-Cel-Partner-Token': partnerKey,
'X-Cel-Api-Key': apiKey,
...data.getHeaders()
},
I expected to get a success message and the funds to be sent to the address provided as data.address.

discord api add user to guild

Hi I am trying to use discord api to add the user to the guild when he login. But I am getting 401 Unauthorized and I am not sure why.
This is my code:
const data = new FormData();
data.append("client_id", CLIENT_ID);
data.append("client_secret", CLIENT_SECRET);
data.append("grant_type", "authorization_code");
data.append("redirect_uri", `http://localhost:3000/callback`);
data.append("scope", "identify,guilds.join");
data.append("code", req.query.code);
var response = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
body: data
});
const json = await response.json();
var resp = await fetch(`https://discord.com/api/guilds/813847215058845708/members/463696108766494730`, {
method: "PUT",
headers: {
"Authorization": `Bot ${json.access_token}`,
"Content-Type": "application/json",
}
});
console.log(resp)
Everything seems to be working,I can get the user avatar,name and etc. but can't add him to the guild,anyone help me,plz
You're providing an invalid authorization header. You can't use your access token with the bot prefix since you're making a normal OAuth2 call. Instead you need to provide the token type returned by the Discord-API.
Change
headers: {
"Authorization": `Bot ${json.access_token}`,
"Content-Type": "application/json",
}
to
headers: {
authorization: `${json.token_type} ${json.access_token}`
}
Also, the way you pass your scopes seems to be incorrect as well. Try
data.append("scope", "identify guilds guilds.join");

How do I get the scope values of a discord oauth2 implicit grant?

I have built a discord bot and now want to build a website for it. I have managed to setup an implicit grant with discord oauth2, however I don't know how to get any of my scope values (identity, email, guilds, bot). All I have is the access token, the token type, the time it will take to expire, the guild id and the scopes, which are listed in the url. Please help!!!!
You need to call the GetCurrentUser Api
It is a GET to https://discord.com/api/users/#me
And you have to pass the Authorization header with your token.
EDIT
In javascript this code should do the work:
fetch('https : //discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
})
.then(res => res.json())
.then(data => {
console.log(data);
});
Or async version:
async getUserInfo() {
const response = await fetch('https://discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
});
var data = await response.json();
console.log(data);
}
getUserInfo();
The values you're looking for should be set as claims in your token.
Try to paste the token into https://jwt.io/

"grant_type parameter is missing": Spotify API PKCE OAuth Flow Troubles

I'm developing a React app that uses the Spotify API I can't figure out why I'm getting this error when trying to get an access token with the API's PKCE OAuth flow.
{
error: "unsupported_grant_type",
error_description: "grant_type parameter is missing"
}
I'm following the directions from the guide exactly and I'm able to obtain an auth code just fine. Here's my call trying to get the token.
let res = await axios.post("https://accounts.spotify.com/api/token", {}, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
params: {
"grant_type": "authorization_code",
"code": data.code,
"redirect_uri": redirectUri,
"code_verifier": verifier,
"client_id": clientId
}
}).catch(err => console.error(err));
I've tried passing the params in the body of the post request and as url params and both produce the same results. As you can see, I'm clearly providing a grant_type and I'm using the value that the guide said to use.
I've tried every method I was able to find on the internet, nothing seemed to be working, but after a few hours, this succeeded:
const headers = {
Authorization:
'Basic ' +
new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'),
}
const { data } = await axios.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
headers: { headers },
)
this.token = data.access_token
After this, you can simply use any endpoint as seen in the Spotify API examples.
Use querystring npm package to parse the data since we're using application/x-www-form-urlencoded in the header
And change the grant_type to grant_type: "client_credentials"
var querystring = require('querystring');
const headers = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
};
let data = {
grant_type: "client_credentials",
code: data.code,
redirectUri: "http://localhost:8000/callback",
client_id: your_client_id,
client_secret: your_client_secret,
};
we use query.stringify() for the data because the content type is application/x-www-form-urlencoded also don't use params since its a post request
axios
.post(
"https://accounts.spotify.com/api/token",
querystring.stringify(data),
headers
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
This works for me:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(this.clientId + ':' + this.clientSecret).toString('base64'),
};
this.http.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
{ headers },
).subscribe(data => {
console.log(data);
});
I have the same issue, and it's resolved with stringfying request body data
const requestAccessToken = ({
code,
grantType = "authorization_code",
redirectUri = `${APP_BASE_URL}/callback`,
}) => {
const data = qs.stringify({ //query-string library
code,
grant_type: "client_credentials",
redirect_uri: redirectUri,
});
return axios.post(
[SPOTIFY_ACCOUNTS_BASE_URL, SPOTIFY_ACCOUNTS_TOKEN_URI].join(""),
data,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`,
).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
};
Have you traced the message and verified that the request body is definitely as expected? Your OAuth fields look totally correct so I suspect this could just be an axios syntax issue.
I could be wrong but should the 'params' field be called 'data' instead, as in this class of mine.

TypeError: Failed to fetch - react js

I want to send data to my sever but I got this error:
TypeError: Failed to fetch
my codes:
function login(username, password) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json','charset':'utf-8' },
body: JSON.stringify({ 'username':username , 'password':password })
};
console.log(requestOptions);
return fetch(BASE_URL+serverConstants.LOGIN_POST_REQUEST, requestOptions)
.then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
})
.then(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
}
return user;
});
}
but I tested it on postman I got correct response.
Your preflight request is failing. Allow cross origin for the API you are hitting:
In node you do it like this,
res.header("Access-Control-Allow-Origin", "*");
Hope this helps
If you want to send values to your sever like form-data from postman sowftware you should use formData (your don't need to import FormData from any class):
var formData = new FormData()
formData.append('yourKey, 'yourValue');
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};
return fetch('Your url', options)
.then(checkStatus)
.then(parseJSON);
of course from your server-side you should enable CORS. CORS depending on your language server-side is different.

Categories