优化小程序登录流程,增加用户协议和隐私政策的勾选机制,确保用户主动同意后方可登录,符合审核要求。同时,增强错误处理逻辑,提升用户体验和系统稳定性。新增用户协议和隐私政策页面,更新相关样式以改善界面交互。
This commit is contained in:
@@ -321,21 +321,18 @@ App({
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
// 登录方法 - 获取openId用于支付
|
// 登录方法 - 获取openId用于支付(加固错误处理,避免审核报“登录报错”)
|
||||||
async login() {
|
async login() {
|
||||||
try {
|
try {
|
||||||
// 获取微信登录code
|
|
||||||
const loginRes = await new Promise((resolve, reject) => {
|
const loginRes = await new Promise((resolve, reject) => {
|
||||||
wx.login({
|
wx.login({ success: resolve, fail: reject })
|
||||||
success: resolve,
|
|
||||||
fail: reject
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
if (!loginRes || !loginRes.code) {
|
||||||
console.log('[App] 获取登录code成功')
|
console.warn('[App] wx.login 未返回 code')
|
||||||
|
wx.showToast({ title: '获取登录态失败,请重试', icon: 'none' })
|
||||||
|
return null
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
// 发送code到服务器获取openId
|
|
||||||
const res = await this.request('/api/miniprogram/login', {
|
const res = await this.request('/api/miniprogram/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data: { code: loginRes.code }
|
data: { code: loginRes.code }
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"pages/my/my",
|
"pages/my/my",
|
||||||
"pages/read/read",
|
"pages/read/read",
|
||||||
"pages/about/about",
|
"pages/about/about",
|
||||||
|
"pages/agreement/agreement",
|
||||||
|
"pages/privacy/privacy",
|
||||||
"pages/referral/referral",
|
"pages/referral/referral",
|
||||||
"pages/purchases/purchases",
|
"pages/purchases/purchases",
|
||||||
"pages/settings/settings",
|
"pages/settings/settings",
|
||||||
|
|||||||
21
miniprogram/pages/agreement/agreement.js
Normal file
21
miniprogram/pages/agreement/agreement.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* Soul创业派对 - 用户协议
|
||||||
|
* 审核要求:登录前可点击《用户协议》查看完整内容
|
||||||
|
*/
|
||||||
|
const app = getApp()
|
||||||
|
|
||||||
|
Page({
|
||||||
|
data: {
|
||||||
|
statusBarHeight: 44
|
||||||
|
},
|
||||||
|
|
||||||
|
onLoad() {
|
||||||
|
this.setData({
|
||||||
|
statusBarHeight: app.globalData.statusBarHeight || 44
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
goBack() {
|
||||||
|
wx.navigateBack()
|
||||||
|
}
|
||||||
|
})
|
||||||
1
miniprogram/pages/agreement/agreement.json
Normal file
1
miniprogram/pages/agreement/agreement.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"usingComponents":{},"navigationStyle":"custom","navigationBarTitleText":"用户协议"}
|
||||||
37
miniprogram/pages/agreement/agreement.wxml
Normal file
37
miniprogram/pages/agreement/agreement.wxml
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<!--用户协议页 - 审核要求可点击查看-->
|
||||||
|
<view class="page">
|
||||||
|
<view class="nav-bar" style="padding-top: {{statusBarHeight}}px;">
|
||||||
|
<view class="nav-back" bindtap="goBack">←</view>
|
||||||
|
<text class="nav-title">用户协议</text>
|
||||||
|
<view class="nav-placeholder"></view>
|
||||||
|
</view>
|
||||||
|
<view class="nav-placeholder" style="height: {{statusBarHeight + 44}}px;"></view>
|
||||||
|
|
||||||
|
<scroll-view class="content" scroll-y enhanced show-scrollbar>
|
||||||
|
<view class="doc-card">
|
||||||
|
<text class="doc-title">Soul创业实验 用户服务协议</text>
|
||||||
|
<text class="doc-update">更新日期:以小程序内展示为准</text>
|
||||||
|
|
||||||
|
<text class="doc-section">一、接受条款</text>
|
||||||
|
<text class="doc-p">欢迎使用 Soul创业实验 小程序。使用本服务即表示您已阅读、理解并同意受本协议约束。若不同意,请勿使用本服务。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">二、服务说明</text>
|
||||||
|
<text class="doc-p">本小程序提供《一场Soul的创业实验》等数字内容阅读、推广与相关服务。我们保留变更、中断或终止部分或全部服务的权利。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">三、用户行为规范</text>
|
||||||
|
<text class="doc-p">您应合法、合规使用本服务,不得利用本服务从事违法违规活动,不得侵犯他人权益。违规行为可能导致账号限制或追究责任。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">四、知识产权</text>
|
||||||
|
<text class="doc-p">本小程序内全部内容(包括但不限于文字、图片、音频、视频)的知识产权归本小程序或权利人所有,未经授权不得复制、传播或用于商业用途。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">五、免责与限制</text>
|
||||||
|
<text class="doc-p">在法律允许范围内,因网络、设备或不可抗力导致的服务中断或数据丢失,我们尽力减少损失但不承担超出法律规定的责任。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">六、协议变更</text>
|
||||||
|
<text class="doc-p">我们可能适时修订本协议,修订后将在小程序内公示。若您继续使用服务,即视为接受修订后的协议。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">七、联系我们</text>
|
||||||
|
<text class="doc-p">如有疑问,请通过小程序内「关于作者」或 Soul 派对房与我们联系。</text>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
</view>
|
||||||
11
miniprogram/pages/agreement/agreement.wxss
Normal file
11
miniprogram/pages/agreement/agreement.wxss
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
.page { min-height: 100vh; background: #000; }
|
||||||
|
.nav-bar { position: fixed; top: 0; left: 0; right: 0; z-index: 100; background: rgba(0,0,0,0.95); display: flex; align-items: center; justify-content: space-between; padding: 0 32rpx; height: 88rpx; }
|
||||||
|
.nav-back { width: 72rpx; height: 72rpx; background: #1c1c1e; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 32rpx; color: #fff; }
|
||||||
|
.nav-title { font-size: 36rpx; font-weight: 600; color: #00CED1; }
|
||||||
|
.nav-placeholder { width: 72rpx; }
|
||||||
|
.content { height: calc(100vh - 132rpx); padding: 32rpx; box-sizing: border-box; }
|
||||||
|
.doc-card { background: #1c1c1e; border-radius: 24rpx; padding: 40rpx; border: 2rpx solid rgba(0,206,209,0.2); }
|
||||||
|
.doc-title { font-size: 34rpx; font-weight: 700; color: #fff; display: block; margin-bottom: 16rpx; }
|
||||||
|
.doc-update { font-size: 24rpx; color: rgba(255,255,255,0.5); display: block; margin-bottom: 32rpx; }
|
||||||
|
.doc-section { font-size: 28rpx; font-weight: 600; color: #00CED1; display: block; margin: 24rpx 0 12rpx; }
|
||||||
|
.doc-p { font-size: 26rpx; color: rgba(255,255,255,0.85); line-height: 1.75; display: block; margin-bottom: 16rpx; }
|
||||||
@@ -57,6 +57,8 @@ Page({
|
|||||||
// 登录弹窗
|
// 登录弹窗
|
||||||
showLoginModal: false,
|
showLoginModal: false,
|
||||||
isLoggingIn: false,
|
isLoggingIn: false,
|
||||||
|
// 用户须主动勾选同意协议(审核要求:不得默认同意)
|
||||||
|
agreeProtocol: false,
|
||||||
|
|
||||||
// 修改昵称弹窗
|
// 修改昵称弹窗
|
||||||
showNicknameModal: false,
|
showNicknameModal: false,
|
||||||
@@ -453,9 +455,29 @@ Page({
|
|||||||
this.setData({ activeTab: tab })
|
this.setData({ activeTab: tab })
|
||||||
},
|
},
|
||||||
|
|
||||||
// 显示登录弹窗
|
// 显示登录弹窗(每次打开时协议未勾选,符合审核要求)
|
||||||
showLogin() {
|
showLogin() {
|
||||||
this.setData({ showLoginModal: true })
|
try {
|
||||||
|
this.setData({ showLoginModal: true, agreeProtocol: false })
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[My] showLogin error:', e)
|
||||||
|
this.setData({ showLoginModal: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// 切换协议勾选(用户主动勾选,非默认同意)
|
||||||
|
toggleAgree() {
|
||||||
|
this.setData({ agreeProtocol: !this.data.agreeProtocol })
|
||||||
|
},
|
||||||
|
|
||||||
|
// 打开用户协议页(审核要求:点击《用户协议》需有响应)
|
||||||
|
openUserProtocol() {
|
||||||
|
wx.navigateTo({ url: '/pages/agreement/agreement' })
|
||||||
|
},
|
||||||
|
|
||||||
|
// 打开隐私政策页(审核要求:点击《隐私政策》需有响应)
|
||||||
|
openPrivacy() {
|
||||||
|
wx.navigateTo({ url: '/pages/privacy/privacy' })
|
||||||
},
|
},
|
||||||
|
|
||||||
// 关闭登录弹窗
|
// 关闭登录弹窗
|
||||||
@@ -464,21 +486,24 @@ Page({
|
|||||||
this.setData({ showLoginModal: false })
|
this.setData({ showLoginModal: false })
|
||||||
},
|
},
|
||||||
|
|
||||||
// 微信登录
|
// 微信登录(须已勾选同意协议,且做好错误处理避免审核报错)
|
||||||
async handleWechatLogin() {
|
async handleWechatLogin() {
|
||||||
|
if (!this.data.agreeProtocol) {
|
||||||
|
wx.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
this.setData({ isLoggingIn: true })
|
this.setData({ isLoggingIn: true })
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await app.login()
|
const result = await app.login()
|
||||||
if (result) {
|
if (result) {
|
||||||
this.initUserStatus()
|
this.initUserStatus()
|
||||||
this.setData({ showLoginModal: false })
|
this.setData({ showLoginModal: false, agreeProtocol: false })
|
||||||
wx.showToast({ title: '登录成功', icon: 'success' })
|
wx.showToast({ title: '登录成功', icon: 'success' })
|
||||||
} else {
|
} else {
|
||||||
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
|
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('微信登录错误:', e)
|
console.error('[My] 微信登录错误:', e)
|
||||||
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
|
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
|
||||||
} finally {
|
} finally {
|
||||||
this.setData({ isLoggingIn: false })
|
this.setData({ isLoggingIn: false })
|
||||||
|
|||||||
@@ -270,16 +270,22 @@
|
|||||||
<text class="login-desc">登录后可购买章节、解锁更多内容</text>
|
<text class="login-desc">登录后可购买章节、解锁更多内容</text>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
class="btn-wechat"
|
class="btn-wechat {{agreeProtocol ? '' : 'btn-wechat-disabled'}}"
|
||||||
bindtap="handleWechatLogin"
|
bindtap="handleWechatLogin"
|
||||||
disabled="{{isLoggingIn}}"
|
disabled="{{isLoggingIn || !agreeProtocol}}"
|
||||||
>
|
>
|
||||||
<text class="btn-wechat-icon">微</text>
|
<text class="btn-wechat-icon">微</text>
|
||||||
<text>{{isLoggingIn ? '登录中...' : '微信快捷登录'}}</text>
|
<text>{{isLoggingIn ? '登录中...' : '微信快捷登录'}}</text>
|
||||||
</button>
|
</button>
|
||||||
<view class="login-modal-cancel" bindtap="closeLoginModal">取消</view>
|
<view class="login-modal-cancel" bindtap="closeLoginModal">取消</view>
|
||||||
|
|
||||||
<text class="login-notice">登录即表示同意《用户协议》和《隐私政策》</text>
|
<view class="login-agree-row" catchtap="toggleAgree">
|
||||||
|
<view class="agree-checkbox {{agreeProtocol ? 'agree-checked' : ''}}">{{agreeProtocol ? '✓' : ''}}</view>
|
||||||
|
<text class="agree-text">我已阅读并同意</text>
|
||||||
|
<text class="agree-link" catchtap="openUserProtocol">《用户协议》</text>
|
||||||
|
<text class="agree-text">和</text>
|
||||||
|
<text class="agree-link" catchtap="openPrivacy">《隐私政策》</text>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
|||||||
@@ -994,12 +994,43 @@
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.login-notice {
|
/* 协议勾选行(审核:用户须主动勾选,协议可点击查看) */
|
||||||
display: block;
|
.login-agree-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
margin-top: 32rpx;
|
margin-top: 32rpx;
|
||||||
font-size: 22rpx;
|
font-size: 22rpx;
|
||||||
color: rgba(255, 255, 255, 0.3);
|
color: rgba(255, 255, 255, 0.5);
|
||||||
text-align: center;
|
}
|
||||||
|
.agree-checkbox {
|
||||||
|
width: 32rpx;
|
||||||
|
height: 32rpx;
|
||||||
|
border: 2rpx solid rgba(255, 255, 255, 0.5);
|
||||||
|
border-radius: 6rpx;
|
||||||
|
margin-right: 12rpx;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 22rpx;
|
||||||
|
color: #fff;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.agree-checked {
|
||||||
|
background: #00CED1;
|
||||||
|
border-color: #00CED1;
|
||||||
|
}
|
||||||
|
.agree-text {
|
||||||
|
color: rgba(255, 255, 255, 0.6);
|
||||||
|
}
|
||||||
|
.agree-link {
|
||||||
|
color: #00CED1;
|
||||||
|
text-decoration: underline;
|
||||||
|
padding: 0 4rpx;
|
||||||
|
}
|
||||||
|
.btn-wechat-disabled {
|
||||||
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ===== 底部留白 ===== */
|
/* ===== 底部留白 ===== */
|
||||||
|
|||||||
21
miniprogram/pages/privacy/privacy.js
Normal file
21
miniprogram/pages/privacy/privacy.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* Soul创业派对 - 隐私政策
|
||||||
|
* 审核要求:登录前可点击《隐私政策》查看完整内容
|
||||||
|
*/
|
||||||
|
const app = getApp()
|
||||||
|
|
||||||
|
Page({
|
||||||
|
data: {
|
||||||
|
statusBarHeight: 44
|
||||||
|
},
|
||||||
|
|
||||||
|
onLoad() {
|
||||||
|
this.setData({
|
||||||
|
statusBarHeight: app.globalData.statusBarHeight || 44
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
goBack() {
|
||||||
|
wx.navigateBack()
|
||||||
|
}
|
||||||
|
})
|
||||||
1
miniprogram/pages/privacy/privacy.json
Normal file
1
miniprogram/pages/privacy/privacy.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"usingComponents":{},"navigationStyle":"custom","navigationBarTitleText":"隐私政策"}
|
||||||
40
miniprogram/pages/privacy/privacy.wxml
Normal file
40
miniprogram/pages/privacy/privacy.wxml
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<!--隐私政策页 - 审核要求可点击查看-->
|
||||||
|
<view class="page">
|
||||||
|
<view class="nav-bar" style="padding-top: {{statusBarHeight}}px;">
|
||||||
|
<view class="nav-back" bindtap="goBack">←</view>
|
||||||
|
<text class="nav-title">隐私政策</text>
|
||||||
|
<view class="nav-placeholder"></view>
|
||||||
|
</view>
|
||||||
|
<view class="nav-placeholder" style="height: {{statusBarHeight + 44}}px;"></view>
|
||||||
|
|
||||||
|
<scroll-view class="content" scroll-y enhanced show-scrollbar>
|
||||||
|
<view class="doc-card">
|
||||||
|
<text class="doc-title">Soul创业实验 隐私政策</text>
|
||||||
|
<text class="doc-update">更新日期:以小程序内展示为准</text>
|
||||||
|
|
||||||
|
<text class="doc-section">一、信息收集</text>
|
||||||
|
<text class="doc-p">为向您提供阅读、购买、推广与提现等服务,我们可能收集:微信昵称、头像、openId、手机号(在您授权时)、订单与收益相关数据。我们仅在法律允许及您同意的范围内收集必要信息。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">二、信息使用</text>
|
||||||
|
<text class="doc-p">所收集信息用于账号识别、订单与收益结算、客服与纠纷处理、产品优化及法律义务履行,不会用于与上述目的无关的营销或向第三方出售。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">三、信息存储与安全</text>
|
||||||
|
<text class="doc-p">数据存储在中华人民共和国境内,我们采取合理技术和管理措施保障数据安全,防止未经授权的访问、泄露或篡改。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">四、信息共享</text>
|
||||||
|
<text class="doc-p">未经您同意,我们不会将您的个人信息共享给第三方,法律法规要求或为完成支付、提现等必要合作除外(如微信支付、微信商家转账)。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">五、您的权利</text>
|
||||||
|
<text class="doc-p">您有权查询、更正、删除您的个人信息,或撤回授权。部分权限撤回可能影响相关功能使用。您可通过小程序设置或联系我们就隐私问题提出请求。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">六、未成年人</text>
|
||||||
|
<text class="doc-p">如您为未成年人,请在监护人同意下使用本服务。我们不会主动收集未成年人个人信息。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">七、政策更新</text>
|
||||||
|
<text class="doc-p">我们可能适时更新本政策,更新后将通过小程序内公示等方式通知您。继续使用即视为接受更新后的政策。</text>
|
||||||
|
|
||||||
|
<text class="doc-section">八、联系我们</text>
|
||||||
|
<text class="doc-p">如有隐私相关疑问或投诉,请通过小程序内「关于作者」或 Soul 派对房与我们联系。</text>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
</view>
|
||||||
11
miniprogram/pages/privacy/privacy.wxss
Normal file
11
miniprogram/pages/privacy/privacy.wxss
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
.page { min-height: 100vh; background: #000; }
|
||||||
|
.nav-bar { position: fixed; top: 0; left: 0; right: 0; z-index: 100; background: rgba(0,0,0,0.95); display: flex; align-items: center; justify-content: space-between; padding: 0 32rpx; height: 88rpx; }
|
||||||
|
.nav-back { width: 72rpx; height: 72rpx; background: #1c1c1e; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 32rpx; color: #fff; }
|
||||||
|
.nav-title { font-size: 36rpx; font-weight: 600; color: #00CED1; }
|
||||||
|
.nav-placeholder { width: 72rpx; }
|
||||||
|
.content { height: calc(100vh - 132rpx); padding: 32rpx; box-sizing: border-box; }
|
||||||
|
.doc-card { background: #1c1c1e; border-radius: 24rpx; padding: 40rpx; border: 2rpx solid rgba(0,206,209,0.2); }
|
||||||
|
.doc-title { font-size: 34rpx; font-weight: 700; color: #fff; display: block; margin-bottom: 16rpx; }
|
||||||
|
.doc-update { font-size: 24rpx; color: rgba(255,255,255,0.5); display: block; margin-bottom: 32rpx; }
|
||||||
|
.doc-section { font-size: 28rpx; font-weight: 600; color: #00CED1; display: block; margin: 24rpx 0 12rpx; }
|
||||||
|
.doc-p { font-size: 26rpx; color: rgba(255,255,255,0.85); line-height: 1.75; display: block; margin-bottom: 16rpx; }
|
||||||
@@ -60,6 +60,7 @@ Page({
|
|||||||
// 弹窗
|
// 弹窗
|
||||||
showShareModal: false,
|
showShareModal: false,
|
||||||
showLoginModal: false,
|
showLoginModal: false,
|
||||||
|
agreeProtocol: false,
|
||||||
showPosterModal: false,
|
showPosterModal: false,
|
||||||
isPaying: false,
|
isPaying: false,
|
||||||
isGeneratingPoster: false,
|
isGeneratingPoster: false,
|
||||||
@@ -483,29 +484,50 @@ Page({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// 显示登录弹窗
|
// 显示登录弹窗(每次打开协议未勾选,符合审核要求)
|
||||||
showLoginModal() {
|
showLoginModal() {
|
||||||
this.setData({ showLoginModal: true })
|
try {
|
||||||
|
this.setData({ showLoginModal: true, agreeProtocol: false })
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Read] showLoginModal error:', e)
|
||||||
|
this.setData({ showLoginModal: true })
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
closeLoginModal() {
|
closeLoginModal() {
|
||||||
this.setData({ showLoginModal: false })
|
this.setData({ showLoginModal: false })
|
||||||
},
|
},
|
||||||
|
|
||||||
|
toggleAgree() {
|
||||||
|
this.setData({ agreeProtocol: !this.data.agreeProtocol })
|
||||||
|
},
|
||||||
|
|
||||||
|
openUserProtocol() {
|
||||||
|
wx.navigateTo({ url: '/pages/agreement/agreement' })
|
||||||
|
},
|
||||||
|
|
||||||
|
openPrivacy() {
|
||||||
|
wx.navigateTo({ url: '/pages/privacy/privacy' })
|
||||||
|
},
|
||||||
|
|
||||||
// 从服务端刷新购买状态,避免登录后误用旧数据导致误解锁
|
// 从服务端刷新购买状态,避免登录后误用旧数据导致误解锁
|
||||||
// 【重构】微信登录(标准流程)
|
// 【重构】微信登录(须先勾选同意协议,符合审核要求)
|
||||||
async handleWechatLogin() {
|
async handleWechatLogin() {
|
||||||
|
if (!this.data.agreeProtocol) {
|
||||||
|
wx.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' })
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const result = await app.login()
|
const result = await app.login()
|
||||||
if (!result) return
|
if (!result) return
|
||||||
|
|
||||||
this.setData({ showLoginModal: false })
|
this.setData({ showLoginModal: false, agreeProtocol: false })
|
||||||
await this.onLoginSuccess()
|
await this.onLoginSuccess()
|
||||||
wx.showToast({ title: '登录成功', icon: 'success' })
|
wx.showToast({ title: '登录成功', icon: 'success' })
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[Read] 登录失败:', e)
|
console.error('[Read] 登录失败:', e)
|
||||||
wx.showToast({ title: '登录失败', icon: 'none' })
|
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -262,7 +262,7 @@
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- 登录弹窗 - 只保留微信登录 -->
|
<!-- 登录弹窗 - 须勾选同意协议,《用户协议》《隐私政策》可点击查看 -->
|
||||||
<view class="modal-overlay" wx:if="{{showLoginModal}}" bindtap="closeLoginModal">
|
<view class="modal-overlay" wx:if="{{showLoginModal}}" bindtap="closeLoginModal">
|
||||||
<view class="modal-content login-modal" catchtap="stopPropagation">
|
<view class="modal-content login-modal" catchtap="stopPropagation">
|
||||||
<view class="modal-close" bindtap="closeLoginModal">✕</view>
|
<view class="modal-close" bindtap="closeLoginModal">✕</view>
|
||||||
@@ -270,12 +270,18 @@
|
|||||||
<text class="login-title">登录 Soul创业派对</text>
|
<text class="login-title">登录 Soul创业派对</text>
|
||||||
<text class="login-desc">登录后可购买章节、解锁更多内容</text>
|
<text class="login-desc">登录后可购买章节、解锁更多内容</text>
|
||||||
|
|
||||||
<button class="btn-wechat" bindtap="handleWechatLogin">
|
<button class="btn-wechat {{agreeProtocol ? '' : 'btn-wechat-disabled'}}" bindtap="handleWechatLogin" disabled="{{!agreeProtocol}}">
|
||||||
<text class="btn-wechat-icon">微</text>
|
<text class="btn-wechat-icon">微</text>
|
||||||
<text>微信快捷登录</text>
|
<text>微信快捷登录</text>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<text class="login-notice">登录即表示同意《用户协议》和《隐私政策》</text>
|
<view class="login-agree-row" catchtap="toggleAgree">
|
||||||
|
<view class="agree-checkbox {{agreeProtocol ? 'agree-checked' : ''}}">{{agreeProtocol ? '✓' : ''}}</view>
|
||||||
|
<text class="agree-text">我已阅读并同意</text>
|
||||||
|
<text class="agree-link" catchtap="openUserProtocol">《用户协议》</text>
|
||||||
|
<text class="agree-text">和</text>
|
||||||
|
<text class="agree-link" catchtap="openPrivacy">《隐私政策》</text>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
|||||||
@@ -830,12 +830,39 @@
|
|||||||
font-size: 32rpx;
|
font-size: 32rpx;
|
||||||
}
|
}
|
||||||
|
|
||||||
.login-notice {
|
.login-agree-row {
|
||||||
font-size: 22rpx;
|
display: flex;
|
||||||
color: rgba(255, 255, 255, 0.3);
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
margin-top: 32rpx;
|
margin-top: 32rpx;
|
||||||
display: block;
|
font-size: 22rpx;
|
||||||
|
color: rgba(255, 255, 255, 0.5);
|
||||||
}
|
}
|
||||||
|
.agree-checkbox {
|
||||||
|
width: 32rpx;
|
||||||
|
height: 32rpx;
|
||||||
|
border: 2rpx solid rgba(255, 255, 255, 0.5);
|
||||||
|
border-radius: 6rpx;
|
||||||
|
margin-right: 12rpx;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 22rpx;
|
||||||
|
color: #fff;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.agree-checked {
|
||||||
|
background: #00CED1;
|
||||||
|
border-color: #00CED1;
|
||||||
|
}
|
||||||
|
.agree-text { color: rgba(255, 255, 255, 0.6); }
|
||||||
|
.agree-link {
|
||||||
|
color: #00CED1;
|
||||||
|
text-decoration: underline;
|
||||||
|
padding: 0 4rpx;
|
||||||
|
}
|
||||||
|
.btn-wechat-disabled { opacity: 0.6; }
|
||||||
|
|
||||||
/* ===== 支付中加载 ===== */
|
/* ===== 支付中加载 ===== */
|
||||||
.loading-box {
|
.loading-box {
|
||||||
|
|||||||
@@ -3,4 +3,5 @@
|
|||||||
# VITE_API_BASE_URL=http://localhost:3006
|
# VITE_API_BASE_URL=http://localhost:3006
|
||||||
VITE_API_BASE_URL=http://localhost:8080
|
VITE_API_BASE_URL=http://localhost:8080
|
||||||
# VITE_API_BASE_URL=https://soulapi.quwanzhi.com
|
# VITE_API_BASE_URL=https://soulapi.quwanzhi.com
|
||||||
|
# VITE_API_BASE_URL=https://soul.quwanzhi.com
|
||||||
|
|
||||||
|
|||||||
28
soul-admin/src/api/auth.ts
Normal file
28
soul-admin/src/api/auth.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
/**
|
||||||
|
* 管理端 JWT 本地存储(localStorage),与 soul-api JWT 鉴权配合
|
||||||
|
*/
|
||||||
|
const ADMIN_TOKEN_KEY = 'admin_token'
|
||||||
|
|
||||||
|
export function getAdminToken(): string | null {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(ADMIN_TOKEN_KEY)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setAdminToken(token: string): void {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(ADMIN_TOKEN_KEY, token)
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearAdminToken(): void {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(ADMIN_TOKEN_KEY)
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* 统一 API 请求封装
|
* 统一 API 请求封装
|
||||||
* 规则:API 路径与现网完全一致,仅通过 baseUrl 区分环境(Next 或未来 Gin)
|
* 规则:API 路径与现网完全一致,仅通过 baseUrl 区分环境(Next 或未来 Gin)
|
||||||
* 无缝切换:仅修改 VITE_API_BASE_URL 即可切换后端
|
* 鉴权:管理端使用 JWT,自动带 Authorization: Bearer <token>(token 存 localStorage)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { getAdminToken } from './auth'
|
||||||
|
|
||||||
/** 未设置环境变量时使用的默认 API 地址(零配置部署) */
|
/** 未设置环境变量时使用的默认 API 地址(零配置部署) */
|
||||||
const DEFAULT_API_BASE = 'https://soulapi.quwanzhi.com'
|
const DEFAULT_API_BASE = 'https://soulapi.quwanzhi.com'
|
||||||
|
|
||||||
@@ -24,7 +26,7 @@ export type RequestInitWithBody = RequestInit & { data?: unknown }
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 发起请求。path 为与现网一致的 API 路径(如 /api/admin、/api/orders)。
|
* 发起请求。path 为与现网一致的 API 路径(如 /api/admin、/api/orders)。
|
||||||
* 自动带上 credentials: 'include' 以支持 Cookie 鉴权(与现有 Next 一致)。
|
* 若有 admin_token(JWT)则自动带 Authorization: Bearer;credentials: 'include' 保留以兼容需 Cookie 的接口。
|
||||||
*/
|
*/
|
||||||
export async function request<T = unknown>(
|
export async function request<T = unknown>(
|
||||||
path: string,
|
path: string,
|
||||||
@@ -33,6 +35,10 @@ export async function request<T = unknown>(
|
|||||||
const { data, ...init } = options
|
const { data, ...init } = options
|
||||||
const url = apiUrl(path)
|
const url = apiUrl(path)
|
||||||
const headers = new Headers(init.headers as HeadersInit)
|
const headers = new Headers(init.headers as HeadersInit)
|
||||||
|
const token = getAdminToken()
|
||||||
|
if (token) {
|
||||||
|
headers.set('Authorization', `Bearer ${token}`)
|
||||||
|
}
|
||||||
if (data !== undefined && data !== null && !headers.has('Content-Type')) {
|
if (data !== undefined && data !== null && !headers.has('Content-Type')) {
|
||||||
headers.set('Content-Type', 'application/json')
|
headers.set('Content-Type', 'application/json')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
BookOpen,
|
BookOpen,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { get, post } from '@/api/client'
|
import { get, post } from '@/api/client'
|
||||||
|
import { clearAdminToken } from '@/api/auth'
|
||||||
|
|
||||||
const menuItems = [
|
const menuItems = [
|
||||||
{ icon: LayoutDashboard, label: '数据概览', href: '/dashboard' },
|
{ icon: LayoutDashboard, label: '数据概览', href: '/dashboard' },
|
||||||
@@ -52,7 +53,12 @@ export function AdminLayout() {
|
|||||||
}, [mounted, navigate])
|
}, [mounted, navigate])
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
await post('/api/admin/logout', {})
|
clearAdminToken()
|
||||||
|
try {
|
||||||
|
await post('/api/admin/logout', {})
|
||||||
|
} catch {
|
||||||
|
// 忽略登出接口失败,本地已清 token
|
||||||
|
}
|
||||||
navigate('/login', { replace: true })
|
navigate('/login', { replace: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { Lock, User, ShieldCheck } from 'lucide-react'
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { post } from '@/api/client'
|
import { post } from '@/api/client'
|
||||||
|
import { setAdminToken } from '@/api/auth'
|
||||||
|
|
||||||
export function LoginPage() {
|
export function LoginPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@@ -16,11 +17,16 @@ export function LoginPage() {
|
|||||||
setError('')
|
setError('')
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
const data = await post<{ success?: boolean; error?: string }>('/api/admin', {
|
const data = await post<{
|
||||||
|
success?: boolean
|
||||||
|
error?: string
|
||||||
|
token?: string
|
||||||
|
}>('/api/admin', {
|
||||||
username: username.trim(),
|
username: username.trim(),
|
||||||
password,
|
password,
|
||||||
})
|
})
|
||||||
if (data?.success !== false) {
|
if (data?.success !== false && data?.token) {
|
||||||
|
setAdminToken(data.token)
|
||||||
navigate('/dashboard', { replace: true })
|
navigate('/dashboard', { replace: true })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ require (
|
|||||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.2 // indirect
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
github.com/jinzhu/now v1.1.5 // indirect
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ
|
|||||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
|||||||
68
soul-api/internal/auth/adminjwt.go
Normal file
68
soul-api/internal/auth/adminjwt.go
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
// Package auth 管理端 JWT:签发与校验,使用 Authorization: Bearer <token>
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const adminJWTExpire = 7 * 24 * time.Hour // 7 天
|
||||||
|
|
||||||
|
// AdminClaims 管理端 JWT 载荷
|
||||||
|
type AdminClaims struct {
|
||||||
|
jwt.RegisteredClaims
|
||||||
|
Username string `json:"username"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IssueAdminJWT 签发管理端 JWT,使用 ADMIN_SESSION_SECRET 签名
|
||||||
|
func IssueAdminJWT(secret, username string) (string, error) {
|
||||||
|
now := time.Now()
|
||||||
|
claims := AdminClaims{
|
||||||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
|
ExpiresAt: jwt.NewNumericDate(now.Add(adminJWTExpire)),
|
||||||
|
IssuedAt: jwt.NewNumericDate(now),
|
||||||
|
Subject: "admin",
|
||||||
|
},
|
||||||
|
Username: username,
|
||||||
|
Role: "admin",
|
||||||
|
}
|
||||||
|
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
return tok.SignedString([]byte(secret))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseAdminJWT 校验并解析 JWT,返回 claims;无效或过期返回 nil, false
|
||||||
|
func ParseAdminJWT(tokenString, secret string) (*AdminClaims, bool) {
|
||||||
|
if tokenString == "" || secret == "" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
tok, err := jwt.ParseWithClaims(tokenString, &AdminClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||||
|
return []byte(secret), nil
|
||||||
|
}, jwt.WithValidMethods([]string{"HS256"}))
|
||||||
|
if err != nil || !tok.Valid {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
claims, ok := tok.Claims.(*AdminClaims)
|
||||||
|
if !ok || claims.Username == "" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return claims, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAdminJWTFromRequest 从请求中读取 JWT:优先 Authorization: Bearer <token>,其次 Cookie admin_session(兼容旧端)
|
||||||
|
func GetAdminJWTFromRequest(r *http.Request) string {
|
||||||
|
// 1. Authorization: Bearer <token>
|
||||||
|
ah := r.Header.Get("Authorization")
|
||||||
|
if strings.HasPrefix(ah, "Bearer ") {
|
||||||
|
return strings.TrimSpace(ah[7:])
|
||||||
|
}
|
||||||
|
// 2. Cookie(兼容:若值为 JWT 格式则可用)
|
||||||
|
c, err := r.Cookie(adminCookieName)
|
||||||
|
if err != nil || c == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(c.Value)
|
||||||
|
}
|
||||||
@@ -53,6 +53,14 @@ func AdminCookieName() string { return adminCookieName }
|
|||||||
// MaxAgeSec 返回 session 有效秒数
|
// MaxAgeSec 返回 session 有效秒数
|
||||||
func MaxAgeSec() int { return maxAgeSec }
|
func MaxAgeSec() int { return maxAgeSec }
|
||||||
|
|
||||||
|
// SetCookieHeaderValue 返回完整的 Set-Cookie 头内容(含 SameSite=None; Secure,供跨站时携带 Cookie)
|
||||||
|
func SetCookieHeaderValue(token string, maxAge int) string {
|
||||||
|
if maxAge <= 0 {
|
||||||
|
return adminCookieName + "=; Path=/; Max-Age=0; HttpOnly; SameSite=None; Secure"
|
||||||
|
}
|
||||||
|
return adminCookieName + "=" + token + "; Path=/; Max-Age=" + strconv.Itoa(maxAge) + "; HttpOnly; SameSite=None; Secure"
|
||||||
|
}
|
||||||
|
|
||||||
// GetAdminTokenFromRequest 从请求 Cookie 中读取 admin_session
|
// GetAdminTokenFromRequest 从请求 Cookie 中读取 admin_session
|
||||||
func GetAdminTokenFromRequest(r *http.Request) string {
|
func GetAdminTokenFromRequest(r *http.Request) string {
|
||||||
c, err := r.Cookie(adminCookieName)
|
c, err := r.Cookie(adminCookieName)
|
||||||
|
|||||||
@@ -9,19 +9,18 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AdminCheck GET /api/admin 鉴权检查(与 next-project 一致:校验 admin_session cookie,已登录返回 success 或概览占位)
|
// AdminCheck GET /api/admin 鉴权检查(JWT:Authorization Bearer 或 Cookie),已登录返回 success 或概览占位
|
||||||
func AdminCheck(c *gin.Context) {
|
func AdminCheck(c *gin.Context) {
|
||||||
cfg := config.Get()
|
cfg := config.Get()
|
||||||
if cfg == nil {
|
if cfg == nil {
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token := auth.GetAdminTokenFromRequest(c.Request)
|
token := auth.GetAdminJWTFromRequest(c.Request)
|
||||||
if !auth.VerifyAdminToken(token, cfg.AdminSessionSecret) {
|
if _, ok := auth.ParseAdminJWT(token, cfg.AdminSessionSecret); !ok {
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 与 next 一致:返回 success,可选带概览占位供前端扩展
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": true,
|
"success": true,
|
||||||
"content": gin.H{
|
"content": gin.H{
|
||||||
@@ -40,7 +39,7 @@ func AdminCheck(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdminLogin POST /api/admin 登录(与 next-project 一致:校验 ADMIN_USERNAME/PASSWORD,写 admin_session cookie)
|
// AdminLogin POST /api/admin 登录(校验 ADMIN_USERNAME/PASSWORD,返回 JWT,前端存 token 并带 Authorization: Bearer)
|
||||||
func AdminLogin(c *gin.Context) {
|
func AdminLogin(c *gin.Context) {
|
||||||
cfg := config.Get()
|
cfg := config.Get()
|
||||||
if cfg == nil {
|
if cfg == nil {
|
||||||
@@ -61,19 +60,22 @@ func AdminLogin(c *gin.Context) {
|
|||||||
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "用户名或密码错误"})
|
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "用户名或密码错误"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token := auth.CreateAdminToken(cfg.AdminSessionSecret)
|
token, err := auth.IssueAdminJWT(cfg.AdminSessionSecret, username)
|
||||||
c.SetCookie(auth.AdminCookieName(), token, auth.MaxAgeSec(), "/", "", false, true)
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "签发失败"})
|
||||||
|
return
|
||||||
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": true,
|
"success": true,
|
||||||
|
"token": token,
|
||||||
"user": gin.H{
|
"user": gin.H{
|
||||||
"id": "admin", "username": cfg.AdminUsername, "role": "admin", "name": "卡若",
|
"id": "admin", "username": cfg.AdminUsername, "role": "admin", "name": "卡若",
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdminLogout POST /api/admin/logout 清除 admin_session cookie
|
// AdminLogout POST /api/admin/logout 服务端无状态,仅返回成功;前端需清除本地 token
|
||||||
func AdminLogout(c *gin.Context) {
|
func AdminLogout(c *gin.Context) {
|
||||||
c.SetCookie(auth.AdminCookieName(), "", -1, "/", "", false, true)
|
|
||||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -149,9 +149,7 @@ func AdminWithdrawalsAction(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 调用微信转账接口;未初始化时仅标记为已打款(线下打款)
|
// 调用微信转账接口(FundApp 单笔发起转账,与 商家转账.md 示例一致)
|
||||||
outBatchNo := wechat.GenerateTransferBatchNo()
|
|
||||||
outDetailNo := wechat.GenerateTransferDetailNo()
|
|
||||||
remark := "提现"
|
remark := "提现"
|
||||||
if w.Remark != nil && *w.Remark != "" {
|
if w.Remark != nil && *w.Remark != "" {
|
||||||
remark = *w.Remark
|
remark = *w.Remark
|
||||||
@@ -161,26 +159,21 @@ func AdminWithdrawalsAction(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "提现金额异常"})
|
c.JSON(http.StatusOK, gin.H{"success": false, "error": "提现金额异常"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 微信批次备注最多 32 字符,用简短文案避免超长
|
outBillNo := w.ID // 商户单号,回调时 out_bill_no 即此值,用于更新该条提现
|
||||||
batchRemark := fmt.Sprintf("提现 %.2f 元", w.Amount)
|
params := wechat.FundAppTransferParams{
|
||||||
if len([]rune(batchRemark)) > 32 {
|
OutBillNo: outBillNo,
|
||||||
batchRemark = "用户提现"
|
OpenID: openID,
|
||||||
}
|
Amount: amountFen,
|
||||||
params := wechat.TransferParams{
|
Remark: remark,
|
||||||
OutBatchNo: outBatchNo,
|
NotifyURL: "", // 由 wechat 包从配置读取 WechatTransferURL
|
||||||
OutDetailNo: outDetailNo,
|
TransferSceneId: "1005",
|
||||||
OpenID: openID,
|
|
||||||
Amount: amountFen,
|
|
||||||
Remark: remark,
|
|
||||||
BatchName: "用户提现",
|
|
||||||
BatchRemark: batchRemark,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := wechat.InitiateTransfer(params)
|
result, err := wechat.InitiateTransferByFundApp(params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errMsg := err.Error()
|
errMsg := err.Error()
|
||||||
fmt.Printf("[AdminWithdrawals] 发起转账失败 id=%s: %s(微信侧不会产生批次记录)\n", body.ID, errMsg)
|
fmt.Printf("[AdminWithdrawals] 发起转账失败 id=%s: %s\n", body.ID, errMsg)
|
||||||
// 未初始化或未配置转账:仅标记为已打款并提示线下处理(与 transfer 包返回文案一致)
|
// 未初始化或未配置转账:仅标记为已打款并提示线下处理
|
||||||
if errMsg == "支付/转账未初始化,请先调用 wechat.Init" || errMsg == "转账客户端未初始化" {
|
if errMsg == "支付/转账未初始化,请先调用 wechat.Init" || errMsg == "转账客户端未初始化" {
|
||||||
_ = db.Model(&w).Updates(map[string]interface{}{
|
_ = db.Model(&w).Updates(map[string]interface{}{
|
||||||
"status": "success",
|
"status": "success",
|
||||||
@@ -192,7 +185,7 @@ func AdminWithdrawalsAction(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 其他打款失败(含调用腾讯接口失败):记失败原因
|
// 微信接口报错或其它失败:把微信/具体原因返回给管理端展示,不返回「微信处理中」
|
||||||
failMsg := errMsg
|
failMsg := errMsg
|
||||||
_ = db.Model(&w).Updates(map[string]interface{}{
|
_ = db.Model(&w).Updates(map[string]interface{}{
|
||||||
"status": "failed",
|
"status": "failed",
|
||||||
@@ -200,6 +193,23 @@ func AdminWithdrawalsAction(c *gin.Context) {
|
|||||||
"error_message": failMsg,
|
"error_message": failMsg,
|
||||||
"processed_at": now,
|
"processed_at": now,
|
||||||
}).Error
|
}).Error
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": false,
|
||||||
|
"error": "发起打款失败",
|
||||||
|
"message": failMsg, // 管理端直接展示微信报错信息(如 IP 白名单、参数错误等)
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 防护:微信未返回商户单号时也按失败返回,避免管理端显示「已发起打款」却无单号
|
||||||
|
if result.OutBillNo == "" {
|
||||||
|
failMsg := "微信未返回商户单号,请检查商户平台(如 IP 白名单)或查看服务端日志"
|
||||||
|
_ = db.Model(&w).Updates(map[string]interface{}{
|
||||||
|
"status": "failed",
|
||||||
|
"fail_reason": failMsg,
|
||||||
|
"error_message": failMsg,
|
||||||
|
"processed_at": now,
|
||||||
|
}).Error
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": false,
|
"success": false,
|
||||||
"error": "发起打款失败",
|
"error": "发起打款失败",
|
||||||
@@ -208,28 +218,26 @@ func AdminWithdrawalsAction(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 打款已受理,更新为处理中并保存商家批次/明细单号及微信批次号
|
// 打款已受理(FundApp 单笔),更新为处理中并保存商户单号、微信转账单号
|
||||||
fmt.Printf("[AdminWithdrawals] 微信已受理 id=%s out_batch_no=%s batch_id=%s(商户后台「商家转账到零钱」可凭商家批次单号查询)\n", body.ID, result.OutBatchNo, result.BatchID)
|
fmt.Printf("[AdminWithdrawals] 微信已受理 id=%s out_bill_no=%s transfer_bill_no=%s\n", body.ID, result.OutBillNo, result.TransferBillNo)
|
||||||
processingStatus := "processing"
|
processingStatus := "processing"
|
||||||
batchID := result.BatchID
|
|
||||||
if err := db.Model(&w).Updates(map[string]interface{}{
|
if err := db.Model(&w).Updates(map[string]interface{}{
|
||||||
"status": processingStatus,
|
"status": processingStatus,
|
||||||
"batch_no": outBatchNo,
|
"detail_no": result.OutBillNo, // 回调用 out_bill_no 匹配此字段
|
||||||
"detail_no": outDetailNo,
|
"batch_no": result.OutBillNo, // 单笔无批次,存同一单号便于查询
|
||||||
"batch_id": batchID,
|
"batch_id": result.TransferBillNo,
|
||||||
"processed_at": now,
|
"processed_at": now,
|
||||||
}).Error; err != nil {
|
}).Error; err != nil {
|
||||||
fmt.Printf("[AdminWithdrawals] 更新提现状态失败 id=%s: %v\n", body.ID, err)
|
fmt.Printf("[AdminWithdrawals] 更新提现状态失败 id=%s: %v\n", body.ID, err)
|
||||||
c.JSON(http.StatusOK, gin.H{"success": false, "error": "更新状态失败: " + err.Error()})
|
c.JSON(http.StatusOK, gin.H{"success": false, "error": "更新状态失败: " + err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 始终返回 out_batch_no 便于追踪;batch_id 为微信返回,可能为空
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": true,
|
"success": true,
|
||||||
"message": "已发起打款,微信处理中",
|
"message": "已发起打款,微信处理中",
|
||||||
"data": gin.H{
|
"data": gin.H{
|
||||||
"batch_id": batchID,
|
"out_bill_no": result.OutBillNo,
|
||||||
"out_batch_no": outBatchNo,
|
"transfer_bill_no": result.TransferBillNo,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
@@ -275,20 +283,29 @@ func AdminWithdrawalsSync(c *gin.Context) {
|
|||||||
if w.DetailNo != nil {
|
if w.DetailNo != nil {
|
||||||
detailNo = *w.DetailNo
|
detailNo = *w.DetailNo
|
||||||
}
|
}
|
||||||
if batchNo == "" || detailNo == "" {
|
if detailNo == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
res, err := wechat.QueryTransfer(batchNo, detailNo)
|
var status, failReason string
|
||||||
if err != nil {
|
// FundApp 单笔:batch_no == detail_no 时用商户单号查询
|
||||||
continue
|
if batchNo == detailNo {
|
||||||
}
|
state, _, fail, err := wechat.QueryTransferByOutBill(detailNo)
|
||||||
status := ""
|
if err != nil {
|
||||||
if s, ok := res["detail_status"].(string); ok {
|
continue
|
||||||
status = s
|
}
|
||||||
}
|
status = state
|
||||||
failReason := ""
|
failReason = fail
|
||||||
if s, ok := res["fail_reason"].(string); ok {
|
} else {
|
||||||
failReason = s
|
res, err := wechat.QueryTransfer(batchNo, detailNo)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if s, ok := res["detail_status"].(string); ok {
|
||||||
|
status = s
|
||||||
|
}
|
||||||
|
if s, ok := res["fail_reason"].(string); ok {
|
||||||
|
failReason = s
|
||||||
|
}
|
||||||
}
|
}
|
||||||
up := map[string]interface{}{"processed_at": now}
|
up := map[string]interface{}{"processed_at": now}
|
||||||
switch status {
|
switch status {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AdminAuth 管理端鉴权:校验 admin_session cookie 签名与过期(与 next-project 一致),未登录返回 401
|
// AdminAuth 管理端鉴权:校验 JWT(Authorization: Bearer 或 Cookie admin_session),未登录返回 401
|
||||||
func AdminAuth() gin.HandlerFunc {
|
func AdminAuth() gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
cfg := config.Get()
|
cfg := config.Get()
|
||||||
@@ -17,8 +17,8 @@ func AdminAuth() gin.HandlerFunc {
|
|||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token := auth.GetAdminTokenFromRequest(c.Request)
|
token := auth.GetAdminJWTFromRequest(c.Request)
|
||||||
if !auth.VerifyAdminToken(token, cfg.AdminSessionSecret) {
|
if _, ok := auth.ParseAdminJWT(token, cfg.AdminSessionSecret); !ok {
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"soul-api/internal/config"
|
"soul-api/internal/config"
|
||||||
|
|
||||||
"github.com/ArtisanCloud/PowerLibs/v3/object"
|
"github.com/ArtisanCloud/PowerLibs/v3/object"
|
||||||
|
fundAppRequest "github.com/ArtisanCloud/PowerWeChat/v3/src/payment/fundApp/request"
|
||||||
"github.com/ArtisanCloud/PowerWeChat/v3/src/payment/transfer/request"
|
"github.com/ArtisanCloud/PowerWeChat/v3/src/payment/transfer/request"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -136,3 +137,83 @@ func GenerateTransferDetailNo() string {
|
|||||||
random := now.UnixNano() % 1000000
|
random := now.UnixNano() % 1000000
|
||||||
return fmt.Sprintf("WDD%s%06d", timestamp, random)
|
return fmt.Sprintf("WDD%s%06d", timestamp, random)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FundAppTransferParams 单笔转账(FundApp 发起转账)参数
|
||||||
|
type FundAppTransferParams struct {
|
||||||
|
OutBillNo string // 商户单号(唯一,回调时 out_bill_no 即此值,建议存到 withdrawal.detail_no)
|
||||||
|
OpenID string
|
||||||
|
UserName string // 可选
|
||||||
|
Amount int // 分
|
||||||
|
Remark string
|
||||||
|
NotifyURL string
|
||||||
|
TransferSceneId string // 可选,如 "1005"
|
||||||
|
}
|
||||||
|
|
||||||
|
// FundAppTransferResult 单笔转账结果
|
||||||
|
type FundAppTransferResult struct {
|
||||||
|
OutBillNo string
|
||||||
|
TransferBillNo string
|
||||||
|
State string
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitiateTransferByFundApp 发起商家转账到零钱(PowerWeChat FundApp.TransferBills 单笔接口)
|
||||||
|
// 与 TransferBatch 不同,此为 /v3/fund-app/mch-transfer/transfer-bills 单笔发起,回调仍为 MCHTRANSFER.BILL.FINISHED,解密后 out_bill_no 即本接口传入的 OutBillNo
|
||||||
|
func InitiateTransferByFundApp(params FundAppTransferParams) (*FundAppTransferResult, error) {
|
||||||
|
if paymentApp == nil || paymentApp.FundApp == nil {
|
||||||
|
return nil, fmt.Errorf("支付/转账未初始化,请先调用 wechat.Init")
|
||||||
|
}
|
||||||
|
req := &fundAppRequest.RequestTransferBills{
|
||||||
|
Appid: cfg.WechatAppID,
|
||||||
|
OutBillNo: params.OutBillNo,
|
||||||
|
TransferSceneId: params.TransferSceneId,
|
||||||
|
Openid: params.OpenID,
|
||||||
|
UserName: params.UserName,
|
||||||
|
TransferAmount: params.Amount,
|
||||||
|
TransferRemark: params.Remark,
|
||||||
|
NotifyUrl: params.NotifyURL,
|
||||||
|
}
|
||||||
|
if req.NotifyUrl == "" && cfg.WechatTransferURL != "" {
|
||||||
|
req.NotifyUrl = cfg.WechatTransferURL
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
resp, err := paymentApp.FundApp.TransferBills(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("发起转账失败: %w", err)
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return nil, fmt.Errorf("转账返回为空")
|
||||||
|
}
|
||||||
|
// 微信返回 4xx 时 body 可能被解析到 resp,需根据 code 或 out_bill_no 判断是否成功
|
||||||
|
if resp.Code != "" {
|
||||||
|
msg := resp.Message
|
||||||
|
if msg == "" {
|
||||||
|
msg = resp.Code
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("微信接口报错: %s", msg)
|
||||||
|
}
|
||||||
|
if resp.OutBillNo == "" {
|
||||||
|
return nil, fmt.Errorf("微信未返回商户单号,可能请求被拒绝(如IP未加入白名单)")
|
||||||
|
}
|
||||||
|
result := &FundAppTransferResult{
|
||||||
|
OutBillNo: resp.OutBillNo,
|
||||||
|
TransferBillNo: resp.TransferBillNo,
|
||||||
|
State: resp.State,
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryTransferByOutBill 按商户单号查询单笔转账结果(FundApp 接口,用于 sync)
|
||||||
|
func QueryTransferByOutBill(outBillNo string) (state, transferBillNo, failReason string, err error) {
|
||||||
|
if paymentApp == nil || paymentApp.FundApp == nil {
|
||||||
|
return "", "", "", fmt.Errorf("支付/转账未初始化")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
resp, err := paymentApp.FundApp.QueryOutBill(ctx, outBillNo)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", "", err
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
return "", "", "", nil
|
||||||
|
}
|
||||||
|
return resp.State, resp.TransferBillNo, resp.FailReason, nil
|
||||||
|
}
|
||||||
|
|||||||
Binary file not shown.
@@ -1 +0,0 @@
|
|||||||
exit status 1
|
|
||||||
Binary file not shown.
@@ -74,3 +74,5 @@
|
|||||||
{"level":"debug","timestamp":"2026-02-10T12:08:29+08:00","caller":"kernel/baseClient.go:459","content":"------------------response content:HTTP/1.1 403 Forbidden\r\nContent-Length: 171\r\nCache-Control: no-cache, must-revalidate\r\nConnection: keep-alive\r\nContent-Language: zh-CN\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 10 Feb 2026 04:08:29 GMT\r\nKeep-Alive: timeout=8\r\nRequest-Id: 08BDDEAACC06109D0518FFD6BCA80120833328B353-268561072\r\nServer: nginx\r\nWechatpay-Nonce: 0c9b955af9117d9b1af03144d0447beb\r\nWechatpay-Serial: 5F2543BF58239A4EB68FA4433DF1438A88B34B16\r\nWechatpay-Signature: kNG2ssMabq8glay+pAo+RW1dX/ehzRBF38SeqoPTNUaEHJZ5R0mOg3FixQiKs8oihZUJr3fRrhIEPObZvNSLsZiCJpTXwFUtW4GJDrHOjXX+/ds/sW84n5EkWgDPkkqZkwdFlB/GDXfcxYRLudneIkshu7pNLXgQKphd6TvNg4duyjtfdhmNb5AtTaWHeryAqTgyY8wuNpVy5eIk3TN04wDQ2Ze0YfbkpTdco14uP56If/tMu8l7U7NVffx2QKPt36+CmO247sLrQv7dvXgUtrNerMdKK79+OhWlR0Pi7Cbzbtz4ZSMSPYT5qUw6D9nvcBLNIGp7q/hRaY6FL5rghQ==\r\nWechatpay-Signature-Type: WECHATPAY2-SHA256-RSA2048\r\nWechatpay-Timestamp: 1770696509\r\nX-Content-Type-Options: nosniff\r\n\r\n{\"code\":\"NO_AUTH\",\"message\":\"当前商户号接入升级版本功能,暂不支持使用升级前功能,请在产品中心-商家转账-前往功能查看接口文档\"}"}
|
{"level":"debug","timestamp":"2026-02-10T12:08:29+08:00","caller":"kernel/baseClient.go:459","content":"------------------response content:HTTP/1.1 403 Forbidden\r\nContent-Length: 171\r\nCache-Control: no-cache, must-revalidate\r\nConnection: keep-alive\r\nContent-Language: zh-CN\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 10 Feb 2026 04:08:29 GMT\r\nKeep-Alive: timeout=8\r\nRequest-Id: 08BDDEAACC06109D0518FFD6BCA80120833328B353-268561072\r\nServer: nginx\r\nWechatpay-Nonce: 0c9b955af9117d9b1af03144d0447beb\r\nWechatpay-Serial: 5F2543BF58239A4EB68FA4433DF1438A88B34B16\r\nWechatpay-Signature: kNG2ssMabq8glay+pAo+RW1dX/ehzRBF38SeqoPTNUaEHJZ5R0mOg3FixQiKs8oihZUJr3fRrhIEPObZvNSLsZiCJpTXwFUtW4GJDrHOjXX+/ds/sW84n5EkWgDPkkqZkwdFlB/GDXfcxYRLudneIkshu7pNLXgQKphd6TvNg4duyjtfdhmNb5AtTaWHeryAqTgyY8wuNpVy5eIk3TN04wDQ2Ze0YfbkpTdco14uP56If/tMu8l7U7NVffx2QKPt36+CmO247sLrQv7dvXgUtrNerMdKK79+OhWlR0Pi7Cbzbtz4ZSMSPYT5qUw6D9nvcBLNIGp7q/hRaY6FL5rghQ==\r\nWechatpay-Signature-Type: WECHATPAY2-SHA256-RSA2048\r\nWechatpay-Timestamp: 1770696509\r\nX-Content-Type-Options: nosniff\r\n\r\n{\"code\":\"NO_AUTH\",\"message\":\"当前商户号接入升级版本功能,暂不支持使用升级前功能,请在产品中心-商家转账-前往功能查看接口文档\"}"}
|
||||||
{"level":"debug","timestamp":"2026-02-10T12:08:49+08:00","caller":"kernel/baseClient.go:457","content":"POST https://api.mch.weixin.qq.com/v3/transfer/batches request header: { Content-Type:application/jsonAuthorization:WECHATPAY2-SHA256-RSA2048 mchid=\"1318592501\",nonce_str=\"njxELaEQZjek7jnMN7D9vrPUnJSfgyMw\",timestamp=\"1770696527\",serial_no=\"4A1DB62CD5C9BE0B6FC51C30621D6F99686E75C5\",signature=\"EXsdVY0hMIES02Q4tEAh0RESMgHU7jQVcvTmEh7E0vvSZqXXL5h0eko+lShUViCKF4bucVIcYxv6oc5wxy0J46ibDMejmXgst3nJTNfBy0YT7OkD4menLuEIuy/gb8KzLaFqkXfdIzJZn8v/hdPYxBFQIdzkVU/hGzq4GUbrc2Nz8ePjo75vGBHTeY0mZiuOA5MkLSQu23BT1NCaktgfF8/8HRTPeYqkTmjBNPeBjgRJKgB0WnzSwOV3QnWa5pBcdNM31LaO60aP6cXvXdAfEagKyMpNEy2ts9ELcrc5TOao6uhqo4woG/FCslMErpq8V7rc+wl8gaE6lCY8X02xaA==\"Accept:*/*} request body:"}
|
{"level":"debug","timestamp":"2026-02-10T12:08:49+08:00","caller":"kernel/baseClient.go:457","content":"POST https://api.mch.weixin.qq.com/v3/transfer/batches request header: { Content-Type:application/jsonAuthorization:WECHATPAY2-SHA256-RSA2048 mchid=\"1318592501\",nonce_str=\"njxELaEQZjek7jnMN7D9vrPUnJSfgyMw\",timestamp=\"1770696527\",serial_no=\"4A1DB62CD5C9BE0B6FC51C30621D6F99686E75C5\",signature=\"EXsdVY0hMIES02Q4tEAh0RESMgHU7jQVcvTmEh7E0vvSZqXXL5h0eko+lShUViCKF4bucVIcYxv6oc5wxy0J46ibDMejmXgst3nJTNfBy0YT7OkD4menLuEIuy/gb8KzLaFqkXfdIzJZn8v/hdPYxBFQIdzkVU/hGzq4GUbrc2Nz8ePjo75vGBHTeY0mZiuOA5MkLSQu23BT1NCaktgfF8/8HRTPeYqkTmjBNPeBjgRJKgB0WnzSwOV3QnWa5pBcdNM31LaO60aP6cXvXdAfEagKyMpNEy2ts9ELcrc5TOao6uhqo4woG/FCslMErpq8V7rc+wl8gaE6lCY8X02xaA==\"Accept:*/*} request body:"}
|
||||||
{"level":"debug","timestamp":"2026-02-10T12:08:49+08:00","caller":"kernel/baseClient.go:459","content":"------------------response content:HTTP/1.1 403 Forbidden\r\nContent-Length: 171\r\nCache-Control: no-cache, must-revalidate\r\nConnection: keep-alive\r\nContent-Language: zh-CN\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 10 Feb 2026 04:08:49 GMT\r\nKeep-Alive: timeout=8\r\nRequest-Id: 08D1DEAACC06102B18FFD6BCA80120AA1928EBB404-268561072\r\nServer: nginx\r\nWechatpay-Nonce: 6c965e3c5aca952b9666dbccc6881923\r\nWechatpay-Serial: 5F2543BF58239A4EB68FA4433DF1438A88B34B16\r\nWechatpay-Signature: KKjTWimPKOSVdM/MzuPt3oAxtq3Cy2lr3ZqFXByMmgs3lovRianNEmtwmOi5EGtyo4TbdbUVpzObLUepZGfTIG7Cz8U1cnGLmqxfZxgSyRIatf5OVGYIh5RIwYrkqFdJaN/zcdjYOc73N8FWYn5+bgY51D6aD27AWbPwA7nYNJB4rKmH2QRR9ZuI1kuwDob2ezKWgzV8pkU3DxRSPP/G+BM/HINzurl04/bjAfAtst9JynlPfO61EmEEUCILSpBbKn9dSzEIq2YSz5SxIExv24fhUJ0pjcjvVZo+O0Ddx9vrkNDNSPXao83zqiZTrQkix2vDAEIc6r5SsLCyaGwaTA==\r\nWechatpay-Signature-Type: WECHATPAY2-SHA256-RSA2048\r\nWechatpay-Timestamp: 1770696529\r\nX-Content-Type-Options: nosniff\r\n\r\n{\"code\":\"NO_AUTH\",\"message\":\"当前商户号接入升级版本功能,暂不支持使用升级前功能,请在产品中心-商家转账-前往功能查看接口文档\"}"}
|
{"level":"debug","timestamp":"2026-02-10T12:08:49+08:00","caller":"kernel/baseClient.go:459","content":"------------------response content:HTTP/1.1 403 Forbidden\r\nContent-Length: 171\r\nCache-Control: no-cache, must-revalidate\r\nConnection: keep-alive\r\nContent-Language: zh-CN\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 10 Feb 2026 04:08:49 GMT\r\nKeep-Alive: timeout=8\r\nRequest-Id: 08D1DEAACC06102B18FFD6BCA80120AA1928EBB404-268561072\r\nServer: nginx\r\nWechatpay-Nonce: 6c965e3c5aca952b9666dbccc6881923\r\nWechatpay-Serial: 5F2543BF58239A4EB68FA4433DF1438A88B34B16\r\nWechatpay-Signature: KKjTWimPKOSVdM/MzuPt3oAxtq3Cy2lr3ZqFXByMmgs3lovRianNEmtwmOi5EGtyo4TbdbUVpzObLUepZGfTIG7Cz8U1cnGLmqxfZxgSyRIatf5OVGYIh5RIwYrkqFdJaN/zcdjYOc73N8FWYn5+bgY51D6aD27AWbPwA7nYNJB4rKmH2QRR9ZuI1kuwDob2ezKWgzV8pkU3DxRSPP/G+BM/HINzurl04/bjAfAtst9JynlPfO61EmEEUCILSpBbKn9dSzEIq2YSz5SxIExv24fhUJ0pjcjvVZo+O0Ddx9vrkNDNSPXao83zqiZTrQkix2vDAEIc6r5SsLCyaGwaTA==\r\nWechatpay-Signature-Type: WECHATPAY2-SHA256-RSA2048\r\nWechatpay-Timestamp: 1770696529\r\nX-Content-Type-Options: nosniff\r\n\r\n{\"code\":\"NO_AUTH\",\"message\":\"当前商户号接入升级版本功能,暂不支持使用升级前功能,请在产品中心-商家转账-前往功能查看接口文档\"}"}
|
||||||
|
{"level":"debug","timestamp":"2026-02-10T14:30:44+08:00","caller":"kernel/baseClient.go:457","content":"POST https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills request header: { Content-Type:application/jsonAuthorization:WECHATPAY2-SHA256-RSA2048 mchid=\"1318592501\",nonce_str=\"tAslXtBASHF46eu8viT6eWrevb5s3amJ\",timestamp=\"1770705044\",serial_no=\"4A1DB62CD5C9BE0B6FC51C30621D6F99686E75C5\",signature=\"45mBO41rIGYDKEtV0wVTh5IjM9OsZNFFDcPpHCEXZin9ukqYHo8GXRlLR50gTYaETzoOry+kdI6Xe1aNpGoLLbeGFOw5Znj167BGrGPnfwyX87lAEvXbafrq7fpab+tVDHXJfLw/dnQ8q+Wy5/gszJx/YllSgyMgoIg+7gc3TDy8e6Ft/QtbbB8CLP4LVUvonG30OdVbspIDd6YpCsJSDQ58dM8Xb7sFEHaUv4bBVwu4U3sZ41muEXFH2JUgsVCT3AR+PgwXyTPeb+cNJyQ0RVAJ04/0fdPV3LszfKvjNJx5rtl05MQd5uS+Dh8JlFDXfHicnC4jG3EtAz1rT7crjw==\"Accept:*/*} request body:"}
|
||||||
|
{"level":"debug","timestamp":"2026-02-10T14:30:44+08:00","caller":"kernel/baseClient.go:459","content":"------------------response content:HTTP/1.1 400 Bad Request\r\nContent-Length: 98\r\nCache-Control: no-cache, must-revalidate\r\nConnection: keep-alive\r\nContent-Language: zh-CN\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 10 Feb 2026 06:30:44 GMT\r\nKeep-Alive: timeout=8\r\nRequest-Id: 0894A1ABCC0610DF0318ECE7F8AF0120EE482884D103-268491067\r\nServer: nginx\r\nWechatpay-Nonce: 1edf81984af96eff23f05a173edee1a9\r\nWechatpay-Serial: 5F2543BF58239A4EB68FA4433DF1438A88B34B16\r\nWechatpay-Signature: sSpmhuIF5wtIHyiwwk7/4mjif3D6FadetjRTkamWXzuiTPp2Vmfo0je2ZKIC038nEqQpfC59ZuC2D6/xROJeAgbpuveTsNw+gRuw7ixMomRnu2ur5paxrelIxjxrStp66wjlbHRQgmsJyCag42ObZqrvJWA7SqPbyaYl3fmLGCv5I4uTiVLwTNmv2dg+9iMw6mk00A5sN99FXKDXIPrrTvKpyi7lbqoleDNzVBdG+DMhPh8Etjlr/QpHydjrTZ28plul6YtITAp8zYmEOMg/s0Iiz9Mp9ZCNDA2PPG1D/jZ2wpxqr1XMCnE6yZE3oKQqoXZZQr336LYjMxeQEh1lRA==\r\nWechatpay-Signature-Type: WECHATPAY2-SHA256-RSA2048\r\nWechatpay-Timestamp: 1770705044\r\nX-Content-Type-Options: nosniff\r\n\r\n{\"code\":\"INVALID_REQUEST\",\"message\":\"此IP地址不允许调用接口,请按开发指引设置\"}"}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@
|
|||||||
### 开发指引
|
### 开发指引
|
||||||
|
|
||||||
- **API V3 开发总览**:https://pay.weixin.qq.com/doc/v3/merchant/4012065168
|
- **API V3 开发总览**:https://pay.weixin.qq.com/doc/v3/merchant/4012065168
|
||||||
- **PHP SDK 使用**:https://pay.weixin.qq.com/doc/v3/merchant/4012076511
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -141,21 +141,8 @@ curl ifconfig.me
|
|||||||
- **1000**:现金营销
|
- **1000**:现金营销
|
||||||
- **1005**:营销活动
|
- **1005**:营销活动
|
||||||
|
|
||||||
### 5. 环境要求
|
|
||||||
|
|
||||||
- PHP >= 7.0
|
|
||||||
- OpenSSL 扩展(必须)
|
|
||||||
- cURL 扩展(必须)
|
|
||||||
- JSON 扩展(必须)
|
|
||||||
- TLS 1.2+
|
|
||||||
|
|
||||||
**检查环境**:
|
**检查环境**:
|
||||||
|
|
||||||
```bash
|
|
||||||
php -v
|
|
||||||
php -m | grep openssl
|
|
||||||
php -m | grep curl
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
116
soul-api/管理端鉴权设计.md
Normal file
116
soul-api/管理端鉴权设计.md
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
# soul-api 管理端登录判断与权限校验
|
||||||
|
|
||||||
|
## 一、有没有登录的依据(JWT)
|
||||||
|
|
||||||
|
**依据:请求中的 JWT。优先从 `Authorization: Bearer <token>` 读取,兼容从 Cookie `admin_session` 读取。**
|
||||||
|
|
||||||
|
| 项目 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 推荐方式 | 请求头 `Authorization: Bearer <JWT>` |
|
||||||
|
| 兼容方式 | Cookie 名 `admin_session`,值为 JWT 字符串 |
|
||||||
|
| JWT 算法 | HS256,密钥为 `ADMIN_SESSION_SECRET` |
|
||||||
|
| 有效期 | 7 天(exp claim) |
|
||||||
|
| 载荷 | sub=admin, username, role=admin |
|
||||||
|
| 校验 | 验签 + 未过期 → 视为已登录 |
|
||||||
|
|
||||||
|
- 配置:`ADMIN_USERNAME` / `ADMIN_PASSWORD` 用于登录校验;`ADMIN_SESSION_SECRET` 用于签发/校验 JWT。
|
||||||
|
- 未带有效 JWT → 401。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、权限校验设计(路由分层)
|
||||||
|
|
||||||
|
- **不校验登录**:只做业务逻辑(登录、登出、鉴权检查)
|
||||||
|
- `GET /api/admin` → 鉴权检查(读 Cookie,有效 200 / 无效 401)
|
||||||
|
- `POST /api/admin` → 登录(校验账号密码,写 Cookie)
|
||||||
|
- `POST /api/admin/logout` → 登出(删 Cookie)
|
||||||
|
|
||||||
|
- **必须已登录**:挂 `AdminAuth()` 中间件,从请求读 `admin_session` 并验签+过期,不通过直接 401,不进入 handler
|
||||||
|
- `/api/admin/*`(如 chapters、content、withdrawals、settings 等)
|
||||||
|
- `/api/db/*`
|
||||||
|
|
||||||
|
- **其它**:如 `/api/miniprogram/*`、`/api/book/*` 等不加 AdminAuth,按各自接口鉴权(如小程序 token)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、框图
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
subgraph 前端["soul-admin 前端"]
|
||||||
|
A[用户打开后台 / 请求接口]
|
||||||
|
A --> B{请求类型}
|
||||||
|
B -->|登录| C[POST /api/admin]
|
||||||
|
B -->|登出| D[POST /api/admin/logout]
|
||||||
|
B -->|进后台前检查| E[GET /api/admin]
|
||||||
|
B -->|业务接口| F[GET/POST /api/admin/xxx]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph 请求["每次请求"]
|
||||||
|
G[浏览器自动携带 Cookie: admin_session]
|
||||||
|
G --> H[发往 soul-api]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph soul-api["soul-api 路由"]
|
||||||
|
I["/api/admin 三条(无中间件)"]
|
||||||
|
J["/api/admin/* 与 /api/db/*"]
|
||||||
|
J --> K[AdminAuth 中间件]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph 鉴权["AdminAuth 与 AdminCheck 逻辑"]
|
||||||
|
K --> L[从请求读 Cookie admin_session]
|
||||||
|
L --> M{有 Cookie?}
|
||||||
|
M -->|无| N[401 未授权]
|
||||||
|
M -->|有| O[解析 exp.signature]
|
||||||
|
O --> P{未过期 且 验签通过?}
|
||||||
|
P -->|否| N
|
||||||
|
P -->|是| Q[放行 / 返回 200]
|
||||||
|
end
|
||||||
|
|
||||||
|
C --> I
|
||||||
|
D --> I
|
||||||
|
E --> I
|
||||||
|
F --> J
|
||||||
|
H --> soul-api
|
||||||
|
I --> E2[GET: 同鉴权逻辑 200/401]
|
||||||
|
I --> C2[POST: 校验账号密码 写 Cookie]
|
||||||
|
I --> D2[POST: 清 Cookie]
|
||||||
|
```
|
||||||
|
|
||||||
|
**路由与中间件关系(框线):**
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph 无鉴权["不经过 AdminAuth"]
|
||||||
|
R1[GET /api/admin]
|
||||||
|
R2[POST /api/admin]
|
||||||
|
R3[POST /api/admin/logout]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph 需登录["经过 AdminAuth"]
|
||||||
|
R4["/api/admin/chapters"]
|
||||||
|
R5["/api/admin/withdrawals"]
|
||||||
|
R6["/api/admin/settings"]
|
||||||
|
R7["/api/db/*"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph 中间件["AdminAuth()"]
|
||||||
|
M[读 Cookie → 验 token → 通过/401]
|
||||||
|
end
|
||||||
|
|
||||||
|
H1[直接进 handler]
|
||||||
|
H2[通过则进 handler]
|
||||||
|
无鉴权 --> H1
|
||||||
|
需登录 --> M --> H2
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、相关代码位置
|
||||||
|
|
||||||
|
| 作用 | 位置 |
|
||||||
|
|------|------|
|
||||||
|
| JWT 签发/校验/从请求取 token | `internal/auth/adminjwt.go` |
|
||||||
|
| 登录、登出、GET 鉴权检查 | `internal/handler/admin.go` |
|
||||||
|
| 管理端中间件 | `internal/middleware/admin_auth.go` |
|
||||||
|
| 路由挂载 | `internal/router/router.go`(api.Group + admin.Use(AdminAuth())) |
|
||||||
Reference in New Issue
Block a user