Glowb Dev Docs
SaaS API

Instagram OAuth API

Instagram Business 계정 연동 API (Facebook Graph API 기반)

Instagram OAuth API

Instagram Business 계정을 연동하기 위한 OAuth API입니다. Facebook Graph API를 통해 Instagram Business Account에 접근합니다.

Base URL: /ai/instagram

인증 정보

항목
인증 필요일부 필요
인증 방식JWT Bearer Token

OAuth 연동 플로우

Instagram 연동은 프론트엔드 Callback 방식을 사용합니다.

1. OAuth URL 요청

프론트엔드에서 백엔드 API를 호출하여 Facebook OAuth URL을 받습니다.

GET /ai/instagram/oauth/url?memberId=user123

응답:

{
  "status": 200,
  "message": "OAuth URL 생성 완료",
  "data": "https://www.facebook.com/v18.0/dialog/oauth?client_id=xxx&redirect_uri=xxx&state=xxx&scope=xxx"
}

2. Facebook 인증 페이지로 리다이렉트

프론트엔드에서 받은 OAuth URL로 사용자를 리다이렉트합니다.

window.location.href = oauthUrl;

사용자는 Facebook 로그인 후 Instagram Business 계정 접근 권한을 허용합니다.

3. 프론트엔드 Callback 수신

Facebook이 사용자를 프론트엔드 callback URL로 리다이렉트합니다.

https://your-frontend.com/instagram/callback?code=AUTH_CODE&state=STATE_VALUE
파라미터설명
codeAuthorization code (토큰 교환용)
stateCSRF 방지용 state 값 (memberId 포함)

4. 백엔드에 code 전달

프론트엔드가 받은 code와 state를 백엔드 API로 전달합니다.

POST /ai/instagram/oauth/connect?code=AUTH_CODE&state=STATE_VALUE

응답:

{
  "status": 200,
  "message": "Instagram 계정이 연결되었습니다.",
  "data": [
    {
      "accountId": 1,
      "username": "my_instagram",
      "name": "My Instagram Account",
      "profilePictureUrl": "https://...",
      "followersCount": 10000,
      "connectionStatus": "CONNECTED"
    }
  ]
}

플로우 다이어그램

┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   프론트    │     │   백엔드    │     │  Facebook   │     │  Instagram  │
└──────┬──────┘     └──────┬──────┘     └──────┬──────┘     └──────┬──────┘
       │                   │                   │                   │
       │ 1. GET /oauth/url │                   │                   │
       │──────────────────>│                   │                   │
       │                   │                   │                   │
       │   OAuth URL 반환  │                   │                   │
       │<──────────────────│                   │                   │
       │                   │                   │                   │
       │ 2. 리다이렉트     │                   │                   │
       │───────────────────────────────────────>                   │
       │                   │                   │                   │
       │                   │    사용자 인증    │                   │
       │                   │    권한 허용      │                   │
       │                   │                   │                   │
       │ 3. Callback (code, state)             │                   │
       │<──────────────────────────────────────│                   │
       │                   │                   │                   │
       │ 4. POST /oauth/connect                │                   │
       │──────────────────>│                   │                   │
       │                   │                   │                   │
       │                   │ 5. Token 교환     │                   │
       │                   │──────────────────>│                   │
       │                   │                   │                   │
       │                   │   Access Token    │                   │
       │                   │<──────────────────│                   │
       │                   │                   │                   │
       │                   │ 6. 프로필 조회    │                   │
       │                   │───────────────────────────────────────>
       │                   │                   │                   │
       │                   │   Instagram 정보  │                   │
       │                   │<──────────────────────────────────────│
       │                   │                   │                   │
       │  연결된 계정 반환 │                   │                   │
       │<──────────────────│                   │                   │
       │                   │                   │                   │

엔드포인트 목록

메서드경로설명인증
GET/ai/instagram/oauth/urlOAuth URL 조회불필요
POST/ai/instagram/oauth/connectInstagram 계정 연결불필요
GET/ai/instagram/accounts연결된 계정 목록 조회불필요
DELETE/ai/instagram/accounts/{accountNo}계정 연결 해제불필요
POST/ai/instagram/accounts/{accountNo}/sync계정 정보 동기화불필요

