// This function constructs the authorization URL and redirects the user.function redirectToXAuth() { const params = new URLSearchParams({ response_type: 'code', client_id: 'YOUR_X_CLIENT_ID', // Replace with your X Client ID redirect_uri: 'YOUR_REDIRECT_URI', // Your callback URL scope: 'users.read email.read tweet.read', // Required scopes state: 'state', // A random string for security code_challenge: 'challenge', // A PKCE code challenge code_challenge_method: 'plain', // Use 'S256' in production }); window.location.assign(`https://x.com/i/oauth2/authorize?${params.toString()}`);}
// On your callback page, handle the redirect from X and get the access token.async function handleXCallback() { const params = new URLSearchParams(window.location.search); const code = params.get('code'); if (code) { try { // Exchange the authorization code for an access token. // Instead of calling X directly, we use the Sequence proxy. const tokenUrl = 'https://xproxy.sequence.xyz/api.x.com/2/oauth2/token'; const tokenResponse = await fetch(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ code, grant_type: 'authorization_code', client_id: 'YOUR_X_CLIENT_ID', // Replace with your X Client ID redirect_uri: 'YOUR_REDIRECT_URI', // Must match the one in Step 1 code_verifier: 'challenge', // The PKCE code verifier }), }); const { access_token } = await tokenResponse.json(); if (!access_token) { throw new Error('Failed to obtain access token'); } // Now you have the access token. You can pass it to the signIn method. console.log('Access Token:', access_token); return access_token; } catch (error) { console.error('X sign-in failed:', error); } }}// Call this function when your callback page loadshandleXCallback();