class CapitalCheckInOAuth2 {
constructor(clientId, clientSecret, redirectUri) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.redirectUri = redirectUri;
this.baseURL = 'https://api.capitalcheckin.app';
}
// Paso 1: Redirigir al usuario para autorización
initiateAuthorization(scope = 'read:profile', state = null) {
const params = new URLSearchParams({
client_id: this.clientId,
redirect_uri: this.redirectUri,
response_type: 'code',
scope: scope
});
if (state) {
params.append('state', state);
}
const authUrl = `${this.baseURL}/oauth/authorize?${params.toString()}`;
window.location.href = authUrl;
}
// Paso 2: Intercambiar código por token
async exchangeCodeForToken(code) {
const response = await fetch(`${this.baseURL}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
grant_type: 'authorization_code',
client_id: this.clientId,
client_secret: this.clientSecret,
code: code,
redirect_uri: this.redirectUri
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Token exchange failed');
}
return response.json();
}
// Paso 3: Usar el token para acceder a la API
async makeAuthenticatedRequest(endpoint, token) {
const response = await fetch(`${this.baseURL}${endpoint}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Request failed');
}
return response.json();
}
// Paso 4: Renovar token usando refresh token
async refreshToken(refreshToken) {
const response = await fetch(`${this.baseURL}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
grant_type: 'refresh_token',
client_id: this.clientId,
client_secret: this.clientSecret,
refresh_token: refreshToken
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Token refresh failed');
}
return response.json();
}
}
// Uso
const oauth2 = new CapitalCheckInOAuth2(
'your_client_id',
'your_client_secret',
'https://your-app.com/callback'
);
// Iniciar flujo de autorización
oauth2.initiateAuthorization('read:profile read:groups', 'random_state');
// En la página de callback
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
if (code) {
try {
const tokenResponse = await oauth2.exchangeCodeForToken(code);
console.log('Token obtenido:', tokenResponse);
// Usar el token para acceder a la API
const profile = await oauth2.makeAuthenticatedRequest(
'/v1/users/profile',
tokenResponse.access_token
);
console.log('Perfil:', profile);
} catch (error) {
console.error('Error:', error);
}
}