API 상세

OAuth URL 조회

Instagram 연결을 위한 Facebook OAuth URL을 생성합니다.

HTTP 요청

GET /ai/instagram/oauth/url

Query Parameters

파라미터타입필수설명
memberIdstring회원 ID

응답

성공 응답 (200 OK)

{
  "status": 200,
  "code": null,
  "message": "OAuth URL 생성 완료",
  "data": "https://www.facebook.com/v18.0/dialog/oauth?client_id=123456&redirect_uri=https://your-frontend.com/instagram/callback&state=base64encodedstate&scope=instagram_basic,instagram_manage_insights,pages_show_list,pages_read_engagement,business_management&response_type=code"
}

Instagram 계정 연결

프론트엔드에서 받은 authorization code로 Instagram 계정을 연결합니다.

HTTP 요청

POST /ai/instagram/oauth/connect

Query Parameters

파라미터타입필수설명
codestringFacebook에서 받은 authorization code
statestringOAuth URL 생성 시 포함된 state 값

응답

성공 응답 (200 OK)

{
  "status": 200,
  "code": null,
  "message": "Instagram 계정이 연결되었습니다.",
  "data": [
    {
      "accountId": 1,
      "platform": 1,
      "platformUserId": "17841400000000000",
      "username": "my_instagram_account",
      "name": "My Instagram",
      "profilePictureUrl": "https://scontent.cdninstagram.com/...",
      "biography": "인스타그램 소개글",
      "website": "https://mywebsite.com",
      "followersCount": 15000,
      "followingCount": 500,
      "mediaCount": 120,
      "connectionStatus": "CONNECTED",
      "priceTier": "B",
      "price": 150000
    }
  ]
}

에러 응답

상태 코드에러 코드설명
400INVALID_REQUESTcode 또는 state 누락
500CONNECTION_FAILED연결 실패 (토큰 교환 오류 등)

연결된 계정 목록 조회

회원에게 연결된 Instagram 계정 목록을 조회합니다.

HTTP 요청

GET /ai/instagram/accounts

Query Parameters

파라미터타입필수설명
memberIdstring회원 ID

응답

성공 응답 (200 OK)

{
  "status": 200,
  "code": null,
  "message": "연결된 계정 조회 완료",
  "data": [
    {
      "accountId": 1,
      "platform": 1,
      "platformUserId": "17841400000000000",
      "username": "my_instagram_account",
      "name": "My Instagram",
      "profilePictureUrl": "https://scontent.cdninstagram.com/...",
      "followersCount": 15000,
      "connectionStatus": "CONNECTED",
      "priceTier": "B",
      "price": 150000
    }
  ]
}

계정 연결 해제

지정된 Instagram 계정의 연결을 해제합니다.

HTTP 요청

DELETE /ai/instagram/accounts/{accountNo}

Path Parameters

파라미터타입필수설명
accountNolongInstagram 계정 번호

Query Parameters

파라미터타입필수설명
memberIdstring회원 ID

응답

성공 응답 (200 OK)

{
  "status": 200,
  "code": null,
  "message": "Instagram 계정 연결이 해제되었습니다.",
  "data": null
}

계정 정보 동기화

Instagram 계정의 프로필 정보를 최신으로 업데이트합니다.

HTTP 요청

POST /ai/instagram/accounts/{accountNo}/sync

Path Parameters

파라미터타입필수설명
accountNolongInstagram 계정 번호

Query Parameters

파라미터타입필수설명
memberIdstring회원 ID

응답

성공 응답 (200 OK)

{
  "status": 200,
  "code": null,
  "message": "동기화 완료",
  "data": {
    "accountId": 1,
    "username": "my_instagram_account",
    "followersCount": 15500,
    "connectionStatus": "CONNECTED"
  }
}

Response 스키마

SocialAccountDto

