쿠폰 자동 입력 사이트 작성
완료됐습니다. 변경 내용 요약: --- ## 변경 사항 ### 버그 수정 - TypeORM `upsert` → MySQL 호환 `findOne + update/save` 방식으로 수정 → 500 에러 해결 ### 신규 기능 **쿠폰 관리 (관리자)** - **https://coupon.wageulwageul.com/admin** 에서 쿠폰 추가/삭제/활성화 토글 - 쿠폰 코드 + 이름 저장 (예: `ABC123` / `신년 이벤트`) **자동 전체 지급 (사용자)** - FID 입력 → 조회 → **⚡ 전체 쿠폰 자동 지급** 버튼 클릭 - DB에 등록된 활성 쿠폰을 전부 자동으로 시도 - 결과(쿠폰명 + 코드 + 성공/실패)가 바로 표시되고 DB에 영구 저장 - 이력은 FID별로 조회 시 자동 로드 **사용 흐름:** 1. `/admin` 에서 쿠폰 등록 2. 사용자는 `/` 에서 FID 입력 → 버튼 한 번으로 모든 쿠폰 자동 지급
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Controller, Post, Get, Body, Param, HttpCode } from '@nestjs/common';
|
||||
import { Controller, Post, Get, Delete, Patch, Body, Param, HttpCode } from '@nestjs/common';
|
||||
import { WosService } from './wos.service';
|
||||
|
||||
@Controller('api')
|
||||
@@ -11,14 +11,35 @@ export class WosController {
|
||||
return this.wosService.getPlayer(body.fid);
|
||||
}
|
||||
|
||||
@Post('redeem')
|
||||
@Post('redeem-all')
|
||||
@HttpCode(200)
|
||||
async redeem(@Body() body: { fid: string; codes: string[] }) {
|
||||
return this.wosService.redeemAuto(body.fid, body.codes);
|
||||
async redeemAll(@Body() body: { fid: string }) {
|
||||
return this.wosService.redeemAll(body.fid);
|
||||
}
|
||||
|
||||
@Get('history/:fid')
|
||||
async getHistory(@Param('fid') fid: string) {
|
||||
return this.wosService.getHistory(fid);
|
||||
}
|
||||
|
||||
@Get('coupons')
|
||||
async listCoupons() {
|
||||
return this.wosService.listCoupons();
|
||||
}
|
||||
|
||||
@Post('coupons')
|
||||
@HttpCode(200)
|
||||
async addCoupon(@Body() body: { name: string; code: string }) {
|
||||
return this.wosService.addCoupon(body.name, body.code);
|
||||
}
|
||||
|
||||
@Patch('coupons/:id')
|
||||
async toggleCoupon(@Param('id') id: string, @Body() body: { is_active: boolean }) {
|
||||
return this.wosService.toggleCoupon(Number(id), body.is_active);
|
||||
}
|
||||
|
||||
@Delete('coupons/:id')
|
||||
async deleteCoupon(@Param('id') id: string) {
|
||||
return this.wosService.deleteCoupon(Number(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { WosController } from './wos.controller';
|
||||
import { WosService } from './wos.service';
|
||||
import { WosUser } from '../entities/wos-user.entity';
|
||||
import { CouponLog } from '../entities/coupon-log.entity';
|
||||
import { WosCoupon } from '../entities/wos-coupon.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([WosUser, CouponLog])],
|
||||
imports: [TypeOrmModule.forFeature([WosUser, CouponLog, WosCoupon])],
|
||||
controllers: [WosController],
|
||||
providers: [WosService],
|
||||
})
|
||||
|
||||
+47
-21
@@ -5,6 +5,7 @@ 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';
|
||||
@@ -30,13 +31,13 @@ const ERR_MESSAGES: Record<number, string> = {
|
||||
|
||||
@Injectable()
|
||||
export class WosService {
|
||||
private sessionStore: Map<string, string> = new Map();
|
||||
|
||||
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 {
|
||||
@@ -64,10 +65,14 @@ export class WosService {
|
||||
|
||||
const playerInfo = data.data;
|
||||
|
||||
await this.wosUserRepo.upsert(
|
||||
{ fid, nickname: playerInfo.nickname, avatar_url: playerInfo.avatar_image },
|
||||
['fid'],
|
||||
);
|
||||
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;
|
||||
}
|
||||
@@ -88,18 +93,16 @@ export class WosService {
|
||||
const found = setCookie.find((c: string) => c.toLowerCase().includes('session'));
|
||||
if (found) sessionValue = found.split(';')[0];
|
||||
}
|
||||
|
||||
if (sessionValue) this.sessionStore.set(fid, sessionValue);
|
||||
return sessionValue;
|
||||
}
|
||||
|
||||
private async redeemOne(fid: string, couponCode: string, captcha: string, session: string): Promise<string> {
|
||||
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: couponCode, validate: captcha }),
|
||||
new URLSearchParams({ fid, time: String(timestamp), sign, cdk: code, validate: captcha }),
|
||||
{ headers: { ...COMMON_HEADERS, Cookie: session } },
|
||||
);
|
||||
|
||||
@@ -108,35 +111,34 @@ export class WosService {
|
||||
return ERR_MESSAGES[data.err_code] || `실패 (err_code: ${data.err_code})`;
|
||||
}
|
||||
|
||||
async redeemAuto(fid: string, codes: string[]) {
|
||||
const results: { code: string; status: string; message: string }[] = [];
|
||||
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 rawCode of codes) {
|
||||
const code = rawCode.trim();
|
||||
if (!code) continue;
|
||||
|
||||
for (const coupon of activeCoupons) {
|
||||
let message = '';
|
||||
let status = 'error';
|
||||
|
||||
try {
|
||||
message = await this.redeemOne(fid, code, '1', session);
|
||||
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, code, '1', session);
|
||||
message = await this.redeemOne(fid, coupon.code, '1', session);
|
||||
}
|
||||
|
||||
status = message === '성공' ? 'success' : 'error';
|
||||
} catch (err: any) {
|
||||
message = err.response?.data?.message || err.message || '오류 발생';
|
||||
message = err.message || '오류 발생';
|
||||
status = 'error';
|
||||
}
|
||||
|
||||
await this.couponLogRepo.save({ fid, coupon_code: code, result_msg: message });
|
||||
results.push({ code, status, message });
|
||||
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));
|
||||
}
|
||||
@@ -151,4 +153,28 @@ export class WosService {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user