coupon/back/src/wos/wos.service.ts
hyoseung930 1b43b874a1 쿠폰 자동 입력 사이트 작성
완료됐습니다. 변경 내용 요약:

---

## 변경 사항

### 버그 수정
- TypeORM `upsert` → MySQL 호환 `findOne + update/save` 방식으로 수정 → 500 에러 해결

### 신규 기능

**쿠폰 관리 (관리자)**
- **https://coupon.wageulwageul.com/admin** 에서 쿠폰 추가/삭제/활성화 토글
- 쿠폰 코드 + 이름 저장 (예: `ABC123` / `신년 이벤트`)

**자동 전체 지급 (사용자)**
- FID 입력 → 조회 → ** 전체 쿠폰 자동 지급** 버튼 클릭
- DB에 등록된 활성 쿠폰을 전부 자동으로 시도
- 결과(쿠폰명 + 코드 + 성공/실패)가 바로 표시되고 DB에 영구 저장
- 이력은 FID별로 조회 시 자동 로드

**사용 흐름:**
1. `/admin` 에서 쿠폰 등록
2. 사용자는 `/` 에서 FID 입력 → 버튼 한 번으로 모든 쿠폰 자동 지급
2026-04-16 18:03:45 +09:00

181 lines
5.9 KiB
TypeScript

import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import axios from 'axios';
import * as crypto from 'crypto';
import { WosUser } from '../entities/wos-user.entity';
import { CouponLog } from '../entities/coupon-log.entity';
import { WosCoupon } from '../entities/wos-coupon.entity';
const SECRET = 'tB87#kPtkxqOS2';
const WOS_API_BASE = 'https://wos-giftcode-api.centurygame.com/api';
const COMMON_HEADERS = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
'Origin': 'https://wos-giftcode.centurygame.com',
'Referer': 'https://wos-giftcode.centurygame.com/',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'ko-KR,ko;q=0.9,en;q=0.8',
};
const ERR_MESSAGES: Record<number, string> = {
20000: '쿠폰 코드가 존재하지 않습니다.',
20001: '이미 사용된 쿠폰입니다.',
20002: '만료된 쿠폰입니다.',
20003: '캡차 인증에 실패했습니다.',
40001: '존재하지 않는 플레이어 ID입니다.',
40004: '캡차 입력이 올바르지 않습니다.',
40014: '캡차 세션이 만료되었습니다. 다시 시도해주세요.',
};
@Injectable()
export class WosService {
constructor(
@InjectRepository(WosUser)
private wosUserRepo: Repository<WosUser>,
@InjectRepository(CouponLog)
private couponLogRepo: Repository<CouponLog>,
@InjectRepository(WosCoupon)
private wosCouponRepo: Repository<WosCoupon>,
) {}
private makeSign(fid: string, timestamp: number): string {
const raw = `fid=${fid}&time=${timestamp}${SECRET}`;
return crypto.createHash('md5').update(raw).digest('hex');
}
async getPlayer(fid: string) {
const timestamp = Date.now();
const sign = this.makeSign(fid, timestamp);
const response = await axios.post(
`${WOS_API_BASE}/player`,
new URLSearchParams({ fid, time: String(timestamp), sign }),
{ headers: { ...COMMON_HEADERS } },
);
const data = response.data;
if (data.code !== 0) {
throw new HttpException(
ERR_MESSAGES[data.err_code] || `오류가 발생했습니다. (${data.err_code})`,
HttpStatus.BAD_REQUEST,
);
}
const playerInfo = data.data;
const existing = await this.wosUserRepo.findOne({ where: { fid } });
if (existing) {
existing.nickname = playerInfo.nickname;
existing.avatar_url = playerInfo.avatar_image;
await this.wosUserRepo.save(existing);
} else {
await this.wosUserRepo.save({ fid, nickname: playerInfo.nickname, avatar_url: playerInfo.avatar_image });
}
return playerInfo;
}
private async acquireSession(fid: string): Promise<string> {
const timestamp = Date.now();
const sign = this.makeSign(fid, timestamp);
const response = await axios.post(
`${WOS_API_BASE}/captcha`,
new URLSearchParams({ fid, time: String(timestamp), sign }),
{ headers: { ...COMMON_HEADERS }, withCredentials: true },
);
const setCookie = response.headers['set-cookie'];
let sessionValue = '';
if (setCookie) {
const found = setCookie.find((c: string) => c.toLowerCase().includes('session'));
if (found) sessionValue = found.split(';')[0];
}
return sessionValue;
}
private async redeemOne(fid: string, code: string, captcha: string, session: string): Promise<string> {
const timestamp = Date.now();
const sign = this.makeSign(fid, timestamp);
const response = await axios.post(
`${WOS_API_BASE}/gift_code`,
new URLSearchParams({ fid, time: String(timestamp), sign, cdk: code, validate: captcha }),
{ headers: { ...COMMON_HEADERS, Cookie: session } },
);
const data = response.data;
if (data.code === 0) return '성공';
return ERR_MESSAGES[data.err_code] || `실패 (err_code: ${data.err_code})`;
}
async redeemAll(fid: string) {
const activeCoupons = await this.wosCouponRepo.find({ where: { is_active: true } });
if (activeCoupons.length === 0) return [];
const results: { name: string; code: string; status: string; message: string }[] = [];
let session = await this.acquireSession(fid);
for (const coupon of activeCoupons) {
let message = '';
let status = 'error';
try {
message = await this.redeemOne(fid, coupon.code, '1', session);
if (message.includes('캡차') || message.includes('세션')) {
session = await this.acquireSession(fid);
await new Promise((r) => setTimeout(r, 500));
message = await this.redeemOne(fid, coupon.code, '1', session);
}
status = message === '성공' ? 'success' : 'error';
} catch (err: any) {
message = err.message || '오류 발생';
status = 'error';
}
await this.couponLogRepo.save({ fid, coupon_code: coupon.code, result_msg: message });
results.push({ name: coupon.name, code: coupon.code, status, message });
await new Promise((r) => setTimeout(r, 1000));
}
return results;
}
async getHistory(fid: string) {
return this.couponLogRepo.find({
where: { fid },
order: { executed_at: 'DESC' },
take: 100,
});
}
async listCoupons() {
return this.wosCouponRepo.find({ order: { created_at: 'DESC' } });
}
async addCoupon(name: string, code: string) {
const exists = await this.wosCouponRepo.findOne({ where: { code } });
if (exists) {
exists.name = name;
exists.is_active = true;
return this.wosCouponRepo.save(exists);
}
return this.wosCouponRepo.save({ name, code, is_active: true });
}
async toggleCoupon(id: number, is_active: boolean) {
await this.wosCouponRepo.update(id, { is_active });
return this.wosCouponRepo.findOne({ where: { id } });
}
async deleteCoupon(id: number) {
await this.wosCouponRepo.delete(id);
return { success: true };
}
}