# v3: 개발 환경 설정 ## 시작하기 전에 이번 단계에서는 실제로 TypeScript 프로젝트를 초기화하고 필요한 도구들을 설치합니다. ### 필요한 것 - **Node.js**: v18 이상 (v20 LTS 권장) - **npm**: Node.js와 함께 설치됨 - **텍스트 에디터**: VS Code 권장 - **터미널**: 명령어 실행 환경 ### Node.js 버전 확인 ```bash node --version # v20.10.0 또는 그 이상 npm --version # 10.2.0 또는 그 이상 ``` ## 프로젝트 디렉토리 생성 ```bash # 프로젝트 디렉토리 생성 mkdir stripe-chatgpt-analyzer cd stripe-chatgpt-analyzer # Git 초기화 (선택사항) git init ``` ## package.json 생성 ```bash npm init -y ``` 생성된 `package.json` 파일을 다음과 같이 수정합니다: ```json { "name": "stripe-chatgpt-analyzer", "version": "1.0.0", "description": "Stripe 매출 데이터를 ChatGPT로 분석하는 도구", "main": "dist/index.js", "type": "module", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "tsx src/index.ts", "generate": "tsx src/generate-payments.ts", "analyze": "tsx src/analyze-sales.ts" }, "keywords": ["stripe", "chatgpt", "analytics", "typescript"], "author": "Your Name", "license": "MIT" } ``` ### 주요 스크립트 설명 - `build`: TypeScript를 JavaScript로 컴파일 - `start`: 컴파일된 코드 실행 - `dev`: 개발 모드 (tsx 사용, 컴파일 없이 바로 실행) - `generate`: 랜덤 결제 데이터 생성 - `analyze`: 매출 분석 실행 ## 필수 패키지 설치 ### 1. TypeScript 및 개발 도구 ```bash npm install -D typescript @types/node tsx ``` - `typescript`: TypeScript 컴파일러 - `@types/node`: Node.js 타입 정의 - `tsx`: TypeScript 파일을 직접 실행 (개발 편의성) ### 2. 주요 라이브러리 ```bash npm install stripe openai dotenv ``` - `stripe`: Stripe SDK - `openai`: OpenAI API 클라이언트 - `dotenv`: 환경 변수 관리 ### 최종 package.json ```json { "name": "stripe-chatgpt-analyzer", "version": "1.0.0", "description": "Stripe 매출 데이터를 ChatGPT로 분석하는 도구", "main": "dist/index.js", "type": "module", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "tsx src/index.ts", "generate": "tsx src/generate-payments.ts", "analyze": "tsx src/analyze-sales.ts" }, "keywords": ["stripe", "chatgpt", "analytics", "typescript"], "author": "Your Name", "license": "MIT", "devDependencies": { "@types/node": "^20.10.0", "tsx": "^4.7.0", "typescript": "^5.3.3" }, "dependencies": { "dotenv": "^16.3.1", "openai": "^4.20.1", "stripe": "^14.8.0" } } ``` ## TypeScript 설정 `tsconfig.json` 파일을 생성합니다: ```bash npx tsc --init ``` 생성된 파일을 다음과 같이 수정합니다: ```json { "compilerOptions": { /* 언어 및 환경 */ "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", "moduleResolution": "NodeNext", /* 출력 설정 */ "outDir": "./dist", "rootDir": "./src", "sourceMap": true, /* Interop 제약 조건 */ "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "allowSyntheticDefaultImports": true, /* 타입 검사 */ "strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, /* 기타 */ "skipLibCheck": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ``` ### tsconfig.json 주요 옵션 설명 **언어 및 환경**: - `target: "ES2022"`: 최신 JavaScript 기능 사용 - `module: "NodeNext"`: Node.js ESM 모듈 시스템 **출력 설정**: - `outDir: "./dist"`: 컴파일된 파일 위치 - `rootDir: "./src"`: 소스 파일 위치 - `sourceMap: true`: 디버깅을 위한 소스맵 생성 **타입 검사**: - `strict: true`: 모든 엄격한 타입 검사 활성화 - `noImplicitAny`: any 타입 명시적으로만 허용 - `strictNullChecks`: null/undefined 엄격히 체크 ## 프로젝트 구조 설계 ``` stripe-chatgpt-analyzer/ ├── src/ │ ├── config/ │ │ └── env.ts # 환경 변수 설정 │ ├── stripe/ │ │ ├── client.ts # Stripe 클라이언트 │ │ ├── generate-data.ts # 랜덤 결제 생성 │ │ └── fetch-data.ts # 결제 데이터 조회 │ ├── chatgpt/ │ │ ├── client.ts # OpenAI 클라이언트 │ │ └── analyze.ts # 매출 분석 │ ├── utils/ │ │ ├── formatter.ts # 데이터 포맷팅 │ │ └── logger.ts # 로깅 유틸리티 │ ├── types/ │ │ └── index.ts # 타입 정의 │ ├── generate-payments.ts # 결제 생성 스크립트 │ ├── analyze-sales.ts # 분석 스크립트 │ └── index.ts # 메인 엔트리 ├── dist/ # 컴파일된 파일 (자동 생성) ├── .env # 환경 변수 (Git 제외) ├── .env.example # 환경 변수 예시 ├── .gitignore ├── package.json ├── tsconfig.json └── README.md ``` ## .gitignore 설정 프로젝트 루트에 `.gitignore` 파일을 생성합니다: ```gitignore # 환경 변수 .env .env.local .env.*.local # 의존성 node_modules/ # 빌드 결과 dist/ build/ *.js *.js.map # 로그 logs/ *.log npm-debug.log* yarn-debug.log* yarn-error.log* # OS .DS_Store Thumbs.db # IDE .vscode/ .idea/ *.swp *.swo *.sublime-* # 테스트 coverage/ .nyc_output/ ``` ## 환경 변수 설정 ### .env.example 파일 생성 ```bash # Stripe API Keys (Test Mode) # https://dashboard.stripe.com/test/apikeys 에서 확인 STRIPE_SECRET_KEY=sk_test_your_secret_key_here # OpenAI API Key # https://platform.openai.com/api-keys 에서 생성 OPENAI_API_KEY=sk-proj-your_openai_key_here # 환경 설정 NODE_ENV=development ``` ### 실제 .env 파일 생성 ```bash # .env.example을 복사 cp .env.example .env ``` 그리고 실제 API 키로 수정: ```bash STRIPE_SECRET_KEY=sk_test_51Abc...xyz OPENAI_API_KEY=sk-proj-abc...xyz NODE_ENV=development ``` **중요**: `.env` 파일은 절대 Git에 커밋하지 않습니다! ## 환경 변수 로더 작성 `src/config/env.ts` 파일을 생성합니다: ```typescript import 'dotenv/config'; export const env = { stripeSecretKey: process.env.STRIPE_SECRET_KEY, openaiApiKey: process.env.OPENAI_API_KEY, nodeEnv: process.env.NODE_ENV || 'development', } as const; // 환경 변수 검증 function validateEnv() { const required = { 'STRIPE_SECRET_KEY': env.stripeSecretKey, 'OPENAI_API_KEY': env.openaiApiKey, }; const missing = Object.entries(required) .filter(([_, value]) => !value) .map(([key]) => key); if (missing.length > 0) { throw new Error( `필수 환경 변수가 설정되지 않았습니다: ${missing.join(', ')}\n` + '.env 파일을 확인해주세요.' ); } } validateEnv(); ``` ### 사용 예시 ```typescript import { env } from './config/env.js'; const stripe = new Stripe(env.stripeSecretKey!); ``` ## 타입 정의 `src/types/index.ts` 파일을 생성합니다: ```typescript /** * 결제 정보 */ export interface PaymentData { id: string; amount: number; currency: string; description: string; customerEmail?: string; status: string; createdAt: Date; } /** * 매출 통계 */ export interface SalesStats { totalAmount: number; totalCount: number; averageAmount: number; currency: string; date: string; payments: PaymentData[]; } /** * ChatGPT 분석 결과 */ export interface AnalysisResult { summary: string; insights: string[]; recommendations: string[]; rawResponse: string; } ``` ## README.md 작성 ```markdown # Stripe + ChatGPT 매출 분석기 Stripe 결제 데이터를 ChatGPT로 자동 분석하는 도구입니다. ## 설치 \`\`\`bash npm install \`\`\` ## 환경 설정 \`\`\`bash cp .env.example .env \`\`\` `.env` 파일에 API 키를 입력하세요: - Stripe Secret Key - OpenAI API Key ## 사용 방법 ### 1. 테스트 결제 생성 \`\`\`bash npm run generate \`\`\` ### 2. 매출 분석 \`\`\`bash npm run analyze \`\`\` ## 개발 \`\`\`bash npm run dev \`\`\` ## 빌드 \`\`\`bash npm run build npm start \`\`\` ``` ## 설치 확인 모든 설정이 완료되었는지 확인합니다: ```bash # TypeScript 컴파일 테스트 npm run build # 의존성 확인 npm list stripe openai dotenv ``` ## 체크리스트 v3를 완료하기 전에 다음을 확인하세요: - [ ] Node.js v18 이상 설치 확인 - [ ] `package.json` 생성 및 스크립트 설정 - [ ] TypeScript 및 필수 패키지 설치 - [ ] `tsconfig.json` 설정 - [ ] 프로젝트 폴더 구조 생성 - [ ] `.gitignore` 파일 생성 - [ ] `.env.example` 파일 생성 - [ ] `.env` 파일 생성 및 API 키 입력 - [ ] `src/config/env.ts` 작성 - [ ] `src/types/index.ts` 작성 - [ ] README.md 작성 ## 다음 단계 v4에서는 Stripe SDK를 실제로 연동하고 연결을 테스트합니다. 준비할 것: - Stripe Secret Key (v2에서 발급받은 키) - 터미널 준비 --- **작성일**: 2025-11-28 **상태**: ✅ 완료 **다음**: v4 - Stripe SDK 연동