Skip to content
COMMUNITY HUB2026.11.26
디자인원엑스COMMUNITY
Login Sign up Write
LatestDXCMS 10.4.102026.06.15 · D+164일 (5개월)
  • 203Download
  • 1Theme
  • 84Plugins
  • 29Skin

DX API Plugin - DXCMS REST API — React Native / 웹앱 / 외부 시스템 연동

D DX관리자
2026.07.23 03:29(edited) 101 0 1


목차

1. 개요 및 특징
2. Install 방법
3. 인증 Method (JWT Bearer Token)
4. 응답 표준 형식
5. All 엔드포인트 List (22 )
6. 인증 API — /api/v1/auth/*
7. Boards/Posts API — /api/v1/boards/*
8. Comments API — /api/v1/posts/*
9. Members API — /api/v1/members/*
10. File 업로드 API — /api/v1/upload/*
11. Admin 화면 사용법
12. 테스트 방법 (테스터 / cURL / Postman / React Native)
13. 다른 플러그인에서 API 확장하기
14. Error 코드 List
15. Security 권장 사항
 
 

1. 개요 및 특징

DX API 플러그인은 DXCMS를 완전한 REST API 서버로 전환합니다. React Native, Flutter, Next.js, Vue 등 모든 프론트엔드와 외부 시스템에서 JSON으로 DXCMS 데이터를 활용할 수 있습니다.
 

주요 특징

•  Laravel Style RESTful API — 동일한 URL 구조, 동일한 응답 형식
•  JWT-like Bearer Token 인증 — Access Token(1Time) + Refresh Token(30day(s)) + 토큰 로테이션
•  기존 DXCMS 코드 완전 비침습 — 웹 기능 그대로 동작
•  Plugins Deactivate 시 API 완전 종료 — Security 제어 Possible
•  훅 기반 확장 — 다른 플러그인이 엔드포인트 추가 Possible (dx_api_endpoints)
•  CORS Automatic 처리 — React Native, 웹앱 Immediately 연동
•  Rate Limiting — Login 분당 10times, Sign up 분당 5times 제한
•  File 업로드 — Image/File 분리, Boards Settings Automatic Apply, 2단계 연결 Method
•  PHP 5.6+ 호환 — 외부 라이브러리 None

 

Categories 엔드포인트 수 주요 기능
인증 (Auth) 5 Login, Sign up, Log out, 토큰 갱신, 내 정보
Boards/Posts 7 List, 상세, 작성(file_ids 포함), Edit, Delete
Comments 3 List, 작성, Delete
Members 3 Profile, 정보 Edit, Password Change
File 업로드 4 Image 업로드, File 업로드, Posts 연결, Delete
 
 
 

2. Install 방법

File 구조

plugins/
  dx-api/
    manifest.php
    plugin.php              ← 훅 등록, DB 테이블 설치
    admin/
      index.php             ← 관리자 화면 (대시보드 + 테스터)
    core/
      Request.php           ← 입력 처리 (Laravel Request 유사)
      Response.php          ← JSON 응답 표준화
      Router.php            ← 라우팅 엔진 + 미들웨어
      Token.php             ← JWT 토큰 발급/검증
    endpoints/
      auth.php              ← 인증 엔드포인트
      boards.php            ← 게시판/게시글 엔드포인트
      comments.php          ← 댓글 엔드포인트
      members.php           ← 회원 엔드포인트
      upload.php            ← 파일 업로드 엔드포인트

admin/
  dx-api/
    index.php               ← 관리자 라우팅 진입점

core/api/
  v1.php                    ← DXCMS dispatchApi() 진입점
 

Install 절차

1.  plugins/dx-api/ 폴더를 DXCMS 루트의 plugins/ 폴더에 Copy
2.  admin/dx-api/index.php 를 DXCMS 루트의 admin/dx-api/ 폴더에 Copy
3.  core/api/v1.php 를 DXCMS 루트의 core/api/ 폴더에 Copy
4.  Admin → Plugins → DX API → Activate
5.  Activate 시 api_tokens 테이블 Automatic 생성
6.  Admin → Sites → DX API 메뉴 OK
 
admin/index.php 사이드바에 DX API 메뉴가 없으면: Sites Settings 바로 Below, adm_nav('DX API', '/admin/dx-api', ...) 한 Row 추가 Required
core/api/v1.php 복사를 빠뜨리면 /api/v1/* 모든 요청이 404 반환
 
 

3. 인증 Method (JWT Bearer Token)

DX API는 세션/쿠키 대신 Bearer Token 방식을 사용합니다. 인증이 필요한 모든 요청에 Authorization 헤더를 포함해야 합니다.
 

토큰 Type

토큰 유효시간 Save Location 용도
Access Token 1Time (3600초) 앱 메모리 / SecureStore API Request 인증 헤더에 Enabled
Refresh Token 30day(s) 앱 SecureStore / Keychain Access Token 만료 시 갱신
 

인증 흐름

1. 로그인
   POST /api/v1/auth/login
   → { access_token, refresh_token, expires_in: 3600, user: {...} }

2. API 요청 시 헤더 포함
   Authorization: Bearer {access_token}

3. Access Token 만료(1시간) 후 갱신
   POST /api/v1/auth/refresh
   Body: { "refresh_token": "..." }
   → 새 access_token + 새 refresh_token 발급 (기존 토큰 파기)

4. 로그아웃
   POST /api/v1/auth/logout
   → DB의 Refresh Token 파기, 모든 기기 로그아웃
토큰 로테이션: Refresh Token Enabled 시 Immediately 파기되고 새 토큰 발급. 탈취 시 재사용 Not possible.
IIS 환경: Authorization 헤더가 전달되지 않으면 web.config에 requestFiltering Settings Required
 
 

4. 응답 표준 형식

Success 응답

{
  "success": true,
  "message": "성공 메시지",     // 선택
  "data": { ... }              // 단건: object / 목록: array
}


페이지네이션 응답

{
  "success": true,
  "data": [ ... ],
  "meta": {
    "total": 100,              // 전체 건수
    "page": 1,                 // 현재 페이지
    "per_page": 20,            // 페이지당 건수
    "last_page": 5,            // 마지막 페이지
    "has_more": true           // 다음 페이지 존재 여부
  }
}
 

에러 응답

{
  "success": false,
  "message": "에러 메시지",
  "code": "UNAUTHORIZED",       // 머신리더블 코드
  "errors": {                  // Validation 오류 시만
    "login_id": "아이디를 입력하세요.",
    "password": "비밀번호를 입력하세요."
  }
}
 

HTTP Status 코드

코드 의미 발생 상황
200 OK 정상 처리
201 Created Posts/Comments 작성, File 업로드, Sign up Success
400 Bad Request 잘못된 Request, 업로드 Error
401 Unauthorized 토큰 None/만료, Login Failed
403 Forbidden 권한 None, File 업로드 비허용 Boards
404 Not Found Boards/Posts/File None
422 Validation Error Required 입력값 누락, 형식 Error
429 Too Many Requests Rate Limit 초과
500 Internal Server Error 서버/DB Error
 
 
 

5. All 엔드포인트 List (22 )

메서드 엔드포인트 Description 인증
POST /api/v1/auth/login Login → 토큰 발급  
POST /api/v1/auth/register Sign up → Automatic Login  
POST /api/v1/auth/logout Log out → 토큰 파기 🔒
POST /api/v1/auth/refresh Access Token 갱신  
GET /api/v1/auth/me 내 정보 Views 🔒
GET /api/v1/boards Boards List  
GET /api/v1/boards/:board_key Boards 정보  
GET /api/v1/boards/:board_key/posts Posts List (페이지네이션) 권한별
GET /api/v1/boards/:board_key/posts/:id Posts 상세 + Attachments 권한별
POST /api/v1/boards/:board_key/posts Posts 작성 (file_ids 포함) 🔒
PUT /api/v1/boards/:board_key/posts/:id Posts Edit 🔒
DELETE /api/v1/boards/:board_key/posts/:id Posts Delete (소프트) 🔒
GET /api/v1/posts/:post_id/comments Comments List  
POST /api/v1/posts/:post_id/comments Comments 작성 🔒
DELETE /api/v1/posts/:post_id/comments/:id Comments Delete 🔒
GET /api/v1/members/:login_id Members Public Profile  
PUT /api/v1/members/me 내 정보 Edit 🔒
PUT /api/v1/members/me/password Password Change 🔒
POST /api/v1/upload/image Image 업로드 (multipart) 🔒
POST /api/v1/upload/file File 업로드 (multipart) 🔒
POST /api/v1/upload/attach File-Posts 연결 🔒
DELETE /api/v1/upload/:file_id 임시 File Delete 🔒
 
 
 

6. 인증 API — /api/v1/auth/*

6-1. Login

 POST   /api/v1/auth/login
Username 또는 이메일로 Login. Success 시 Access Token + Refresh Token 발급.

파라미터
Name Location Required Description
login_id Body Required Username 또는 Email
password Body Required Password

Request Body (JSON)
{"login_id": "admin","password": "비밀번호"}

Response
{"success": true,"data": {
  "token_type": "Bearer",
  "access_token": "eyJ...",
  "refresh_token": "a1b2c3...",
  "expires_in": 3600,
  "user": { "id": "...", "login_id": "admin", "name": "관리자", "role": "admin", "level": "9", "point": "500" }
}}
rate:10 — IP당 분당 10times 초과 시 429 반환
 

6-2. Sign up

 POST   /api/v1/auth/register
신규 Sign up. Success 시 Automatic 로그인되어 토큰 Immediately 반환 (HTTP 201).

파라미터
Name Location Required Description
login_id Body Required Username (4자 이상)
password Body Required Password (6자 이상)
name Body Required Name/Nickname
email Body Select Email


Request Body (JSON)
{"login_id": "newuser","password": "pass1234","name": "홍길동","email": "user@email.com"}

Response
{"success": true,"message": "회원가입이 완료되었습니다.","data": { "token_type": "Bearer", "access_token": "...", ... }}
rate:5 — IP당 분당 5times 초과 시 429 반환
site_settings 's join_level=0 이면 Sign-up Not possible (403)
 

6-3. Log out

 POST   /api/v1/auth/logout
Current 기기의 Refresh Token 파기. 이후 토큰 갱신 Not possible.
🔒 Authorization: Bearer {access_token} 헤더 Required

Response
{"success": true,"message": "로그아웃 되었습니다."}
 

6-4. Access Token 갱신

 POST   /api/v1/auth/refresh
Refresh Token으로 새 Access Token 발급. 기존 Refresh Token은 Immediately 파기되고 새 토큰 발급 (토큰 로테이션).

파라미터
Name Location Required Description
refresh_token Body Required Login 시 발급된 refresh_token


Request Body (JSON)
{"refresh_token": "a1b2c3..."}

Response
{"success": true,"data": {"token_type": "Bearer","access_token": "eyJ...(새)","refresh_token": "d4e5f6...(새)","expires_in": 3600}}
기존 refresh_token은 Immediately 폐기됨. 새로 발급된 토큰만 유효.
 

6-5. 내 정보 Views

 GET   /api/v1/auth/me
Current 로그인한 사용자 정보 반환. Password 등 민감 정보는 제외.
🔒 Authorization: Bearer {access_token} 헤더 Required

Response
{"success": true,"data": {"id": "...","login_id": "admin","name": "관리자","email": "admin@example.com","role": "admin","level": "9","point": "500","profile_img": null}}
 
 
 

7. Boards/Posts API — /api/v1/boards/*

7-1. Boards List

 GET   /api/v1/boards
활성화된 Boards All List 반환.

Response
{"success": true,"data": [{"id":"1","board_name":"자유게시판","board_key":"free","board_type":"normal","description":"...","read_level":"0","write_level":"1"},...]}
 

7-2. Posts List

 GET   /api/v1/boards/:board_key/posts
Posts List 반환. 페이지네이션, Search, Categories 필터 지원.

파라미터
Name Location Required Description
board_key URL Required Boards 키 (예: free)
page Query Select Page No. (Default: 1)
per_page Query Select 페이지당 건수 (Default: 20, 최대: 100)
q Query Select Search term (Title+Content)
category Query Select Categories 필터


Response
{"success": true,"data": [{"id":"...","title":"제목","category":"공지","view_count":"150","like_count":"12","comment_count":"5","thumbnail":"...","author_name":"홍길동","author_id":"hong","excerpt":"내용 미리보기...","created_at":"2026-07-22 09:00:00"}],"meta": {"total": 100,"page": 1,"per_page": 20,"last_page": 5,"has_more": true}}
Boards read_level에 따라 비로그인 접근 제한 Possible
 

7-3. Posts 상세

 GET   /api/v1/boards/:board_key/posts/:id
Posts 상세 + Attachments List + 여분필드 반환. Views Automatic 증가.

파라미터
Name Location Required Description
board_key URL Required Boards 키
id URL Required Posts ID

Response
{"success": true,"data": {"id":"...","title":"제목","content":"<p>본문HTML</p>","files": [{"id":"1","orig_name":"사진.jpg","file_ext":"jpg","file_size":"102400","url":"https://사이트.com/data/uploads/..."}],"extra_fields": {...},"author_name":"홍길동","created_at":"..."}}
files는 Editor 삽입 Image 제외, 직접 업로드한 파일만 포함
 

7-4. Posts 작성

 POST   /api/v1/boards/:board_key/posts
Posts 작성. 업로드된 파일을 file_ids로 연결 Possible.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
board_key URL Required Boards 키

Request Body (JSON)
{"title": "게시글 제목","content": "<p>본문 HTML</p>","category": "공지","file_ids": [1, 2, 3]}

Response
{"success": true,"message": "게시글이 등록되었습니다.","data": {"id": "1784211424708247","post_id": "1784211424708247"}}
file_ids: /api/v1/upload/* 로 먼저 업로드 후 반환된 file_id 배열 전달
Thumbnail Automatic 생성 (Boards thumb Settings Apply)
 

7-5. Posts Edit

 PUT   /api/v1/boards/:board_key/posts/:id
Posts Edit. 본인 또는 Admins only Possible.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
board_key URL Required Boards 키
id URL Required Posts ID

Request Body (JSON)
{"title": "수정된 제목","content": "<p>수정된 내용</p>","category": "일반"}

Response
{"success": true,"message": "게시글이 수정되었습니다.","data": {"id": "..."}}
변경할 필드만 포함해도 됨 (부분 Edit 지원)
 

7-6. Posts Delete

 DELETE   /api/v1/boards/:board_key/posts/:id
Posts 소프트 Delete (status=0). 본인 또는 Admins only Possible.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
board_key URL Required Boards 키
id URL Required Posts ID

Response
{"success": true,"message": "게시글이 삭제되었습니다."}
소프트 Delete: DB에서 status=0 처리. 실제 데이터는 유지됨.
 
 
 

8. Comments API — /api/v1/posts/*

8-1. Comments List

 GET   /api/v1/posts/:post_id/comments
Comments List. Default 페이지당 50 .

파라미터
Name Location Required Description
post_id URL Required Posts ID
page Query Select Page No.
per_page Query Select 건수 (Default: 50)

Response
{"success": true,"data": [{"id":"...","content":"댓글 내용","parent_id":"0","depth":"0","is_secret":"0","author_name":"홍길동","author_id":"hong","created_at":"..."}],"meta": {"total": 30,"page": 1,"per_page": 50}}
parent_id=0: 최상위 Comments / parent_id>0: 대댓글
 

8-2. Comments 작성

 POST   /api/v1/posts/:post_id/comments
Comments 작성. 대댓글 지원.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
post_id URL Required Posts ID

Request Body (JSON)
{"content": "댓글 내용","parent_id": 0}

Response
{"success": true,"message": "댓글이 등록되었습니다.","data": {"id": "..."}}
parent_id: 0=최상위, 부모댓글ID=대댓글
Comments 작성 시 posts.comment_count Automatic 증가
 

8-3. Comments Delete

 DELETE   /api/v1/posts/:post_id/comments/:id
Comments 소프트 Delete. 본인 또는 Admins only Possible.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
post_id URL Required Posts ID
id URL Required Comments ID

Response
{"success": true,"message": "댓글이 삭제되었습니다."}
Delete 시 posts.comment_count Automatic 감소 (최소 0)
 
 
 

9. Members API — /api/v1/members/*

9-1. Members Public Profile

 GET   /api/v1/members/:login_id
Members Public 정보 Views. Password 등 민감 정보 제외.

파라미터
Name Location Required Description
login_id URL Required Members Login Username

Response
{"success": true,"data": {"id":"...","name":"홍길동","login_id":"hong","level":"5","point":"1200","bio":"자기소개","profile_img":null,"join_date":"2026-01-01 00:00:00"}}
 

9-2. 내 정보 Edit

 PUT   /api/v1/members/me
Name, Email Edit. 변경할 항목만 포함.
🔒 Authorization: Bearer {access_token} 헤더 Required

Request Body (JSON)
{"name": "새이름","email": "new@email.com"}

Response
{"success": true,"message": "회원 정보가 수정되었습니다."}
name 또는 email 중 하나 이상 Required
 

9-3. Password Change

 PUT   /api/v1/members/me/password
Password Change. Change Success 시 모든 Device 토큰 파기.
🔒 Authorization: Bearer {access_token} 헤더 Required

Request Body (JSON)
{"current_password": "현재비밀번호","new_password": "새비밀번호"}

Response
{"success": true,"message": "비밀번호가 변경되었습니다. 다시 로그인하세요."}
Password Change 후 모든 기기에서 재로그인 Required (All Refresh Token 파기)
new_password 6자 이상 Required
 
 
 

10. File 업로드 API — /api/v1/upload/*

2단계 방식으로 동작합니다. 먼저 파일을 업로드(file_id 반환)하고, Posts 작성 시 file_ids 배열로 연결합니다.
【업로드 흐름】

1단계: 파일 업로드 (post_id=0으로 임시 저장)
  POST /api/v1/upload/image  또는  POST /api/v1/upload/file
  → { file_id: 42, url: "https://..." }

2단계: 게시글 작성 시 file_ids 포함 (자동 연결)
  POST /api/v1/boards/free/posts
  Body: { "title": "...", "content": "...", "file_ids": [42, 43] }

또는 게시글 작성 후 별도 연결
  POST /api/v1/upload/attach
  Body: { "post_id": "...", "file_ids": [42, 43] }
 

10-1. Image 업로드

 POST   /api/v1/upload/image
Image 파일만 Allow. multipart/form-data Send.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
file Form Required Image File (jpg, jpeg, png, gif, webp, bmp)
board_key Form Required Boards 키 (업로드 권한 및 Thumbnail Settings Apply)

Request Body (JSON)
// multipart/form-data 전송 (JSON 아님)
// React Native FormData 사용

Response
{"success": true,"message": "이미지가 업로드되었습니다.","data": {"file_id": 42,"url": "https://사이트.com/data/uploads/boards/free/20260722_abc123.jpg","save_path": "boards/free/20260722_abc123.jpg","orig_name": "product.jpg","file_size": 102400,"file_ext": "jpg","is_image": true}}
Content-Type: multipart/form-data (JSON 아님)
Boards use_file=0 이면 403 반환
System upload_max_size 초과 시 400 반환
Image getimagesize() 검증 — 위장 File Blocked
Thumbnail Automatic 생성 (Boards thumb Settings Apply)
 

10-2. File 업로드

 POST   /api/v1/upload/file
Image 포함 모든 File. 위험 확장자 Automatic Blocked.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
file Form Required 업로드할 File
board_key Form Required Boards 키

Request Body (JSON)
// multipart/form-data 전송

Response
{"success": true,"data": {"file_id": 43,"url": "https://...","orig_name": "document.pdf","file_ext": "pdf","is_image": false,...}}
Blocked 확장자: php, exe, sh, bat, js, jar, asp, jsp 등 20
System upload_allowed_ext Settings Automatic Apply
 

10-3. File-Posts 연결

 POST   /api/v1/upload/attach
업로드된 임시 File(post_id=0)을 게시글에 연결.
🔒 Authorization: Bearer {access_token} 헤더 Required

Request Body (JSON)
{"post_id": "1784211424708247","file_ids": [42, 43]}

Response
{"success": true,"message": "2개 파일이 게시글에 연결되었습니다.","data": {"post_id": "...","attached": 2,"requested": 2}}
이미 다른 게시글에 연결된 File(post_id!=0)은 연결 Not possible (Security)
본인 Posts 또는 Admins only Possible
 

10-4. 임시 File Delete

 DELETE   /api/v1/upload/:file_id
게시글에 연결되지 않은 임시 File(post_id=0) Delete.
🔒 Authorization: Bearer {access_token} 헤더 Required

파라미터
Name Location Required Description
file_id URL Required 삭제할 File ID

Response
{"success": true,"message": "파일이 삭제되었습니다."}
post_id=0 인 파일만 Delete Possible. 이미 게시글에 연결된 File 보호.
물리 File + Thumbnail + DB 레코드 모두 Delete
 
 
 

11. Admin 화면 사용법

Admin → Sites → DX API 또는 /admin/dx-api 접속
 

Dashboard

Item Description
Active 토큰 Current 유효한 Refresh Token 수
연결된 Device 토큰이 발급된 고유 Members 수
엔드포인트 등록된 API 엔드포인트 수 (22 )
인증 Method Bearer Token Method Show
 

API 테스터 사용법

1.  Boards Select 드롭다운에서 테스트할 Boards Select
2.  Posts ID Input (Comments/Posts 상세 테스트 시)
3.  Top 프리셋 Button 클릭 (Login, Posts List, Comments 작성, File 업로드 등)
4.  File 업로드 프리셋 Select 시 File Select Field Automatic Show
5.  Send Button 클릭
6.  Login Success 시 "access_token 자동입력" Button 클릭 → 이후 요청에 Automatic 포함
 

토큰 Manage

•  Active 토큰 List: 회원별 발급일시, 만료일시 OK
•  개별 파기: 특정 회원의 기기에서 Log out 처리
•  All 파기: All 앱 사용자 재로그인 Required (긴급 Security 조치)
 
토큰 파기 후에도 만료되지 않은 Access Token은 최대 1Time 유효. 즉각 차단은 Plugins Deactivate.
 
 

12. 테스트 방법

12-1. Admin 내장 테스터

/admin/dx-api 에서 브라우저로 바로 테스트 Possible. 별도 도구 불필요.

12-2. cURL

Login
curl -X POST https://사이트.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"login_id":"admin","password":"비밀번호"}'

Posts List
curl https://사이트.com/api/v1/boards/free/posts

인증 Request
curl https://사이트.com/api/v1/auth/me \
  -H "Authorization: Bearer eyJ..."

Posts 작성
curl -X POST https://사이트.com/api/v1/boards/free/posts \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer eyJ..." \
  -d '{"title":"테스트 글","content":"<p>내용</p>"}'

Image 업로드 (cURL)
curl -X POST https://사이트.com/api/v1/upload/image \
  -H "Authorization: Bearer eyJ..." \
  -F "file=@/path/to/image.jpg" \
  -F "board_key=free"

12-3. Postman

1.  새 컬렉션 생성: DX API
2.  환경 변수 Settings: BASE_URL = https://Sites.com, ACCESS_TOKEN = (비어있음)
3.  Login Request Tests 탭에 Automatic 토큰 Save Script 추가:
const res = pm.response.json();
if (res.success) {
  pm.environment.set("ACCESS_TOKEN", res.data.access_token);
  pm.environment.set("REFRESH_TOKEN", res.data.refresh_token);
}
4.  이후 모든 Request Authorization Tab → Bearer Token → {{ACCESS_TOKEN}}
5.  File 업로드: Body → form-data → file 키에 File Select

12-4. React Native

api.js — Axios 클라이언트 Settings
import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";

const api = axios.create({
  baseURL: "https://사이트.com/api/v1",
  headers: { "Content-Type": "application/json" },
  timeout: 10000,
});

// 요청 인터셉터 — 토큰 자동 주입
api.interceptors.request.use(async (config) => {
  const token = await AsyncStorage.getItem("access_token");
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// 응답 인터셉터 — 401 시 토큰 자동 갱신
api.interceptors.response.use(
  (res) => res,
  async (error) => {
    if (error.response?.status === 401) {
      const refresh = await AsyncStorage.getItem("refresh_token");
      if (refresh) {
        try {
          const res = await axios.post(
            "https://사이트.com/api/v1/auth/refresh",
            { refresh_token: refresh }
          );
          if (res.data.success) {
            const { access_token, refresh_token } = res.data.data;
            await AsyncStorage.setItem("access_token", access_token);
            await AsyncStorage.setItem("refresh_token", refresh_token);
            error.config.headers.Authorization = `Bearer ${access_token}`;
            return axios(error.config);
          }
        } catch(e) {}
      }
    }
    return Promise.reject(error);
  }
);

export default api;

Login
async function login(loginId, password) {
  const res = await api.post("/auth/login", { login_id: loginId, password });
  const { access_token, refresh_token, user } = res.data.data;
  await AsyncStorage.setItem("access_token", access_token);
  await AsyncStorage.setItem("refresh_token", refresh_token);
  return user;
}

Image 업로드 (React Native)
async function uploadImage(uri, boardKey) {
  const form = new FormData();
  form.append("file", {
    uri,
    type: "image/jpeg",
    name: "photo.jpg",
  });
  form.append("board_key", boardKey);

  const res = await api.post("/upload/image", form, {
    headers: { "Content-Type": "multipart/form-data" },
  });
  return res.data.data.file_id; // file_id 반환
}

// 파일 업로드 후 게시글 작성
async function createPost(boardKey, title, content, fileIds) {
  const res = await api.post(`/boards/${boardKey}/posts`, {
    title,
    content,
    file_ids: fileIds,
  });
  return res.data.data.post_id;
}
 
 
 

13. 다른 플러그인에서 API 확장하기

dx_api_endpoints 훅으로 어떤 플러그인에서도 새 엔드포인트를 추가할 수 있습니다.
 
// plugins/my-shop/plugin.php

dx_add_hook("dx_api_endpoints", function() {

  // GET /api/v1/shop/products
  DxApiRouter::get("/v1/shop/products", function($params) {
    $db = Database::getInstance();
    $pg = DxApiRequest::pagination(20);
    $limit  = (int)$pg["per_page"];
    $offset = (int)$pg["offset"];
    $items = $db->rows(
      "SELECT * FROM `{$db->table('products')}` WHERE status=1
       ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}"
    );
    $total = (int)$db->value(
      "SELECT COUNT(*) FROM `{$db->table('products')}` WHERE status=1"
    );
    DxApiResponse::paginate($items, $total, $pg["page"], $pg["per_page"]);
  });

  // POST /api/v1/shop/orders (인증 필요)
  DxApiRouter::post("/v1/shop/orders", function($params) {
    $payload   = isset($GLOBALS["dx_api_user"]) ? $GLOBALS["dx_api_user"] : array();
    $productId = DxApiRequest::int("product_id");
    // ... 주문 처리
    DxApiResponse::ok(array("order_id" => $orderId), "주문 완료", 201);
  }, array("auth"));

});
 
 
 

14. Error 코드 List

code HTTP Description 해결 방법
LOGIN_FAILED 401 Username/Password 불일치 자격증명 OK
UNAUTHORIZED 401 토큰 None 또는 만료 토큰 갱신 또는 재로그인
INVALID_REFRESH_TOKEN 401 만료/사용된 Refresh Token 재로그인 Required
FORBIDDEN 403 접근 권한 None 권한 Level 또는 소유자 OK
NOT_FOUND 404 리소스 None URL/ID OK
VALIDATION_ERROR 422 입력값 Error errors Field OK
TOO_MANY_REQUESTS 429 Rate Limit 초과 잠시 후 재시도
UPLOAD_ERROR 400 File 업로드 Error File Select 여부 OK
FILE_TOO_LARGE 400 File Size 초과 upload_max_size Settings OK
FILE_NOT_ALLOWED 400 허용되지 않는 확장자 Allow 확장자 OK
INVALID_IMAGE 400 유효하지 않은 Image 실제 Image 파일인지 OK
UPLOAD_NOT_ALLOWED 403 Boards File 업로드 비허용 Boards use_file Settings OK
UPLOAD_FAILED 500 서버 File Save Failed data/uploads/ 권한 OK
INTERNAL_SERVER_ERROR 500 서버 Error 서버 로그 OK
PLUGIN_NOT_FOUND 404 dx-api Plugins 미설치 v1.php Copy 여부 OK
PLUGIN_DISABLED 503 dx-api Deactivate Admin → Plugins Activate
 
 
 

15. Security 권장 사항

Required

•  HTTPS Required — HTTP에서는 Bearer Token이 평문 전송됨
•  Access Token은 앱 메모리에만 Save
•  Refresh Token은 AsyncStorage 대신 Expo SecureStore / iOS Keychain / Android Keystore Enabled
•  data/uploads/ Folder 권한 755 Settings
 

권장

•  프로덕션에서 CORS origin을 * 대신 실제 도메인으로 제한 (Response.php Edit)
•  Admin 화면에서 주기적으로 만료 토큰 정리
•  의심스러운 Activity 시 Admin 화면 → All 토큰 파기
•  API 불필요 시 Plugins 비활성화로 완전 Blocked
 

CORS Domain 제한 (Response.php)

// plugins/dx-api/core/Response.php send() 메서드에서
// 변경 전:
header("Access-Control-Allow-Origin: *");

// 변경 후:
$allowed = array("https://myapp.com", "https://admin.myapp.com");
$origin  = isset($_SERVER["HTTP_ORIGIN"]) ? $_SERVER["HTTP_ORIGIN"] : "";
if (in_array($origin, $allowed)) {
  header("Access-Control-Allow-Origin: " . $origin);
}
Attachments 1 Members only

Comments1

D
DX관리자 2026.07.23 03:31

아직 완벽한 수준은 아니지만, 시니어 개발자님들의 의견을 듣고 더 나은 플러그인으로 발전시키기 위해 먼저 배포하게 되었습니다.

부족한 부분이나 개선이 필요한 사항이 있다면 아낌없이 말씀해 주시면 감사하겠습니다. 보내주시는 피드백 하나하나를 소중히 받아들이고, 배우는 자세로 적극 반영하도록 하겠습니다.

많은 조언과 검토를 부탁드립니다. 감사합니다.

Login to be able to write a comment.
Plugin TOTAL 84
List Login
List