这版是公共号授权版

This commit is contained in:
cao123
2026-08-12 11:47:51 +08:00
parent d0776f9676
commit e47df01af9
18 changed files with 365 additions and 378 deletions
@@ -1,4 +1,3 @@
import { appId } from "../../../env";
import { request } from "../../../utils/request";
import { receiveRedPacket } from "../../../utils/util";
@@ -76,7 +75,7 @@ Page({
async handleReceive(e: any) {
const { id } = e.currentTarget.dataset;
const { code } = app.globalData.store || {};
const appId = wx.getStorageSync("appId");
try {
await receiveRedPacket(
{ appId, code, openId: wx.getStorageSync("openId"), redId: id },
+1 -2
View File
@@ -1,4 +1,3 @@
import { appId } from "../../../env";
import { request } from "../../../utils/request";
Page({
@@ -118,7 +117,7 @@ Page({
seeId: wx.getStorageSync("seeId") || '',
code: wx.getStorageSync("code") || '',
openId: wx.getStorageSync("openId") || '',
appId,
appId: wx.getStorageSync("appId") || '',
type: this.data.selectedReason,
description: this.data.description,
},
+25
View File
@@ -5,6 +5,31 @@ page {
height: 100%;
}
/* loading 遮罩:未登录时显示,防止页面内容一闪 */
.fullscreen-loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #f9f9f9;
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.fullscreen-loading .loading-spinner {
width: 48rpx;
height: 48rpx;
border: 4rpx solid #e0e0e0;
border-top-color: #07c160;
border-radius: 50%;
animation: fullscreen-spin 0.8s linear infinite;
}
@keyframes fullscreen-spin {
to { transform: rotate(360deg); }
}
.scrollarea {
height: 90vh;
display: flex;
+23 -4
View File
@@ -5,7 +5,7 @@ import { htmlToWxNodes } from "../../../utils/html-to-wx-nodes";
import { request } from "../../../utils/request";
import { version, appversion, appId } from "../../../env";
import { receiveRedPacket } from "../../../utils/util";
const app = getApp<IAppOption>()
const isMobileEnvironment = (): boolean => {
const platform = wx.getSystemInfoSync().platform?.toLowerCase() || '';
return platform !== 'windows' && platform !== 'mac';
@@ -24,18 +24,34 @@ Page({
active: 0,
canSubmit: false,
safeBottom: 0,
initialLoading: false,
},
/**
* 生命周期函数--监听页面加载
*/
async onLoad(options: any) {
const app = getApp<IAppOption>();
const openId = wx.getStorageSync("openId");
if (!openId) {
// 未登录:保持 loading 遮罩,跳转 web-view 授权
const code = options.code || "";
const url = `/pages/webview-auth/index?back=video&code=${code}`
wx.navigateTo({ url });
return;
}
// 已登录(含授权返回):隐藏 loading 遮罩,直接进入页面
this.setData({ initialLoading: true });
wx.hideShareMenu({
menus: ["shareAppMessage"], // 单独禁用好友分享
});
new UrlParamsHandler(options);
app.globalData.store = options;
// 合并 URL 参数与 globalData.store 中已有的登录信息(来自 webview-auth
app.globalData.store = {
...app.globalData.store,
...options,
};
let safeBottom = 0;
//@ts-ignore
if (wx.getWindowInfo) {
@@ -52,7 +68,7 @@ Page({
}
this.setData({
safeBottom: safeBottom,
store: options,
store: app.globalData.store,
});
if (!isMobileEnvironment()) {
@@ -95,6 +111,9 @@ Page({
* 生命周期函数--监听页面显示
*/
onShow() {
const openId = wx.getStorageSync("openId");
if (!openId) return;
this.setData({ initialLoading: true });
this.search();
},
+6 -1
View File
@@ -1,4 +1,8 @@
<!--pages/video/video.wxml-->
<view wx:if="{{!initialLoading}}" class="fullscreen-loading">
<view class="loading-spinner"></view>
</view>
<view wx:else>
<navigation-bar title="" back="{{false}}" bind:handleBack="handleBack" color="black" background="#FFF">
<view slot="left" class="report-nav-btn" bind:tap="handleCustomReport">举报</view>
</navigation-bar>
@@ -36,4 +40,5 @@
<image class="icon" src="./assets/1.png" />
</view>
</van-tabs>
</scroll-view>
</scroll-view>
</view>
+44 -313
View File
@@ -3,261 +3,13 @@ import { LoginRes } from "./login.d";
import { wxLogin, wxRequest } from "../../utils/wx-api";
const app = getApp<IAppOption>();
const defaultAvatarUrl =
"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";
type LoginDisplayConfig = {
showLoginImage: boolean;
};
type PartialLoginDisplayConfig = Partial<LoginDisplayConfig>;
const loginConfigKeys = [
"login",
"loginConfig",
"loginPage",
"auth",
"authConfig",
"authPage",
];
const WXROOM_REDIRECT_PATH_KEY = "wxroomRedirectPath";
function isPlainObject(value: unknown): value is Record<string, any> {
return Object.prototype.toString.call(value) === "[object Object]";
}
function hasOwnValue(source: Record<string, any>, keys: string[]) {
return keys.some((key) => source[key] !== undefined && source[key] !== null);
}
function normalizeString(value: unknown) {
return typeof value === "string" ? value.trim() : "";
}
function normalizeBoolean(value: unknown) {
if (typeof value === "boolean") return value;
if (typeof value === "number") return value > 0;
if (typeof value !== "string") return undefined;
const normalized = value.trim().toLowerCase();
if (["1", "true", "yes", "show", "visible", "enabled"].includes(normalized)) {
return true;
}
if (["0", "false", "no", "hide", "hidden", "disabled"].includes(normalized)) {
return false;
}
return undefined;
}
function normalizeSwitchValue(value: unknown) {
const normalized = normalizeBoolean(value);
if (normalized !== undefined) return normalized;
if (typeof value === "string") return value.trim().length > 0;
if (Array.isArray(value)) return value.length > 0;
if (isPlainObject(value)) {
const innerToggle = getBooleanValue(value, ["show", "visible", "enabled", "value"]);
if (innerToggle !== undefined) return innerToggle;
return !!getStringValue(value, [
"url",
"src",
"image",
"imageUrl",
"background",
"backgroundImage",
]);
}
return undefined;
}
function getObjectValue(source: Record<string, any>, keys: string[]) {
for (const key of keys) {
const value = source[key];
if (value !== undefined && value !== null && value !== "") {
return value;
}
}
return undefined;
}
function getStringValue(source: Record<string, any>, keys: string[]):string {
const value = getObjectValue(source, keys);
if (value === undefined) return "";
if (isPlainObject(value)) {
return getStringValue(value, [
"url",
"src",
"image",
"imageUrl",
"background",
"backgroundImage",
]);
}
return normalizeString(value);
}
function getBooleanValue(source: Record<string, any>, keys: string[]) {
const value = getObjectValue(source, keys);
return normalizeBoolean(value);
}
function pushConfigCandidate(list: Record<string, any>[], value: unknown) {
if (isPlainObject(value)) {
list.push(value);
}
}
function collectLoginConfigCandidates(template: unknown) {
const candidates: Record<string, any>[] = [];
if (!isPlainObject(template)) return candidates;
if (
hasOwnValue(template, [
"showLoginImage",
"showLoginBackground",
"showBackgroundImage",
"showImage",
"imageSwitch",
"backgroundSwitch",
"loginImage",
"heroImage",
"loginBg",
"loginBackground",
"backgroundImage",
"backgroundUrl",
"background",
"image",
])
) {
candidates.push(template);
}
loginConfigKeys.forEach((key) => {
pushConfigCandidate(candidates, template[key]);
pushConfigCandidate(candidates, template.pageConfig?.[key]);
pushConfigCandidate(candidates, template.pages?.[key]);
pushConfigCandidate(candidates, template.property?.[key]);
});
if (Array.isArray(template.pages?.login)) {
template.pages.login.forEach((item: any) => {
pushConfigCandidate(candidates, item);
pushConfigCandidate(candidates, item?.props);
});
}
Object.entries(template).forEach(([key, value]) => {
if (!/login|auth/i.test(key)) return;
if (Array.isArray(value)) {
value.forEach((item) => {
if (!isPlainObject(item)) return;
pushConfigCandidate(candidates, item);
pushConfigCandidate(candidates, item.props);
});
return;
}
pushConfigCandidate(candidates, value);
});
return candidates;
}
function readLoginImageSwitch(source: Record<string, any>) {
const imageValue = getObjectValue(source, [
"showLoginImage",
"showLoginBackground",
"showBackgroundImage",
"showImage",
"imageSwitch",
"backgroundSwitch",
"loginImage",
"heroImage",
"loginBackground",
"loginBg",
"backgroundImage",
"backgroundUrl",
"background",
"image",
"imageUrl",
]);
return normalizeSwitchValue(imageValue);
}
function resolveLoginDisplayConfigFromSource(source: unknown): PartialLoginDisplayConfig {
if (!isPlainObject(source)) return {};
const showLoginImage = readLoginImageSwitch(source);
return {
...(showLoginImage !== undefined ? { showLoginImage } : {}),
};
}
function mergeLoginDisplayConfig(
current: PartialLoginDisplayConfig,
next: PartialLoginDisplayConfig
) {
return {
...current,
...(next.showLoginImage !== undefined ? { showLoginImage: next.showLoginImage } : {}),
};
}
Page({
data: {
back: "",
agree: false,
nickFocus: true,
showPopup: false,
safeBottom: app.globalData.safeBottom,
showLoginImage: false,
userInfo: {
avatarUrl: defaultAvatarUrl,
nickName: "微信用户",
},
},
applyLoginDisplayConfig(options: Record<string, any> = {}) {
const template = app.globalData.template as Record<string, any> | null;
const config = collectLoginConfigCandidates(template).reduce(
(result, item) =>
mergeLoginDisplayConfig(result, resolveLoginDisplayConfigFromSource(item)),
{} as PartialLoginDisplayConfig
);
const optionConfig = resolveLoginDisplayConfigFromSource(options);
const merged = mergeLoginDisplayConfig(config, optionConfig);
this.setData({
showLoginImage: merged.showLoginImage ?? false,
});
},
async onChooseAvatar(e: any) {
const { avatarUrl } = e.detail;
wx.uploadFile({
url: `${BASE_URL}/api/operation/sys-media/upload-oss`,
filePath: avatarUrl,
name: "media",
success: (res: any) => {
const { data } = JSON.parse(res.data);
this.setData({
userInfo: {
...this.data.userInfo,
avatarUrl: data,
},
});
},
fail: () => {
wx.showToast({
title: "上传头像失败",
icon: "none",
});
},
});
},
buildQueryString(params: Record<string, any>): string {
@@ -288,56 +40,55 @@ Page({
"/package-live/wxroom/index";
wx.removeStorageSync(WXROOM_REDIRECT_PATH_KEY);
} else {
const store = app.globalData.store;
const state = wx.getStorageSync("state") ?? undefined;
const code = wx.getStorageSync("code") ?? undefined;
const groupId = wx.getStorageSync("groupId") ?? undefined;
const store = app.globalData.store;
const state = wx.getStorageSync("state") ?? undefined;
const code = wx.getStorageSync("code") ?? undefined;
const groupId = wx.getStorageSync("groupId") ?? undefined;
if (state && !code) {
if (self.data.back === "video") {
const storeParams =
typeof store === "string" ? store : this.buildQueryString(store);
fullPath = `/pages/live/video/video?${storeParams}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
if (state && !code) {
if (self.data.back === "video") {
const storeParams =
typeof store === "string" ? store : this.buildQueryString(store);
fullPath = `/pages/live/video/video?${storeParams}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
} else {
fullPath = `/pages/live/registration/registration?state=${state}`;
}
} else if (!state && code) {
if (self.data.back === "video") {
const storeParams =
typeof store === "string" ? store : this.buildQueryString(store);
fullPath = `/pages/live/video/video?${storeParams}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
} else {
fullPath = `/pages/live/registration/registration?code=${code}`;
}
} else {
fullPath = `/pages/live/registration/registration?state=${state}`;
if (self.data.back === "room") {
fullPath = `/pages/live/room/room?groupId=${groupId}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
}
}
} else if (!state && code) {
if (self.data.back === "video") {
const storeParams =
typeof store === "string" ? store : this.buildQueryString(store);
fullPath = `/pages/live/video/video?${storeParams}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
} else {
fullPath = `/pages/live/registration/registration?code=${code}`;
}
} else {
if (self.data.back === "room") {
fullPath = `/pages/live/room/room?groupId=${groupId}`;
} else if (self.data.back === "red") {
fullPath = `/pages/common/red/red`;
} else if (self.data.back === "user") {
fullPath = `/pages/tab-bar/user/user`;
}
}
}
} else {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 2];
if (!currentPage) {
// 如果没有上一页,跳转到第一个可用 tab,而不是硬编码的 index
const tabbarItems = app.globalData.tabbarItems;
if (tabbarItems && tabbarItems.length > 0) {
wx.switchTab({ url: tabbarItems[0].pagePath });
wx.switchTab({ url: tabbarItems[0].pagePath });
} else {
wx.switchTab({ url: "/pages/tab-bar/medicine-box/index" });
wx.switchTab({ url: "/pages/tab-bar/medicine-box/index" });
}
return;
}
@@ -382,33 +133,24 @@ Page({
const loginRes = await wxLogin();
if (!loginRes.code) throw new Error(loginRes.errMsg);
const { avatarUrl, nickName } = this.data.userInfo;
const state = wx.getStorageSync("state");
let loginResult: LoginRes;
if (state) {
const reqData: Record<string, any> = {
state: wx.getStorageSync("state") ?? undefined,
...(nickName && nickName !== "微信用户" ? { nickName } : {}),
...(avatarUrl && avatarUrl !== defaultAvatarUrl ? { avatarUrl } : {}),
};
loginResult = await wxRequest<LoginRes>({
url: `${BASE_URL}/api/auth/app-login?appId=${appId}&code=${loginRes.code}`,
method: "POST",
data: reqData,
data: {
state: wx.getStorageSync("state") ?? undefined,
},
});
} else {
const reqData: Record<string, any> = {
state: wx.getStorageSync("code") ?? undefined,
...(nickName && nickName !== "微信用户" ? { nickName } : {}),
...(avatarUrl && avatarUrl !== defaultAvatarUrl ? { avatarUrl } : {}),
};
loginResult = await wxRequest<LoginRes>({
url: `${BASE_URL}/api/auth/app-auth?appId=${appId}&code=${loginRes.code}`,
method: "POST",
data: reqData,
data: {
state: wx.getStorageSync("code") ?? undefined,
},
});
}
@@ -442,10 +184,6 @@ Page({
});
app.globalData.isLogin = true;
this.triggerEvent("loginSuccess", {
userName: resNickName,
avatarUrl: resAvatarUrl,
});
wx.showToast({
title: "登录成功",
duration: 2000,
@@ -477,12 +215,5 @@ Page({
if (options.back) {
this.setData({ back: options.back });
}
this.applyLoginDisplayConfig(options);
},
onShow() {
setTimeout(() => {
this.setData({ nickFocus: true });
}, 200);
},
});
});
@@ -0,0 +1,4 @@
{
"navigationBarTitleText": "授权登录",
"usingComponents": {}
}
+74
View File
@@ -0,0 +1,74 @@
import { BASE_URL } from "../../env";
Page({
data: {
webViewUrl: "",
loading: true,
backUrl: "",
code: "",
authCompleted: false, // 防止重复处理
},
onLoad(options: any) {
if (options.back) {
this.setData({ backUrl: decodeURIComponent(options.back) });
}
const code = options.code || "";
this.setData({ code })
setTimeout(() => {
const authUrl = `${BASE_URL}/h5/oauth/auth-success.html?entryCode=${encodeURIComponent(code)}`
this.setData({
webViewUrl: authUrl,
loading: true,
});
}, 50);
},
/** web-view 首次加载完成,隐藏骨架屏 */
onWebViewLoad() {
this.setData({ loading: false });
},
onMessage(e: any) {
const dataList = e.detail?.data || [];
console.log("onMessage===========》", dataList);
if (dataList.length === 0) return;
const data = dataList.reduce((acc: any, curr: any) => ({ ...acc, ...curr }), {});
console.log("onMessage", data);
// 先存储缓存,再操作页面状态
const fields: Record<string, string> = {
openId: data.openId || '',
unionId: data.unionId || '',
appId: data.appId || '',
userName: data.nickname || '微信用户',
avatarUrl: data.avatar || '',
code: data.code || '',
userId: data.userId || '',
};
Object.entries(fields).forEach(([key, value]) => {
if (value) {
try {
wx.setStorageSync(key, value);
} catch (err: any) {
console.log("缓存写入失败 key:", key, "error:", err?.message || err);
}
}
});
getApp<IAppOption>().globalData.isLogin = true;
getApp<IAppOption>().globalData.store = {
...getApp<IAppOption>().globalData.store,
...fields,
};
try { this.setData({ authCompleted: true }); } catch (_) { }
},
});
+13
View File
@@ -0,0 +1,13 @@
<!--pages/webview-auth/index.wxml-->
<view class="container">
<view class="loading" wx:if="{{loading && webViewUrl}}">
<view class="loading-spinner"></view>
<text class="loading-text">正在加载授权页面...</text>
</view>
<web-view
wx:if="{{webViewUrl}}"
src="{{webViewUrl}}"
bindmessage="onMessage"
bindload="onWebViewLoad"
></web-view>
</view>
+61
View File
@@ -0,0 +1,61 @@
/* pages/webview-auth/index.wxss */
.container {
width: 100%;
height: 100vh;
overflow: hidden;
position: relative;
}
.loading {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #fff;
z-index: 10;
}
.loading-spinner {
width: 40rpx;
height: 40rpx;
border: 4rpx solid #e5e5e5;
border-top-color: #07c160;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loading-text {
margin-top: 20rpx;
font-size: 28rpx;
color: #999;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.cancel-btn {
position: fixed;
bottom: 40rpx;
left: 50%;
transform: translateX(-50%);
width: 300rpx;
height: 72rpx;
line-height: 72rpx;
text-align: center;
background: #e64340;
color: #fff;
font-size: 28rpx;
border-radius: 36rpx;
z-index: 999;
box-shadow: 0 4rpx 12rpx rgba(230, 67, 64, 0.3);
}
.cancel-btn:active {
opacity: 0.8;
}