Hello there! I am trying to use the Patreon OAuth2 feature to let people on my website login with their Patreon. But for some weird reason I always get the “invalid grant” error when I try fetching for the access_token… This is my code:
(Client-side)
document.getElementById('authorize').addEventListener('click', function() {
// Redirect user to Patreon for authorization
window.location.href = 'https://www.patreon.com/oauth2/authorize?response_type=code&client_id=3bCp2Wk8hmEylEGex9yftIgJs7vSZAmNUjxRCXk9SRxlMV4vkvtnXGWR-Y6Bh5r2&redirect_uri=http://localhost:5500';
});
// After authorization, Patreon will redirect back to your site with a code parameter in the URL
// Extract the code and exchange it for an access token
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
// Make an API call to exchange the code for an access token
fetch('http://localhost:2000/getdata', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: `{"code": "${code}"}`
})
console.log(code)
}
(Server-side)
const express = require('express');
const app = express();
const cors = require('cors');
const fetch = require('node-fetch');
const port = 2000;
app.use(cors())
app.use(express.json())
app.listen(port, () => {
console.log(`Server is online and running!`)
})
app.post('/getdata', async (req, res) => {
const code = req.body.code;
console.log(req.body)
fetch('https://www.patreon.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `code=${code}&grant_type=authorization_code&client_id=3bCp2Wk8hmEylEGex9yftIgJs7vSZAmNUjxRCXk9SRxlMV4vkvtnXGWR-Y6Bh5r2&client_secret=secret&redirect_uri=http://localhost:5500`
})
.then(response => response.json())
.then(data => {
console.log(data);
const accessToken = data.access_token;
// Now that we have the access token, make an API call to check if the user is a subscriber
fetch('https://www.patreon.com/api/oauth2/api/current_user', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
})
.then(response => response.json())
.then(user => {
console.log(user);
})
.catch(error => {
console.error('Error checking subscription:', error);
});
})
.catch(error => {
console.error('Error exchanging code for access token:', error);
});
})
app.post('/get', async (req, res) => {
console.log(req.body)
})