You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Facebook Graph API长时访问令牌缺失expires_in字段问题咨询

Facebook长时访问令牌API返回缺失expires_in字段问题解答

问题场景

使用以下Python函数获取Facebook长时访问令牌时,原本正常返回access_token和expires_in字段,现在仅返回access_token和值为bearer的token_type字段,缺失expires_in:

def get_long_lived_access_token(app_id, app_secret, user_access_token):
    url = f"https://graph.facebook.com/{API_VERSION}/oauth/access_token"
    params = {
        'grant_type': 'fb_exchange_token',
        'client_id': app_id,
        'client_secret': app_secret,
        'fb_exchange_token': user_access_token
    }
    response = requests.get(url, params=params)
    data = response.json()
    if 'access_token' in data:
        expires_in = data.get('expires_in')
        expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
        return data['access_token'], expires_at
    else:
        raise Exception(f"Error obtaining long-lived access token: {data}")

解答

这种情况是Meta Graph API的预期变更,并非未公示的改动:

  • 对于使用v14.0及以上API版本、且通过应用审核的应用,长时用户访问令牌的有效期统一调整为60天,API不再返回expires_in字段
  • 旧版API(v13.0及更早)可能仍保留expires_in返回,但Meta已逐步淘汰旧版API的相关特性,建议尽快升级到最新API版本

修复后的函数示例

可以直接按固定60天有效期处理,兼容两种返回情况:

from datetime import datetime, timedelta
import requests

def get_long_lived_access_token(app_id, app_secret, user_access_token, API_VERSION):
    url = f"https://graph.facebook.com/{API_VERSION}/oauth/access_token"
    params = {
        'grant_type': 'fb_exchange_token',
        'client_id': app_id,
        'client_secret': app_secret,
        'fb_exchange_token': user_access_token
    }
    response = requests.get(url, params=params)
    data = response.json()
    if 'access_token' in data:
        # 无expires_in时默认按60天计算
        expires_in = data.get('expires_in', 60 * 24 * 3600)
        expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
        return data['access_token'], expires_at
    else:
        raise Exception(f"Error obtaining long-lived access token: {data}")

额外验证方式

若需要确认令牌的实际有效期,可调用/debug_token端点,传入目标令牌及应用凭证,该端点会返回明确的expires_at字段。

内容的提问来源于stack exchange,提问作者cycero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:17:40