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

如何将Facebook授权码转换为Access Token?(NestJs环境)

如何用NestJS将Facebook授权码兑换为长期Access Token(用于Instagram企业账号)

1. 授权码兑换短期Access Token

你需要调用Facebook的/oauth/access_token端点,通过POST请求完成兑换,必填参数如下:

  • client_id: 你的Instagram应用ID(即配置中的INSTAGRAM_CID)
  • client_secret: 你的应用密钥
  • redirect_uri: 必须和生成授权链接时使用的redirect_uri完全一致
  • code: 回调接口获取到的授权码
  • grant_type: 固定值authorization_code

2. NestJS实现代码示例

在你的NestJS服务中,可使用内置HttpService发送请求:

import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class InstagramAuthService {
  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {}

  async exchangeCodeForShortToken(code: string): Promise<any> {
    const clientId = this.configService.getOrThrow('INSTAGRAM_CID');
    const clientSecret = this.configService.getOrThrow('INSTAGRAM_CLIENT_SECRET');
    const redirectUri = `${this.configService.get('BASE_URL')}/instagram/oauth/callback`;

    const params = new URLSearchParams();
    params.append('client_id', clientId);
    params.append('client_secret', clientSecret);
    params.append('redirect_uri', redirectUri);
    params.append('code', code);
    params.append('grant_type', 'authorization_code');

    const response = await firstValueFrom(
      this.httpService.post('https://graph.facebook.com/v18.0/oauth/access_token', params),
    );
    return response.data; // 返回包含短期access_token、token_type、expires_in的对象
  }
}

3. 短期Token转长期Access Token

拿到短期token后,调用同一个端点将其兑换为有效期60天的长期token,参数调整为:

  • grant_type: 固定值fb_exchange_token
  • client_id: 应用ID
  • client_secret: 应用密钥
  • fb_exchange_token: 刚获取的短期access_token

对应的NestJS代码示例:

async exchangeShortTokenForLongToken(shortToken: string): Promise<any> {
  const clientId = this.configService.getOrThrow('INSTAGRAM_CID');
  const clientSecret = this.configService.getOrThrow('INSTAGRAM_CLIENT_SECRET');

  const params = new URLSearchParams();
  params.append('grant_type', 'fb_exchange_token');
  params.append('client_id', clientId);
  params.append('client_secret', clientSecret);
  params.append('fb_exchange_token', shortToken);

  const response = await firstValueFrom(
    this.httpService.post('https://graph.facebook.com/v18.0/oauth/access_token', params),
  );
  return response.data; // 返回包含长期access_token、token_type、expires_in的对象
}

关键注意事项

  • redirect_uri必须与授权链接中的完全一致,包括协议(http/https)和路径
  • 应用密钥(client_secret)需妥善保管,禁止暴露在前端或日志中
  • API版本号(示例中用v18.0)建议使用Facebook当前支持的最新稳定版本
  • 长期token到期前,可重复调用兑换接口续期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:33:25