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 处理
|
||||||
|
|||||||
@@ -159,6 +159,9 @@ const UserSchema = new Schema({
|
|||||||
type: Date,
|
type: Date,
|
||||||
default: Date.now
|
default: Date.now
|
||||||
},
|
},
|
||||||
|
// vpay 用户态签名必需(code2Session 返回,有过期时间,过期后重登录刷新)
|
||||||
|
sessionKey: { type: String, default: '' },
|
||||||
|
vpayCoins: { type: Number, default: 0 },
|
||||||
lastLoginAt: {
|
lastLoginAt: {
|
||||||
type: Date,
|
type: Date,
|
||||||
default: Date.now
|
default: Date.now
|
||||||
|
|||||||
@@ -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