How to Access the Coinbase API. using OAuth2 | by Jennifer Bland | Jan, 2022

Using OAuth2

Jennifer Bland
Photo by Pierre Portery on Unsplash
npx express-generator -e --view=ejs coinbase-demo
cd coinbase-demo
npm install
npm install axios nodemon qs
"start": "nodemon app.js"
const axios = require('axios'); 
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', function () { 
console.log("Server starting on localhost:" + port);
});
<a href="https://www.coinbase.com/oauth/authorize?response_type=code&client_id=2240e80398486d147c6a3e2e48e63b3d9a562497ad85bcd3300b7dda67eae42d&redirect_uri=http://localhost:3000/callback&state=MY_SECRET_KEY&scope=wallet:user:read,wallet:user:email,wallet:accounts:read,wallet:transactions:read&account=all" class="btn"> Connect with Coinbase </a>
const SECRET = "MY_SECRET_KEY"; 
const REDIRECT_URI = "http://localhost:3000/callback";
const CLIENT_ID = "2240e80398486d147c6a3e2e48e63b3d9a562497ad85bcd3300b7dda67eae42d"; const SCOPE = "wallet:user:read,wallet:user:email,wallet:accounts:read,wallet:transactions:read";
router.get('/', function(req, res, next) { 
res.render('index', {
title: 'Express',
CLIENT_ID: CLIENT_ID,
REDIRECT_URI: REDIRECT_URI,
SECRET: SECRET, SCOPE: SCOPE,
});
});
<a href="https://www.coinbase.com/oauth/authorize?response_type=code&client_id=<%= CLIENT_ID %>&redirect_uri=<%= REDIRECT_URI %>&state=<%= SECRET %>&scope=<%= SCOPE %>&account=all" > Connect with Coinbase </a>
.btn { 
width: 100%;
background: #2364d2;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: 500;
padding: 8px 15px;
font-family: "Source Sans Pro", sans-serif;
color: #fff;
cursor: pointer;
text-decoration: none;
}
// User gets redirected to this endpoint on successful login router.get("/callback", async (req, res) => { 
const { code, state } = req.query;
if (state === SECRET) {
const data = qs.stringify({
'grant_type': 'authorization_code',
'code': code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI
});
const config = {
method: 'post',
url: 'https://api.coinbase.com/oauth/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data
};
try {
const response = await axios(config);
res.send({ response: response?.data });
} catch (e) {
console.log("Could not trade code for tokens", e)
}
}
});
const qs = require('qs');
let axios = require('axios');
res.send({ response: response?.data });

Leave a Comment