필드명타입설명
accountIdlong계정 ID
platformint플랫폼 (1: Instagram)
platformUserIdstringInstagram Business Account ID
usernamestringInstagram 사용자명 (@없이)
namestring계정 이름
profilePictureUrlstring프로필 이미지 URL
biographystring소개글
websitestring웹사이트 URL
followersCountlong팔로워 수
followingCountlong팔로잉 수
mediaCountlong게시물 수
connectionStatusSocialConnectionStatus연결 상태
priceTierstring가격 티어 (N/S/A/B/C 등)
priceint산정 가격

SocialConnectionStatus

설명
CONNECTED연결됨
DISCONNECTED연결 해제됨
EXPIRED토큰 만료
ERROR오류

설정 (application.yml)

Instagram OAuth를 사용하려면 다음 설정이 필요합니다:

sns:
  instagram:
    client:
      id: YOUR_FACEBOOK_APP_ID        # Facebook App ID
      secret: YOUR_FACEBOOK_APP_SECRET # Facebook App Secret
    callback:
      url: https://your-frontend.com/instagram/callback  # 프론트엔드 callback URL

중요: callback.url프론트엔드 URL이어야 합니다. 이 URL을 Facebook Developer Console의 "Valid OAuth Redirect URIs"에도 동일하게 등록해야 합니다.


Facebook Developer Console 설정

1. 앱 생성

Facebook Developer Console에서 Business 타입 앱을 생성합니다.

2. 제품 추가

  • Facebook 로그인
  • Instagram Graph API

3. OAuth 설정

Facebook 로그인 > 설정에서 다음을 설정:

  • Valid OAuth Redirect URIs: 프론트엔드 callback URL 등록
    • 개발: http://localhost:3000/instagram/callback
    • 운영: https://your-frontend.com/instagram/callback

4. 권한 요청

다음 권한이 필요합니다:

권한설명
instagram_basicInstagram 기본 정보 접근
instagram_manage_insights인사이트 데이터 접근
pages_show_listFacebook 페이지 목록 조회
pages_read_engagement페이지 참여 데이터 읽기
business_management비즈니스 계정 관리

프론트엔드 구현 예시

React 예시

// 1. OAuth 시작
const startOAuth = async () => {
  const { data } = await api.get('/ai/instagram/oauth/url', {
    params: { memberId: user.id }
  });

  // Facebook으로 리다이렉트
  window.location.href = data.data;
};

// 2. Callback 페이지 (/instagram/callback)
const InstagramCallback = () => {
  const searchParams = useSearchParams();
  const code = searchParams.get('code');
  const state = searchParams.get('state');
  const error = searchParams.get('error');

  useEffect(() => {
    if (error) {
      // 에러 처리 (사용자가 취소한 경우 등)
      alert('Instagram 연결이 취소되었습니다.');
      router.push('/settings');
      return;
    }

    if (code && state) {
      connectInstagram(code, state);
    }
  }, [code, state, error]);

  const connectInstagram = async (code: string, state: string) => {
    try {
      const { data } = await api.post('/ai/instagram/oauth/connect', null, {
        params: { code, state }
      });

      // 연결 성공
      alert(`${data.data.length}개의 Instagram 계정이 연결되었습니다.`);
      router.push('/settings/instagram');
    } catch (error) {
      alert('Instagram 연결에 실패했습니다.');
      router.push('/settings');
    }
  };

  return <div>Instagram 연결 중...</div>;
};

에러 처리

OAuth 에러

Facebook OAuth 과정에서 에러가 발생하면 프론트엔드 callback URL에 에러 파라미터가 전달됩니다:

https://your-frontend.com/instagram/callback?error=access_denied&error_description=User%20denied
에러 코드설명
access_denied사용자가 권한 허용을 거부함
invalid_request잘못된 요청

API 에러

상태 코드에러 코드설명해결 방법
400INVALID_REQUEST필수 파라미터 누락code, state 확인
500CONNECTION_FAILED연결 실패재시도 또는 관리자 문의

API 테스트

On this page