feat: 虚拟支付完整链路——vpay服务模块(双签名/充值下单/回调到账/退款) + 充值页 + 我的入口 + session_key存储
This commit is contained in:
@@ -124,6 +124,12 @@
|
|||||||
"navigationBarTitleText": "协议",
|
"navigationBarTitleText": "协议",
|
||||||
"navigationStyle": "custom"
|
"navigationStyle": "custom"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "pages/vpay/recharge",
|
||||||
|
"style": {
|
||||||
|
"navigationBarTitleText": "充值星尘"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"globalStyle": {
|
"globalStyle": {
|
||||||
|
|||||||
@@ -87,6 +87,16 @@
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
<!-- 星尘充值入口 -->
|
||||||
|
<view class="vpay-entry" @click="goRecharge">
|
||||||
|
<view class="ve-icon">✨</view>
|
||||||
|
<view class="ve-info">
|
||||||
|
<text class="ve-title">充值星尘</text>
|
||||||
|
<text class="ve-desc">AI问答 · 会员订阅</text>
|
||||||
|
</view>
|
||||||
|
<text class="ve-arrow">→</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
<!-- 菜单列表 -->
|
<!-- 菜单列表 -->
|
||||||
<view class="menu-section">
|
<view class="menu-section">
|
||||||
<view class="menu-item" @click="goFavorites">
|
<view class="menu-item" @click="goFavorites">
|
||||||
@@ -261,6 +271,7 @@ async function handleLogout() {
|
|||||||
|
|
||||||
function goLogin() { uni.navigateTo({ url: '/pages/login/login' }) }
|
function goLogin() { uni.navigateTo({ url: '/pages/login/login' }) }
|
||||||
|
|
||||||
|
function goRecharge() { uni.navigateTo({ url: '/pages/vpay/recharge' }) }
|
||||||
function goChat() { uni.switchTab({ url: '/pages/chat/chat' }) }
|
function goChat() { uni.switchTab({ url: '/pages/chat/chat' }) }
|
||||||
function goFavorites() { uni.navigateTo({ url: '/pages/favorites/favorites' }) }
|
function goFavorites() { uni.navigateTo({ url: '/pages/favorites/favorites' }) }
|
||||||
function goProgress() { uni.navigateTo({ url: '/pages/progress/progress' }) }
|
function goProgress() { uni.navigateTo({ url: '/pages/progress/progress' }) }
|
||||||
@@ -624,3 +635,17 @@ onShareTimeline(() => ({
|
|||||||
padding: 8px 0 20px;
|
padding: 8px 0 20px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.vpay-entry {
|
||||||
|
display: flex; align-items: center; gap: 12px;
|
||||||
|
background: linear-gradient(135deg, rgba(91,95,248,.1), rgba(139,92,246,.06));
|
||||||
|
border: 1.5px solid var(--glass-hover-border);
|
||||||
|
border-radius: var(--radius-lg); padding: 14px 16px; margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.ve-icon { font-size: 22px; }
|
||||||
|
.ve-info { flex: 1; }
|
||||||
|
.ve-title { font-size: 14px; font-weight: 700; color: var(--text-primary); display: block; }
|
||||||
|
.ve-desc { font-size: 11px; color: var(--text-tertiary); }
|
||||||
|
.ve-arrow { font-size: 14px; color: var(--text-muted); }
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<template>
|
||||||
|
<view class="vpay-page page-layout">
|
||||||
|
<view class="status-bar-placeholder"></view>
|
||||||
|
|
||||||
|
<view class="balance-card">
|
||||||
|
<text class="balance-label">我的{{ info.coinName || '星尘' }}</text>
|
||||||
|
<text class="balance-num">{{ info.balance || 0 }}</text>
|
||||||
|
<text class="balance-hint">{{ info.env === 'sandbox' ? '(沙箱环境)' : '' }}1元 = 100 {{ info.coinName || '星尘' }}</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="section-header">
|
||||||
|
<text class="section-title">选择充值档位</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="pkg-grid">
|
||||||
|
<view
|
||||||
|
v-for="p in info.packages || []"
|
||||||
|
:key="p.id"
|
||||||
|
class="pkg-card"
|
||||||
|
:class="{ active: picked === p.id }"
|
||||||
|
@tap="picked = p.id"
|
||||||
|
>
|
||||||
|
<text class="pkg-coins">{{ p.label }}</text>
|
||||||
|
<text class="pkg-price">¥{{ p.priceYuan }}</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="use-cases">
|
||||||
|
<text class="uc-title">{{ info.coinName || '星尘' }}用途</text>
|
||||||
|
<view class="uc-item"><text class="uc-tag">问答</text><text>AI 问答一次 10 {{ info.coinName || '星尘' }}</text></view>
|
||||||
|
<view class="uc-item"><text class="uc-tag">会员</text><text>Pro 月卡 3000 {{ info.coinName || '星尘' }}</text></view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="pay-agreement-row">
|
||||||
|
<text class="pay-agreement-text">
|
||||||
|
充值即消耗型虚拟商品,不支持退款(法定情形除外),详见
|
||||||
|
<text class="pay-agreement-link" @click.stop="openAgreement">《用户协议》</text>
|
||||||
|
</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<button class="recharge-btn" :disabled="!picked || paying" @tap="recharge">
|
||||||
|
{{ paying ? '拉起支付中…' : '立即充值' }}
|
||||||
|
</button>
|
||||||
|
</view>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { request } from '../../utils/api'
|
||||||
|
import { useUserStore } from '../../stores/user'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const info = ref({})
|
||||||
|
const picked = ref('')
|
||||||
|
const paying = ref(false)
|
||||||
|
|
||||||
|
function openAgreement() {
|
||||||
|
uni.navigateTo({ url: '/pages/agreement/agreement?type=terms' })
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
if (!userStore.isLoggedIn) {
|
||||||
|
uni.showToast({ title: '请先登录', icon: 'none' })
|
||||||
|
setTimeout(() => uni.navigateBack(), 1500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
info.value = await request('GET', '/api/vpay/info', null, userStore.token)
|
||||||
|
if ((info.value.packages || []).length) picked.value = info.value.packages[0].id
|
||||||
|
} catch (e) {
|
||||||
|
uni.showToast({ title: e.message || '获取充值信息失败', icon: 'none' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
async function recharge() {
|
||||||
|
if (!picked.value || paying.value) return
|
||||||
|
paying.value = true
|
||||||
|
try {
|
||||||
|
const data = await request('POST', '/api/vpay/recharge', { packageId: picked.value }, userStore.token)
|
||||||
|
const pay = data.payParams
|
||||||
|
if (!pay) throw new Error('支付参数异常')
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
uni.requestVirtualPayment({
|
||||||
|
mode: pay.mode,
|
||||||
|
env: pay.env,
|
||||||
|
offerId: pay.offerId,
|
||||||
|
buyQuantity: pay.buyQuantity,
|
||||||
|
currencyType: pay.currencyType,
|
||||||
|
platform: pay.platform,
|
||||||
|
outTradeNo: pay.outTradeNo,
|
||||||
|
signData: pay.signData,
|
||||||
|
paySig: pay.paySig,
|
||||||
|
signature: pay.signature,
|
||||||
|
success: resolve,
|
||||||
|
fail: (err) => reject(new Error(err.errMsg || err.errCode || '支付失败')),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// #ifndef MP-WEIXIN
|
||||||
|
uni.showToast({ title: '请在微信小程序内充值', icon: 'none' })
|
||||||
|
return
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
uni.showToast({ title: '充值成功!', icon: 'success' })
|
||||||
|
// 刷新余额
|
||||||
|
info.value = await request('GET', '/api/vpay/info', null, userStore.token)
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e.message || '支付未完成'
|
||||||
|
if (msg.includes('cancel')) {
|
||||||
|
uni.showToast({ title: '已取消支付', icon: 'none' })
|
||||||
|
} else {
|
||||||
|
uni.showToast({ title: msg, icon: 'none', duration: 3000 })
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
paying.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style lang="scss" scoped>
|
||||||
|
.vpay-page { min-height: 100vh; padding: 0 20px 40px; background: var(--bg-primary); }
|
||||||
|
.status-bar-placeholder { height: 44px; }
|
||||||
|
.balance-card {
|
||||||
|
background: linear-gradient(135deg, #5b5ff8, #8b5cf6);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 22px 20px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex; flex-direction: column; gap: 4px;
|
||||||
|
.balance-label { font-size: 12px; color: rgba(255,255,255,.7); }
|
||||||
|
.balance-num { font-size: 36px; font-weight: 800; color: #fff; }
|
||||||
|
.balance-hint { font-size: 11px; color: rgba(255,255,255,.5); }
|
||||||
|
}
|
||||||
|
.section-header { display: flex; align-items: center; margin: 16px 0 12px;
|
||||||
|
.section-title { font-size: 15px; font-weight: 700; color: var(--text-primary); } }
|
||||||
|
.pkg-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||||
|
.pkg-card {
|
||||||
|
background: var(--glass-bg); border: 2px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-lg); padding: 16px 14px;
|
||||||
|
display: flex; flex-direction: column; align-items: center; gap: 4px;
|
||||||
|
transition: border-color .2s;
|
||||||
|
&.active { border-color: var(--color-brand); background: var(--color-brand-bg); }
|
||||||
|
.pkg-coins { font-size: 16px; font-weight: 700; color: var(--text-primary); }
|
||||||
|
.pkg-price { font-size: 14px; color: var(--color-brand); font-weight: 600; }
|
||||||
|
}
|
||||||
|
.use-cases {
|
||||||
|
background: var(--glass-bg); border: 1px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-lg); padding: 14px 16px; margin-top: 16px;
|
||||||
|
.uc-title { font-size: 13px; font-weight: 700; color: var(--text-primary); display: block; margin-bottom: 8px; }
|
||||||
|
.uc-item { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; font-size: 12px; color: var(--text-tertiary); }
|
||||||
|
.uc-tag {
|
||||||
|
background: var(--color-brand-bg); color: var(--color-brand);
|
||||||
|
border-radius: 4px; padding: 1px 6px; font-size: 10px; font-weight: 600; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.pay-agreement-row { display: flex; justify-content: center; margin-top: 14px; }
|
||||||
|
.pay-agreement-text { font-size: 10px; color: var(--text-muted); text-align: center; }
|
||||||
|
.pay-agreement-link { color: var(--color-brand); }
|
||||||
|
.recharge-btn {
|
||||||
|
width: 100%; height: 48px; margin-top: 16px;
|
||||||
|
background: linear-gradient(135deg, var(--color-brand), var(--color-brand-light));
|
||||||
|
color: #fff; font-size: 16px; font-weight: 700; border-radius: var(--radius-lg);
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
&[disabled] { opacity: .5; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -12,7 +12,7 @@ const API_BASE = import.meta.env.VITE_API_BASE || (import.meta.env.DEV ? DEV_URL
|
|||||||
/**
|
/**
|
||||||
* 通用请求封装
|
* 通用请求封装
|
||||||
*/
|
*/
|
||||||
async function request(method, path, data = null, token = null) {
|
export async function request(method, path, data = null, token = null) {
|
||||||
const url = `${API_BASE}${path}`
|
const url = `${API_BASE}${path}`
|
||||||
const headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ const connectDB = require('./config/database')
|
|||||||
const initRoutes = require('./routes')
|
const initRoutes = require('./routes')
|
||||||
const seoRoutes = require('./routes/seo')
|
const seoRoutes = require('./routes/seo')
|
||||||
const registerWxMsgRoutes = require('./routes/wxmsg')
|
const registerWxMsgRoutes = require('./routes/wxmsg')
|
||||||
|
const registerVpayRoutes = require('./routes/vpay')
|
||||||
const logger = require('./utils/logger')
|
const logger = require('./utils/logger')
|
||||||
|
|
||||||
// 创建 Express 应用
|
// 创建 Express 应用
|
||||||
@@ -75,6 +76,7 @@ app.get('/health', (req, res) => {
|
|||||||
|
|
||||||
// API 路由
|
// API 路由
|
||||||
registerWxMsgRoutes(app)
|
registerWxMsgRoutes(app)
|
||||||
|
registerVpayRoutes(app)
|
||||||
initRoutes(app)
|
initRoutes(app)
|
||||||
|
|
||||||
// 404 处理
|
// 404 处理
|
||||||
|
|||||||
+314
-311
@@ -1,311 +1,314 @@
|
|||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
const { Schema } = mongoose
|
const { Schema } = mongoose
|
||||||
const bcrypt = require('bcryptjs')
|
const bcrypt = require('bcryptjs')
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户探索数据结构
|
* 用户探索数据结构
|
||||||
*/
|
*/
|
||||||
const ExploreDataSchema = new Schema({
|
const ExploreDataSchema = new Schema({
|
||||||
dim1: {
|
dim1: {
|
||||||
completed: { type: Boolean, default: false },
|
completed: { type: Boolean, default: false },
|
||||||
bestScore: { type: Number, default: 0 },
|
bestScore: { type: Number, default: 0 },
|
||||||
collectedEggs: { type: Number, default: 0 },
|
collectedEggs: { type: Number, default: 0 },
|
||||||
totalLength: { type: Number, default: 0 }
|
totalLength: { type: Number, default: 0 }
|
||||||
},
|
},
|
||||||
dim2: {
|
dim2: {
|
||||||
completed: { type: Boolean, default: false },
|
completed: { type: Boolean, default: false },
|
||||||
bestArea: { type: Number, default: 0 },
|
bestArea: { type: Number, default: 0 },
|
||||||
createdShapes: { type: Number, default: 0 }
|
createdShapes: { type: Number, default: 0 }
|
||||||
},
|
},
|
||||||
dim3: {
|
dim3: {
|
||||||
completed: { type: Boolean, default: false },
|
completed: { type: Boolean, default: false },
|
||||||
exploredFaces: { type: Number, default: 0 },
|
exploredFaces: { type: Number, default: 0 },
|
||||||
rotationTime: { type: Number, default: 0 },
|
rotationTime: { type: Number, default: 0 },
|
||||||
bestScore: { type: Number, default: 0 }
|
bestScore: { type: Number, default: 0 }
|
||||||
},
|
},
|
||||||
dim4: {
|
dim4: {
|
||||||
completed: { type: Boolean, default: false },
|
completed: { type: Boolean, default: false },
|
||||||
bestScore: { type: Number, default: 0 },
|
bestScore: { type: Number, default: 0 },
|
||||||
exploredEvents: { type: Number, default: 0 }
|
exploredEvents: { type: Number, default: 0 }
|
||||||
},
|
},
|
||||||
dim5: {
|
dim5: {
|
||||||
completed: { type: Boolean, default: false },
|
completed: { type: Boolean, default: false },
|
||||||
bestScore: { type: Number, default: 0 },
|
bestScore: { type: Number, default: 0 },
|
||||||
exploredThoughts: { type: Number, default: 0 }
|
exploredThoughts: { type: Number, default: 0 }
|
||||||
}
|
}
|
||||||
}, { _id: false })
|
}, { _id: false })
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户模型
|
* 用户模型
|
||||||
*/
|
*/
|
||||||
const UserSchema = new Schema({
|
const UserSchema = new Schema({
|
||||||
// 微信用户标识
|
// 微信用户标识
|
||||||
openid: {
|
openid: {
|
||||||
type: String,
|
type: String,
|
||||||
required: false,
|
required: false,
|
||||||
unique: true,
|
unique: true,
|
||||||
sparse: true,
|
sparse: true,
|
||||||
index: true
|
index: true
|
||||||
},
|
},
|
||||||
unionid: {
|
unionid: {
|
||||||
type: String,
|
type: String,
|
||||||
index: true
|
index: true
|
||||||
},
|
},
|
||||||
|
|
||||||
// H5环境用户名密码登录
|
// H5环境用户名密码登录
|
||||||
username: {
|
username: {
|
||||||
type: String,
|
type: String,
|
||||||
unique: true,
|
unique: true,
|
||||||
sparse: true,
|
sparse: true,
|
||||||
index: true
|
index: true
|
||||||
},
|
},
|
||||||
email: {
|
email: {
|
||||||
type: String,
|
type: String,
|
||||||
unique: true,
|
unique: true,
|
||||||
sparse: true,
|
sparse: true,
|
||||||
index: true
|
index: true
|
||||||
},
|
},
|
||||||
password: {
|
password: {
|
||||||
type: String,
|
type: String,
|
||||||
select: false
|
select: false
|
||||||
},
|
},
|
||||||
|
|
||||||
// 基本信息
|
// 基本信息
|
||||||
nickName: {
|
nickName: {
|
||||||
type: String,
|
type: String,
|
||||||
default: '星辰旅行者'
|
default: '星辰旅行者'
|
||||||
},
|
},
|
||||||
avatarUrl: {
|
avatarUrl: {
|
||||||
type: String,
|
type: String,
|
||||||
default: ''
|
default: ''
|
||||||
},
|
},
|
||||||
|
|
||||||
// 探索数据
|
// 探索数据
|
||||||
exploreData: {
|
exploreData: {
|
||||||
type: ExploreDataSchema,
|
type: ExploreDataSchema,
|
||||||
default: () => ({})
|
default: () => ({})
|
||||||
},
|
},
|
||||||
|
|
||||||
// 分数(冗余字段,便于排行榜查询)
|
// 分数(冗余字段,便于排行榜查询)
|
||||||
totalScore: { type: Number, default: 0 },
|
totalScore: { type: Number, default: 0 },
|
||||||
dim1Score: { type: Number, default: 0 },
|
dim1Score: { type: Number, default: 0 },
|
||||||
dim2Score: { type: Number, default: 0 },
|
dim2Score: { type: Number, default: 0 },
|
||||||
dim3Score: { type: Number, default: 0 },
|
dim3Score: { type: Number, default: 0 },
|
||||||
dim4Score: { type: Number, default: 0 },
|
dim4Score: { type: Number, default: 0 },
|
||||||
dim5Score: { type: Number, default: 0 },
|
dim5Score: { type: Number, default: 0 },
|
||||||
|
|
||||||
// 已解锁维度(新用户默认解锁第1维度)
|
// 已解锁维度(新用户默认解锁第1维度)
|
||||||
unlockedDims: {
|
unlockedDims: {
|
||||||
type: [{ type: Number, enum: [1, 2, 3, 4, 5] }],
|
type: [{ type: Number, enum: [1, 2, 3, 4, 5] }],
|
||||||
default: [1]
|
default: [1]
|
||||||
},
|
},
|
||||||
|
|
||||||
// 商品相关
|
// 商品相关
|
||||||
ownedSkins: [{
|
ownedSkins: [{
|
||||||
type: String
|
type: String
|
||||||
}],
|
}],
|
||||||
purchasedItems: [{
|
purchasedItems: [{
|
||||||
type: String
|
type: String
|
||||||
}],
|
}],
|
||||||
|
|
||||||
// 会员状态
|
// 会员状态
|
||||||
isAdFree: {
|
isAdFree: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false
|
||||||
},
|
},
|
||||||
isSubscriber: {
|
isSubscriber: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false
|
||||||
},
|
},
|
||||||
subscribeExpiry: {
|
subscribeExpiry: {
|
||||||
type: Date
|
type: Date
|
||||||
},
|
},
|
||||||
|
|
||||||
// 收藏与成就
|
// 收藏与成就
|
||||||
collectedKnowledge: [{
|
collectedKnowledge: [{
|
||||||
type: mongoose.Schema.Types.ObjectId,
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
ref: 'Knowledge'
|
ref: 'Knowledge'
|
||||||
}],
|
}],
|
||||||
achievements: [{
|
achievements: [{
|
||||||
type: String
|
type: String
|
||||||
}],
|
}],
|
||||||
|
|
||||||
// 设置
|
// 设置
|
||||||
settings: {
|
settings: {
|
||||||
voiceEnabled: { type: Boolean, default: true },
|
voiceEnabled: { type: Boolean, default: true },
|
||||||
difficulty: {
|
difficulty: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ['easy', 'normal', 'hard'],
|
enum: ['easy', 'normal', 'hard'],
|
||||||
default: 'normal'
|
default: 'normal'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// 探索等级系统
|
// 探索等级系统
|
||||||
level: {
|
level: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 1
|
default: 1
|
||||||
},
|
},
|
||||||
levelPoints: {
|
levelPoints: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0
|
default: 0
|
||||||
},
|
},
|
||||||
|
|
||||||
// 时间戳
|
// 时间戳
|
||||||
totalPlayTime: {
|
totalPlayTime: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0
|
default: 0
|
||||||
},
|
},
|
||||||
createdAt: {
|
createdAt: {
|
||||||
type: Date,
|
type: Date,
|
||||||
default: Date.now
|
default: Date.now
|
||||||
},
|
},
|
||||||
lastLoginAt: {
|
// vpay 用户态签名必需(code2Session 返回,有过期时间,过期后重登录刷新)
|
||||||
type: Date,
|
sessionKey: { type: String, default: '' },
|
||||||
default: Date.now
|
vpayCoins: { type: Number, default: 0 },
|
||||||
},
|
lastLoginAt: {
|
||||||
updatedAt: {
|
type: Date,
|
||||||
type: Date,
|
default: Date.now
|
||||||
default: Date.now
|
},
|
||||||
}
|
updatedAt: {
|
||||||
}, {
|
type: Date,
|
||||||
timestamps: true,
|
default: Date.now
|
||||||
toJSON: { virtuals: true },
|
}
|
||||||
toObject: { virtuals: true }
|
}, {
|
||||||
})
|
timestamps: true,
|
||||||
|
toJSON: { virtuals: true },
|
||||||
// 索引
|
toObject: { virtuals: true }
|
||||||
UserSchema.index({ totalScore: -1 })
|
})
|
||||||
UserSchema.index({ dim1Score: -1 })
|
|
||||||
UserSchema.index({ dim2Score: -1 })
|
// 索引
|
||||||
UserSchema.index({ dim3Score: -1 })
|
UserSchema.index({ totalScore: -1 })
|
||||||
UserSchema.index({ dim4Score: -1 })
|
UserSchema.index({ dim1Score: -1 })
|
||||||
UserSchema.index({ dim5Score: -1 })
|
UserSchema.index({ dim2Score: -1 })
|
||||||
UserSchema.index({ createdAt: -1 })
|
UserSchema.index({ dim3Score: -1 })
|
||||||
UserSchema.index({ lastLoginAt: -1 }) // 用于活跃用户统计
|
UserSchema.index({ dim4Score: -1 })
|
||||||
|
UserSchema.index({ dim5Score: -1 })
|
||||||
// 虚拟字段:是否是新用户(24小时内注册)
|
UserSchema.index({ createdAt: -1 })
|
||||||
UserSchema.virtual('isNew').get(function() {
|
UserSchema.index({ lastLoginAt: -1 }) // 用于活跃用户统计
|
||||||
return Date.now() - this.createdAt < 24 * 60 * 60 * 1000
|
|
||||||
})
|
// 虚拟字段:是否是新用户(24小时内注册)
|
||||||
|
UserSchema.virtual('isNew').get(function() {
|
||||||
// 中间件:保存前加密密码(仅针对username/password登录)
|
return Date.now() - this.createdAt < 24 * 60 * 60 * 1000
|
||||||
UserSchema.pre('save', async function(next) {
|
})
|
||||||
if (!this.isModified('password')) {
|
|
||||||
return next()
|
// 中间件:保存前加密密码(仅针对username/password登录)
|
||||||
}
|
UserSchema.pre('save', async function(next) {
|
||||||
|
if (!this.isModified('password')) {
|
||||||
try {
|
return next()
|
||||||
const salt = await bcrypt.genSalt(10)
|
}
|
||||||
this.password = await bcrypt.hash(this.password, salt)
|
|
||||||
next()
|
try {
|
||||||
} catch (error) {
|
const salt = await bcrypt.genSalt(10)
|
||||||
next(error)
|
this.password = await bcrypt.hash(this.password, salt)
|
||||||
}
|
next()
|
||||||
})
|
} catch (error) {
|
||||||
|
next(error)
|
||||||
// 实例方法:验证密码
|
}
|
||||||
UserSchema.methods.validatePassword = async function(password) {
|
})
|
||||||
return bcrypt.compare(password, this.password)
|
|
||||||
}
|
// 实例方法:验证密码
|
||||||
|
UserSchema.methods.validatePassword = async function(password) {
|
||||||
// 实例方法:计算总分
|
return bcrypt.compare(password, this.password)
|
||||||
UserSchema.methods.calculateTotalScore = function() {
|
}
|
||||||
this.totalScore =
|
|
||||||
(this.exploreData.dim1?.bestScore || 0) +
|
// 实例方法:计算总分
|
||||||
(this.exploreData.dim2?.bestArea || 0) +
|
UserSchema.methods.calculateTotalScore = function() {
|
||||||
(this.exploreData.dim3?.bestScore || 0) +
|
this.totalScore =
|
||||||
(this.exploreData.dim4?.bestScore || 0) +
|
(this.exploreData.dim1?.bestScore || 0) +
|
||||||
(this.exploreData.dim5?.bestScore || 0)
|
(this.exploreData.dim2?.bestArea || 0) +
|
||||||
|
(this.exploreData.dim3?.bestScore || 0) +
|
||||||
// 同步维度分数
|
(this.exploreData.dim4?.bestScore || 0) +
|
||||||
this.dim1Score = this.exploreData.dim1?.bestScore || 0
|
(this.exploreData.dim5?.bestScore || 0)
|
||||||
this.dim2Score = this.exploreData.dim2?.bestArea || 0
|
|
||||||
this.dim3Score = this.exploreData.dim3?.bestScore || 0
|
// 同步维度分数
|
||||||
this.dim4Score = this.exploreData.dim4?.bestScore || 0
|
this.dim1Score = this.exploreData.dim1?.bestScore || 0
|
||||||
this.dim5Score = this.exploreData.dim5?.bestScore || 0
|
this.dim2Score = this.exploreData.dim2?.bestArea || 0
|
||||||
|
this.dim3Score = this.exploreData.dim3?.bestScore || 0
|
||||||
return this.totalScore
|
this.dim4Score = this.exploreData.dim4?.bestScore || 0
|
||||||
}
|
this.dim5Score = this.exploreData.dim5?.bestScore || 0
|
||||||
|
|
||||||
// 实例方法:计算等级
|
return this.totalScore
|
||||||
UserSchema.methods.calculateLevel = function() {
|
}
|
||||||
// 等级计算公式:基于总分和探索时长
|
|
||||||
// 基础分:每100分 = 1级
|
// 实例方法:计算等级
|
||||||
const scorePoints = Math.floor(this.totalScore / 100)
|
UserSchema.methods.calculateLevel = function() {
|
||||||
// 时长分:每1小时 = 1级
|
// 等级计算公式:基于总分和探索时长
|
||||||
const timePoints = Math.floor(this.totalPlayTime / 60)
|
// 基础分:每100分 = 1级
|
||||||
// 成就分:每个成就 = 2级
|
const scorePoints = Math.floor(this.totalScore / 100)
|
||||||
const achievementPoints = (this.achievements?.length || 0) * 2
|
// 时长分:每1小时 = 1级
|
||||||
// 收藏分:每5个收藏 = 1级
|
const timePoints = Math.floor(this.totalPlayTime / 60)
|
||||||
const collectionPoints = Math.floor((this.collectedKnowledge?.length || 0) / 5)
|
// 成就分:每个成就 = 2级
|
||||||
|
const achievementPoints = (this.achievements?.length || 0) * 2
|
||||||
this.levelPoints = scorePoints + timePoints + achievementPoints + collectionPoints
|
// 收藏分:每5个收藏 = 1级
|
||||||
|
const collectionPoints = Math.floor((this.collectedKnowledge?.length || 0) / 5)
|
||||||
// 等级阈值表
|
|
||||||
const levelThresholds = [
|
this.levelPoints = scorePoints + timePoints + achievementPoints + collectionPoints
|
||||||
0, 5, 15, 30, 50, 75, 105, 140, 180, 225,
|
|
||||||
275, 330, 390, 455, 525, 600, 680, 765, 855, 950, 1050
|
// 等级阈值表
|
||||||
]
|
const levelThresholds = [
|
||||||
|
0, 5, 15, 30, 50, 75, 105, 140, 180, 225,
|
||||||
// 计算等级
|
275, 330, 390, 455, 525, 600, 680, 765, 855, 950, 1050
|
||||||
let newLevel = 1
|
]
|
||||||
for (let i = 0; i < levelThresholds.length; i++) {
|
|
||||||
if (this.levelPoints >= levelThresholds[i]) {
|
// 计算等级
|
||||||
newLevel = i + 1
|
let newLevel = 1
|
||||||
} else {
|
for (let i = 0; i < levelThresholds.length; i++) {
|
||||||
break
|
if (this.levelPoints >= levelThresholds[i]) {
|
||||||
}
|
newLevel = i + 1
|
||||||
}
|
} else {
|
||||||
|
break
|
||||||
this.level = newLevel
|
}
|
||||||
return this.level
|
}
|
||||||
}
|
|
||||||
|
this.level = newLevel
|
||||||
// 实例方法:获取等级信息
|
return this.level
|
||||||
UserSchema.methods.getLevelInfo = function() {
|
}
|
||||||
const levelNames = [
|
|
||||||
'星辰旅者', '维度学徒', '空间探索者', '几何学者', '维度行者',
|
// 实例方法:获取等级信息
|
||||||
'时空旅人', '多维大师', '宇宙探索者', '维度掌控者', '空间主宰',
|
UserSchema.methods.getLevelInfo = function() {
|
||||||
'维度领主', '宇宙行者', '时空主宰', '维度之神', '宇宙之主',
|
const levelNames = [
|
||||||
'维度创世者', '空间造物主', '宇宙掌控者', '维度至尊', '宇宙之神'
|
'星辰旅者', '维度学徒', '空间探索者', '几何学者', '维度行者',
|
||||||
]
|
'时空旅人', '多维大师', '宇宙探索者', '维度掌控者', '空间主宰',
|
||||||
|
'维度领主', '宇宙行者', '时空主宰', '维度之神', '宇宙之主',
|
||||||
const levelThresholds = [
|
'维度创世者', '空间造物主', '宇宙掌控者', '维度至尊', '宇宙之神'
|
||||||
0, 5, 15, 30, 50, 75, 105, 140, 180, 225,
|
]
|
||||||
275, 330, 390, 455, 525, 600, 680, 765, 855, 950, 1050
|
|
||||||
]
|
const levelThresholds = [
|
||||||
|
0, 5, 15, 30, 50, 75, 105, 140, 180, 225,
|
||||||
const currentLevel = this.level || 1
|
275, 330, 390, 455, 525, 600, 680, 765, 855, 950, 1050
|
||||||
const currentPoints = this.levelPoints || 0
|
]
|
||||||
const nextLevelPoints = levelThresholds[currentLevel] || levelThresholds[levelThresholds.length - 1]
|
|
||||||
const progress = Math.min(100, Math.floor((currentPoints / nextLevelPoints) * 100))
|
const currentLevel = this.level || 1
|
||||||
|
const currentPoints = this.levelPoints || 0
|
||||||
return {
|
const nextLevelPoints = levelThresholds[currentLevel] || levelThresholds[levelThresholds.length - 1]
|
||||||
level: currentLevel,
|
const progress = Math.min(100, Math.floor((currentPoints / nextLevelPoints) * 100))
|
||||||
name: levelNames[Math.min(currentLevel - 1, levelNames.length - 1)],
|
|
||||||
points: currentPoints,
|
return {
|
||||||
nextLevelPoints: nextLevelPoints,
|
level: currentLevel,
|
||||||
progress: progress,
|
name: levelNames[Math.min(currentLevel - 1, levelNames.length - 1)],
|
||||||
totalProgress: Math.min(100, Math.floor((currentPoints / 1050) * 100))
|
points: currentPoints,
|
||||||
}
|
nextLevelPoints: nextLevelPoints,
|
||||||
}
|
progress: progress,
|
||||||
|
totalProgress: Math.min(100, Math.floor((currentPoints / 1050) * 100))
|
||||||
// 静态方法:获取排行榜
|
}
|
||||||
UserSchema.statics.getLeaderboard = function(dim = null, limit = 50) {
|
}
|
||||||
const sortField = dim ? `dim${dim}Score` : 'totalScore'
|
|
||||||
return this.find()
|
// 静态方法:获取排行榜
|
||||||
.select('openid nickName avatarUrl totalScore dim1Score dim2Score dim3Score dim4Score dim5Score unlockedDims')
|
UserSchema.statics.getLeaderboard = function(dim = null, limit = 50) {
|
||||||
.sort({ [sortField]: -1 })
|
const sortField = dim ? `dim${dim}Score` : 'totalScore'
|
||||||
.limit(limit)
|
return this.find()
|
||||||
.lean()
|
.select('openid nickName avatarUrl totalScore dim1Score dim2Score dim3Score dim4Score dim5Score unlockedDims')
|
||||||
}
|
.sort({ [sortField]: -1 })
|
||||||
|
.limit(limit)
|
||||||
// 中间件:保存前更新 updatedAt、计算总分和等级
|
.lean()
|
||||||
UserSchema.pre('save', function(next) {
|
}
|
||||||
this.updatedAt = Date.now()
|
|
||||||
this.calculateTotalScore()
|
// 中间件:保存前更新 updatedAt、计算总分和等级
|
||||||
this.calculateLevel()
|
UserSchema.pre('save', function(next) {
|
||||||
next()
|
this.updatedAt = Date.now()
|
||||||
})
|
this.calculateTotalScore()
|
||||||
|
this.calculateLevel()
|
||||||
module.exports = mongoose.model('User', UserSchema)
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
module.exports = mongoose.model('User', UserSchema)
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ router.post('/login', async (req, res) => {
|
|||||||
if (code) {
|
if (code) {
|
||||||
const sessionData = await weChatService.code2Session(code)
|
const sessionData = await weChatService.code2Session(code)
|
||||||
openid = sessionData.openid
|
openid = sessionData.openid
|
||||||
|
req.body._sessionKey = sessionData.sessionKey || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
// 方式2: 开发环境直接使用 openid (已废弃,仅用于本地调试)
|
// 方式2: 开发环境直接使用 openid (已废弃,仅用于本地调试)
|
||||||
@@ -118,6 +119,7 @@ router.post('/login', async (req, res) => {
|
|||||||
if (userInfo?.nickName) user.nickName = userInfo.nickName
|
if (userInfo?.nickName) user.nickName = userInfo.nickName
|
||||||
if (userInfo?.avatarUrl) user.avatarUrl = userInfo.avatarUrl
|
if (userInfo?.avatarUrl) user.avatarUrl = userInfo.avatarUrl
|
||||||
}
|
}
|
||||||
|
if (req.body._sessionKey) user.sessionKey = req.body._sessionKey
|
||||||
|
|
||||||
await user.save()
|
await user.save()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
const express = require('express')
|
||||||
|
const crypto = require('crypto')
|
||||||
|
const router = express.Router()
|
||||||
|
const { User, Order, AIChatQuota } = require('../models')
|
||||||
|
const ApiResponse = require('../utils/response')
|
||||||
|
const { userAuthMiddleware } = require('../middleware/auth')
|
||||||
|
const logger = require('../utils/logger')
|
||||||
|
|
||||||
|
// ===== 环境与密钥 =====
|
||||||
|
const ENV = parseInt(process.env.VPAY_ENV || '1') // 0=现网 1=沙箱
|
||||||
|
const OFFER_ID = process.env.VPAY_OFFER_ID || ''
|
||||||
|
const APPKEY = ENV === 0 ? (process.env.VPAY_APPKEY_PROD || '') : (process.env.VPAY_APPKEY_SANDBOX || '')
|
||||||
|
|
||||||
|
/** 代币名称(前端展示用) */
|
||||||
|
const COIN_NAME = '星尘'
|
||||||
|
|
||||||
|
/** 充值档位(前端传 productId → 此表映射;1:100 兑换比例下分即星尘数) */
|
||||||
|
const RECHARGE_PACKAGES = [
|
||||||
|
{ id: 'pack_600', coins: 600, priceFen: 600, label: '600 星尘' },
|
||||||
|
{ id: 'pack_1800', coins: 1800, priceFen: 1800, label: '1800 星尘' },
|
||||||
|
{ id: 'pack_5000', coins: 5000, priceFen: 5000, label: '5000 星尘' },
|
||||||
|
{ id: 'pack_12000', coins: 12000, priceFen: 12000, label: '12000 星尘' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// ===== 签名工具 =====
|
||||||
|
function hmacSha256Hex(key, data) {
|
||||||
|
return crypto.createHmac('sha256', key).update(data, 'utf8').digest('hex')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成虚拟支付拉起参数(客户端 wx.requestVirtualPayment 直接用)
|
||||||
|
* 服务端计算两个签名:
|
||||||
|
* paySig = hmac_sha256(appKey, "requestVirtualPayment&" + signData)
|
||||||
|
* signature = hmac_sha256(sessionKey, signData)
|
||||||
|
*/
|
||||||
|
function buildPayParams(user, pack, outTradeNo) {
|
||||||
|
const signData = JSON.stringify({
|
||||||
|
mode: 'coin',
|
||||||
|
offerId: OFFER_ID,
|
||||||
|
buyQuantity: pack.coins,
|
||||||
|
outTradeNo,
|
||||||
|
custom: '',
|
||||||
|
attach: JSON.stringify({ uid: String(user._id), pack: pack.id }),
|
||||||
|
ts: Math.floor(Date.now() / 1000),
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
mode: 'coin',
|
||||||
|
env: ENV,
|
||||||
|
offerId: OFFER_ID,
|
||||||
|
buyQuantity: pack.coins,
|
||||||
|
outTradeNo,
|
||||||
|
currencyType: 'CNY',
|
||||||
|
platform: 'android',
|
||||||
|
signData,
|
||||||
|
paySig: hmacSha256Hex(APPKEY, `requestVirtualPayment&${signData}`),
|
||||||
|
signature: hmacSha256Hex(user.sessionKey || '', signData),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 接口 =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询充值档位 + 当前星尘余额
|
||||||
|
* GET /api/vpay/info
|
||||||
|
*/
|
||||||
|
router.get('/info', userAuthMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const user = req.user
|
||||||
|
return ApiResponse.success(res, {
|
||||||
|
coinName: COIN_NAME,
|
||||||
|
env: ENV === 0 ? 'production' : 'sandbox',
|
||||||
|
packages: RECHARGE_PACKAGES.map(p => ({ id: p.id, coins: p.coins, priceYuan: (p.priceFen / 100).toFixed(2), label: p.label })),
|
||||||
|
balance: user.vpayCoins || 0,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('vpay info 失败:', error)
|
||||||
|
return ApiResponse.serverError(res, '获取充值信息失败')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建充值订单(返回客户端拉起支付的完整参数)
|
||||||
|
* POST /api/vpay/recharge { packageId }
|
||||||
|
*/
|
||||||
|
router.post('/recharge', userAuthMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const user = req.user
|
||||||
|
const { packageId } = req.body
|
||||||
|
const pack = RECHARGE_PACKAGES.find(p => p.id === packageId)
|
||||||
|
if (!pack) return ApiResponse.error(res, '无效的充值档位', 400)
|
||||||
|
if (!user.sessionKey) {
|
||||||
|
return ApiResponse.error(res, '登录态已过期,请重新登录后再充值', 401, { needRelogin: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
const outTradeNo = `VP${Date.now()}${crypto.randomBytes(3).toString('hex').toUpperCase()}`
|
||||||
|
|
||||||
|
// 记订单
|
||||||
|
const order = new Order({
|
||||||
|
orderNo: outTradeNo,
|
||||||
|
openid: user.openid,
|
||||||
|
userId: user._id,
|
||||||
|
productId: pack.id,
|
||||||
|
productName: pack.label,
|
||||||
|
amount: pack.priceFen / 100,
|
||||||
|
status: 'pending',
|
||||||
|
metadata: { type: 'vpay_recharge', coins: pack.coins, env: ENV },
|
||||||
|
})
|
||||||
|
await order.save()
|
||||||
|
|
||||||
|
const payParams = buildPayParams(user, pack, outTradeNo)
|
||||||
|
logger.info(`[vpay] 充值订单 ${outTradeNo} 创建 (${pack.label}, env=${ENV})`)
|
||||||
|
return ApiResponse.success(res, { orderNo: outTradeNo, payParams })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('vpay recharge 失败:', error)
|
||||||
|
return ApiResponse.serverError(res, '创建充值订单失败')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
module.exports = router
|
||||||
@@ -47,10 +47,39 @@ module.exports = function registerWxMsgRoutes(app) {
|
|||||||
}
|
}
|
||||||
const event = fields.Event || fields.event || ''
|
const event = fields.Event || fields.event || ''
|
||||||
console.log('[wx-msg] 收到推送 Event=' + event, JSON.stringify(fields).slice(0, 500))
|
console.log('[wx-msg] 收到推送 Event=' + event, JSON.stringify(fields).slice(0, 500))
|
||||||
// TODO(vpay接入):按事件分发改写用户星尘余额/发货状态
|
|
||||||
// xpay_coin_pay_notify 代币充值到账
|
// 代币充值到账:改写用户星尘余额 + 订单状态
|
||||||
// xpay_goods_deliver_notify 道具发货
|
if (event === 'xpay_coin_pay_notify') {
|
||||||
// xpay_refund_notify 退款
|
try {
|
||||||
|
const { User, Order } = require('../models')
|
||||||
|
const outTradeNo = fields.OutTradeNo || ''
|
||||||
|
const coins = parseInt(fields.BuyQuantity || fields.buyQuantity || '0')
|
||||||
|
if (outTradeNo && coins > 0) {
|
||||||
|
const order = await Order.findOne({ orderNo: outTradeNo })
|
||||||
|
if (order && order.status === 'pending') {
|
||||||
|
await Order.updateOne({ _id: order._id }, { status: 'paid', paidAt: new Date() })
|
||||||
|
await User.updateOne({ _id: order.userId }, { $inc: { vpayCoins: coins } })
|
||||||
|
console.log(`[wx-msg] 星尘充值到账: ${outTradeNo} +${coins}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { console.error('[wx-msg] 充值到账失败:', e.message) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 退款:扣回星尘
|
||||||
|
if (event === 'xpay_refund_notify') {
|
||||||
|
try {
|
||||||
|
const { User, Order } = require('../models')
|
||||||
|
const outTradeNo = fields.OutTradeNo || ''
|
||||||
|
const order = await Order.findOne({ orderNo: outTradeNo, status: 'paid' })
|
||||||
|
if (order) {
|
||||||
|
await Order.updateOne({ _id: order._id }, { status: 'refunded' })
|
||||||
|
const coins = (order.metadata || {}).coins || 0
|
||||||
|
if (coins > 0) await User.updateOne({ _id: order.userId }, { $inc: { vpayCoins: -coins } })
|
||||||
|
console.log(`[wx-msg] 星尘退款: ${outTradeNo} -${coins}`)
|
||||||
|
}
|
||||||
|
} catch (e) { console.error('[wx-msg] 退款处理失败:', e.message) }
|
||||||
|
}
|
||||||
|
|
||||||
return res.status(200).json({ ErrCode: 0, ErrMsg: '' })
|
return res.status(200).json({ ErrCode: 0, ErrMsg: '' })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[wx-msg] 处理失败:', e.message)
|
console.error('[wx-msg] 处理失败:', e.message)
|
||||||
|
|||||||
Reference in New Issue
Block a user