'use strict'; const { Service } = require('egg'); const crypto = require('crypto'); const { Op } = require('sequelize'); /** 小程序登录的 mock 前缀:`mock:` 直接指定 openid,方便本地联调固定账号 */ const MOCK_PREFIX = 'mock:'; /** * 微信小程序登录 / 绑定 * * 链路:`uni.login()` 拿 code → `jscode2session` 换 openid → * 按 (appid, openid) 找 `wechat_mp_accounts`: * - 已绑定平台账号 → 签发该账号的 user JWT(`firstTime: false`); * - 未绑定 → 自动建平台账号(`wx_`,随机密码)并绑定(`firstTime: true`)。 * * 未配置 `WX_MP_APPID / WX_MP_SECRET` 时(本地 / 单测),走 mock: * 传 `mock:` 固定账号,或任意 code 按 sha1 推导 openid。生产必须显式 `WX_MP_MOCK=true` 才允许 mock。 */ class WechatMpService extends Service { get cfg() { return this.app.config.wechat.mp || {}; } get Account() { return this.app.model.WechatMpAccount; } /** 配置齐全(有 appid + secret)才算真机模式 */ get enabled() { return Boolean(this.cfg.appid && this.cfg.secret); } /** mock 是否可用 */ get mockEnabled() { if (this.cfg.mock) return true; return !this.enabled && this.app.config.env !== 'prod'; } get appid() { return this.cfg.appid || 'mock-appid'; } get apiBase() { return this.cfg.apiBase || 'https://api.weixin.qq.com'; } /** * code → openid * @param {string} code `uni.login()` 返回的 code(本地可用 `mock:`) */ async code2Session(code) { const jsCode = String(code || '').trim(); if (!jsCode) this.ctx.throw(422, '缺少微信登录 code'); if (jsCode.startsWith(MOCK_PREFIX)) { if (!this.mockEnabled) this.ctx.throw(400, 'mock 微信登录未开启'); const openid = this.normalizeOpenid(jsCode.slice(MOCK_PREFIX.length)); return { openid, unionid: null, sessionKey: null, devMode: true }; } if (!this.enabled) { if (!this.mockEnabled) { this.ctx.throw(503, '微信小程序登录未配置(WX_MP_APPID / WX_MP_SECRET)'); } const digest = crypto.createHash('sha1').update(jsCode).digest('hex').slice(0, 24); this.ctx.logger.warn('[wechat-mp] 未配置 appid/secret,使用 mock openid=%s', digest); return { openid: `mock_${digest}`, unionid: null, sessionKey: null, devMode: true }; } const res = await this.ctx.curl(`${this.apiBase}/sns/jscode2session`, { data: { appid: this.cfg.appid, secret: this.cfg.secret, js_code: jsCode, grant_type: 'authorization_code', }, dataType: 'json', timeout: 8000, }); const data = res.data || {}; if (data.errcode) { this.ctx.logger.warn('[wechat-mp] jscode2session 失败: %s %s', data.errcode, data.errmsg); this.ctx.throw(401, `微信登录失败:${data.errmsg || data.errcode}(code 可能已过期,请重试)`); } if (!data.openid) { this.ctx.logger.error('[wechat-mp] jscode2session 未返回 openid: %s', JSON.stringify(data)); this.ctx.throw(502, '微信登录失败:未获取到 openid'); } return { openid: String(data.openid), unionid: data.unionid || null, sessionKey: data.session_key || null, devMode: false, }; } /** 只保留 openid 允许的字符,并限制长度(DB 是 varchar(64)) */ normalizeOpenid(value) { const openid = String(value || '').replace(/[^A-Za-z0-9_\-@.]/g, '').slice(0, 64); return openid || 'mock_default'; } /** * 小程序登录 * @param {object} params code / userInfo(可选微信昵称头像)/ client * @return {Promise<{user:object, binding:object, firstTime:boolean}>} */ async login({ code, userInfo }) { const session = await this.code2Session(code); const appid = this.appid; let account = await this.Account.findOne({ where: { appid, openid: session.openid } }); let firstTime = false; if (!account) { account = await this.Account.create({ appid, openid: session.openid, unionid: session.unionid, nickname: this.pickNickname(userInfo), avatar: this.pickAvatar(userInfo), sessionKey: session.sessionKey, lastLoginAt: new Date(), loginCount: 0, }); firstTime = true; } if (account.status === 0) { this.ctx.throw(403, '该微信已被停用,请联系管理员'); } let user = account.userId ? await this.ctx.service.user.findById(account.userId) : null; if (!user) { user = await this.createUserFor(account, userInfo); firstTime = true; } await account.update({ userId: user.id, unionid: session.unionid || account.unionid, sessionKey: session.sessionKey, nickname: this.pickNickname(userInfo) || account.nickname, avatar: this.pickAvatar(userInfo) || account.avatar, lastLoginAt: new Date(), loginCount: Number(account.loginCount || 0) + 1, }); if (Number(user.status) !== 1) { this.ctx.throw(403, '账号已被禁用,请联系管理员'); } await this.ctx.service.user.touchLogin(user.id); this.ctx.logger.info('[wechat-mp] 登录成功 userId=%s openid=%s firstTime=%s', user.id, session.openid, firstTime); return { user, binding: this.toPublic(account.toJSON()), firstTime }; } /** * 把微信绑定到已有账号(需 user 令牌) * 该 openid 已绑定别的账号 → 409(先解绑) */ async bind(userId, { code, userInfo }) { const session = await this.code2Session(code); const appid = this.appid; const exists = await this.Account.findOne({ where: { appid, openid: session.openid } }); if (exists && exists.userId && Number(exists.userId) !== Number(userId)) { this.ctx.throw(409, '该微信已绑定其他账号,请先在对应账号里解绑'); } if (exists && exists.status === 0) this.ctx.throw(403, '该微信已被停用'); const payload = { userId, unionid: session.unionid || (exists && exists.unionid) || null, sessionKey: session.sessionKey, nickname: this.pickNickname(userInfo) || (exists && exists.nickname) || '', avatar: this.pickAvatar(userInfo) || (exists && exists.avatar) || '', lastLoginAt: new Date(), }; const account = exists ? await exists.update(payload) : await this.Account.create(Object.assign({ appid, openid: session.openid, loginCount: 0 }, payload)); this.ctx.logger.info('[wechat-mp] 用户 %s 绑定微信 openid=%s', userId, session.openid); return this.toPublic((account.toJSON ? account.toJSON() : account)); } /** 当前账号的微信绑定列表 */ async listByUser(userId) { const rows = await this.Account.findAll({ where: { userId }, order: [[ 'id', 'DESC' ]] }); return rows.map(row => this.toPublic(row.toJSON())); } /** 解绑:解绑后该 openid 不能再登录;至少要保留一种登录方式 */ async unbind(userId, id) { const account = await this.Account.findByPk(id); if (!account || Number(account.userId) !== Number(userId)) this.ctx.throw(404, '绑定不存在'); const user = await this.ctx.service.user.findByIdWithPassword(userId); const others = await this.Account.count({ where: { userId, id: { [Op.ne]: account.id } } }); if (!(user && user.passwordHash) && others === 0) { this.ctx.throw(422, '这是唯一的登录方式,请先设置密码再解绑'); } await account.update({ userId: null }); this.ctx.logger.info('[wechat-mp] 用户 %s 解绑微信 id=%s', userId, id); return { id: Number(account.id) }; } /** 给新 openid 建一个平台账号(用户名 wx_xxx,随机密码,用户可用「找回密码」设置) */ async createUserFor(account, userInfo) { const nickname = this.pickNickname(userInfo) || '微信用户'; const password = crypto.randomBytes(24).toString('hex'); let lastError = null; for (let i = 0; i < 5; i++) { const username = this.candidateUsername(account.openid, i); try { const user = await this.ctx.service.auth.register({ username, password, nickname, email: null, phone: null, }); const avatar = this.pickAvatar(userInfo); if (avatar) await this.ctx.service.user.update(user.id, { avatar }); this.ctx.logger.info('[wechat-mp] 新用户注册: %s (id=%s, openid=%s)', username, user.id, account.openid); return this.ctx.service.user.findById(user.id) || user; } catch (err) { if (err.status !== 409) throw err; lastError = err; } } throw lastError || new Error('创建微信账号失败'); } /** `wx_` + openid 末尾 12 位;重名时加随机后缀 */ candidateUsername(openid, attempt) { const tail = String(openid).replace(/[^A-Za-z0-9_]/g, '').slice(-12) || 'user'; if (attempt === 0) return `wx_${tail}`; return `wx_${tail}_${crypto.randomBytes(3).toString('hex')}`; } pickNickname(userInfo) { const nickname = String((userInfo && userInfo.nickname) || '').trim().slice(0, 64); return nickname || ''; } pickAvatar(userInfo) { const avatar = String((userInfo && userInfo.avatar) || '').trim().slice(0, 255); return avatar || ''; } /** 对外结构(不吐 session_key / appid 内部细节) */ toPublic(row) { return { id: Number(row.id), userId: row.userId ? Number(row.userId) : null, nickname: row.nickname || '', avatar: row.avatar || '', unionid: row.unionid || null, lastLoginAt: row.lastLoginAt || null, loginCount: Number(row.loginCount || 0), }; } } module.exports = WechatMpService;