React Native fbsdk:如何通过服务器将短时访问令牌转为长时令牌?
Hey there! I see you've successfully grabbed an access token using react-native-fbsdk, but you're unsure if it's short or long-lived. Let's walk through how to convert that short-lived token to a longer-lasting one using your server—this matters because client-side tokens are almost always short-lived (valid for ~1-2 hours), while long-lived ones stick around for up to 60 days.
Step 1: Gather Required Parameters
First, pull these values from your Facebook Developer Dashboard:
client_id: Your Facebook App IDclient_secret: Your App's Secret (keep this private—never expose it to the client side!)fb_exchange_token: The short-lived access token you got viaAccessToken.getCurrentAccessToken()in your React Native appgrant_type: Fixed valuefb_exchange_token
Step 2: Send a GET Request to Facebook's Token Exchange Endpoint
You’ll need to make an HTTP GET request to Facebook’s Graph API endpoint. Use the latest API version (e.g., v18.0 or newer) for best compatibility.
Example with curl:
curl -i "https://graph.facebook.com/v18.0/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=fb_exchange_token&fb_exchange_token=YOUR_SHORT_LIVED_TOKEN"
Example with Node.js (using axios):
const axios = require('axios'); async function exchangeShortLivedToken() { try { const response = await axios.get('https://graph.facebook.com/v18.0/oauth/access_token', { params: { client_id: 'YOUR_APP_ID', client_secret: 'YOUR_APP_SECRET', grant_type: 'fb_exchange_token', fb_exchange_token: 'THE_SHORT_LIVED_TOKEN_FROM_CLIENT' } }); // Extract the long-lived token and its expiry const longLivedToken = response.data.access_token; const expiresInSeconds = response.data.expires_in; // ~5184000 seconds = 60 days console.log('Long-lived Access Token:', longLivedToken); console.log('Token Expiry (seconds):', expiresInSeconds); } catch (error) { console.error('Failed to exchange token:', error.response?.data || error.message); } } exchangeShortLivedToken();
Step 3: Handle the Response
A successful response will return a JSON object like this:
{ "access_token": "YOUR_LONG_LIVED_TOKEN", "token_type": "bearer", "expires_in": 5184000 }
Key Reminders
- Never run this client-side: Your
client_secretmust stay on the server to avoid unauthorized access to your Facebook app. - Refresh expired long-lived tokens: When a long-lived token expires, you can use it to get a new one (same endpoint—just pass the expired long-lived token as
fb_exchange_token). - Verify token details: To check if a token is short or long-lived, use the
debug_tokenendpoint. Send a GET request withclient_id,client_secret, andinput_token(the token you want to verify) tohttps://graph.facebook.com/v18.0/debug_token.
内容的提问来源于stack exchange,提问作者Radhouane BENBRAHIM

