const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const XLSX = require('xlsx'); const { Controller, } = require('egg'); const { toSuccess, toFailure } = require('../lib/api_response'); // 扫描记录 Excel 追加串行队列(临时联调用,避免并发读写冲突) let scanExcelWriteQueue = Promise.resolve(); class HomeController extends Controller { /** * 规范化平台编码。 * @param {*} platformCode 平台编码原始值。 * @return {string} 标准化后的平台编码。 */ normalizePlatformCode(platformCode) { return String(platformCode || '').trim().toUpperCase(); } /** * 判断店铺记录的平台编码是否与目标平台一致。 * @param {object|null|undefined} shop 店铺记录。 * @param {string} platformCode 目标平台编码。 * @return {boolean} 是否一致。 */ isMatchedShopPlatform(shop, platformCode) { return this.normalizePlatformCode(shop && shop.platform_code) === this.normalizePlatformCode(platformCode); } /** * 解析绑定授权回调 state 并提取业务编码。 * * 仅支持以 bind_ 开头的 state,去掉前缀后的剩余整段即业务 code。 * * @param {string} state 授权回调中的 state 原始值。 * @return {string} 解析得到的业务 code,无法解析时返回空字符串。 */ parsePlatformOauthBindBusinessCode(state) { const bindStatePrefix = 'bind_'; if (typeof state !== 'string') { return ''; } const normalizedState = state.trim(); if (!normalizedState.startsWith(bindStatePrefix)) { return ''; } return normalizedState.slice(bindStatePrefix.length).trim(); } /** * 渲染平台绑定授权的简易结果页。 * * 成功场景仅展示简洁成功文案;失败场景仅展示简洁失败文案并提示重新授权。 * * @param {boolean} isSuccess 是否成功。 * @return {Promise} 无返回值。 */ async renderPlatformOauthBindResultPage(isSuccess) { const title = isSuccess ? '绑定成功' : '绑定失败'; const message = isSuccess ? '绑定成功' : '绑定失败,请重新授权'; const color = isSuccess ? '#2f7d32' : '#c62828'; const html = ` ${title}

${title}

${message}

`; this.ctx.status = isSuccess ? 200 : 400; this.ctx.type = 'text/html; charset=utf-8'; this.ctx.body = html; } /** * 解析平台授权回调 state,提取平台编码与授权随机码。 * @param {string} state 回调原始 state。 * @param {string} reservationCodePrefix 配置的预留前缀。 * @return {{normalizedState: string, platformCode: string, authRandomCode: string}|null} 解析结果,失败时返回 null。 */ parsePlatformOauthState(state, reservationCodePrefix) { const normalizedState = reservationCodePrefix && state.startsWith(reservationCodePrefix) ? state.slice(reservationCodePrefix.length) : state; const separatorIndex = normalizedState.indexOf('_'); if (separatorIndex <= 0 || separatorIndex === normalizedState.length - 1) { return null; } const platformCode = normalizedState.slice(0, separatorIndex).trim(); const authRandomCode = normalizedState.slice(separatorIndex + 1).trim(); if (!platformCode || !authRandomCode) { return null; } return { normalizedState, platformCode, authRandomCode, }; } /** * 组装平台授权回调页面展示数据。 * @param {object} payload 页面数据参数。 * @param {string} payload.code 平台回调返回的授权码。 * @param {string} payload.state 平台回调返回的原始 state。 * @param {{normalizedState: string, platformCode: string, authRandomCode: string}|null} payload.parsedState 解析后的 state 数据。 * @param {import('sequelize').Model|null} payload.shop 店铺记录。 * @param {string} payload.errorMessage 预校验失败提示。 * @return {object} 页面渲染数据。 */ buildPlatformOauthCallbackViewData({ code, state, parsedState, shop, errorMessage }) { const platformCode = parsedState ? parsedState.platformCode : ''; const authRandomCode = parsedState ? parsedState.authRandomCode : ''; const normalizedState = parsedState ? parsedState.normalizedState : ''; const hasShop = Boolean(shop); const isProcessed = hasShop ? Number(shop.status) === 1 : null; const isPlatformMatched = hasShop && parsedState ? this.isMatchedShopPlatform(shop, platformCode) : null; let resultLevel = 'error'; let resultText = errorMessage || '授权回调校验失败'; if (!errorMessage && !hasShop) { resultText = '预授权码不存在'; } else if (!errorMessage && isPlatformMatched === false) { resultText = '平台不匹配'; } else if (!errorMessage && isProcessed === true) { resultLevel = 'warning'; resultText = '该预授权码已处理'; } else if (!errorMessage && isProcessed === false && isPlatformMatched === true) { resultLevel = 'success'; resultText = '预授权码有效,平台匹配且尚未处理'; } return { title: '平台授权回调结果', resultLevel, resultText, code, state, normalizedState, platformCode, authRandomCode, isProcessed, isProcessedText: hasShop ? (isProcessed ? '是(已处理)' : '否(未处理)') : '无法判断', isPlatformMatched, isPlatformMatchedText: hasShop ? (isPlatformMatched ? '是' : '否') : '无法判断', shopPlatformCode: hasShop ? String(shop.platform_code || '') : '', shopStatus: hasShop ? Number(shop.status) : null, hasShop, }; } /** * 将淘宝授权接口返回的奇门响应归一化为可读取的对象。 * @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。 * @return {object|null} 归一化后的响应对象,无法识别时返回 null。 */ normalizeTbOauthQimenResponse(xmlArray) { if (!xmlArray || typeof xmlArray !== 'object' || Array.isArray(xmlArray)) { return null; } const response = xmlArray.response && typeof xmlArray.response === 'object' ? xmlArray.response : xmlArray; if (response.top_auth_token_create_response && typeof response.top_auth_token_create_response === 'object') { return response.top_auth_token_create_response; } return response; } /** * 从淘宝授权接口的奇门返回中提取 access_token。 * @param {object|Array|null|undefined} xmlArray 奇门返回中的 xmlArray 字段。 * @return {string} 提取出的 access_token,失败时返回空字符串。 */ extractTbOauthAccessToken(xmlArray) { if (Array.isArray(xmlArray)) { const tokenCreateResponse = xmlArray.find(item => item && typeof item === 'object' && item.name === 'top_auth_token_create_response'); const tokenCreateChildren = Array.isArray(tokenCreateResponse && tokenCreateResponse.children) ? tokenCreateResponse.children : []; const tokenCreateResult = tokenCreateChildren.find(item => item && typeof item === 'object' && item.name === 'result'); const resultChildren = Array.isArray(tokenCreateResult && tokenCreateResult.children) ? tokenCreateResult.children : []; const accessTokenItem = resultChildren.find(item => item && typeof item === 'object' && item.name === 'access_token'); return accessTokenItem && accessTokenItem.value !== undefined && accessTokenItem.value !== null ? String(accessTokenItem.value).trim() : ''; } const response = this.normalizeTbOauthQimenResponse(xmlArray); const result = response && response.result && typeof response.result === 'object' ? response.result : null; const accessTokenValue = result && result.access_token !== undefined && result.access_token !== null ? result.access_token : response && response.access_token !== undefined && response.access_token !== null ? response.access_token : ''; return accessTokenValue ? String(accessTokenValue).trim() : ''; } async testSendData() { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } /** * 读取原始请求报文文本。 * * 优先取 koa-bodyparser 已解析的 rawBody;若上游未携带可识别的 * Content-Type(bodyParser 未消费请求流),则直接从请求流中读取。 * @return {Promise} 报文文本,读取失败时返回空字符串。 */ async readRawRequestText() { const { ctx } = this; const rawBody = ctx.request.rawBody; if (rawBody !== undefined && rawBody !== null) { return Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody); } const chunks = []; try { for await (const chunk of ctx.req) { chunks.push(chunk); } } catch (err) { ctx.logger.error('[scan] 读取请求流失败', err && err.message || String(err)); } return Buffer.concat(chunks.map(chunk => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))).toString('utf8'); } /** * 生成格式化的当前时间字符串。 * @param {Date} date 时间对象。 * @return {string} YYYY-MM-DD HH:mm:ss。 */ formatScanRecordTime(date = new Date()) { const pad = value => String(value).padStart(2, '0'); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; } /** * 将一次扫描记录(时间 + 条码)追加写入项目根目录的 scan_records.xlsx。 * * 临时联调用途:文件不存在则新建(含表头),存在则读取全部已有行后追加。 * 写入复用 ExcelService 的原子写(临时文件 + rename),避免写坏文件。 * * @param {string} barcode 扫描到的条码内容。 * @return {Promise<{filePath: string, timeText: string, barcode: string, totalRows: number}>} 追加结果。 */ async appendScanRecordToExcel(barcode) { const filePath = path.join(this.app.baseDir, 'scan_records.xlsx'); const timeText = this.formatScanRecordTime(); const headerRow = [ '时间', '条码' ]; let rows = [ headerRow ]; if (fs.existsSync(filePath)) { try { const workbook = XLSX.readFile(filePath); const firstSheetName = workbook.SheetNames && workbook.SheetNames[0]; if (firstSheetName) { const sheet = workbook.Sheets[firstSheetName]; const parsedRows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false }); const existingRows = parsedRows.filter(row => Array.isArray(row) && row.length); if (existingRows.length) { rows = existingRows; } } } catch (error) { this.ctx.logger.error('[scan] 读取根目录 scan_records.xlsx 失败,将重建文件', error && error.message || String(error)); rows = [ headerRow ]; } } rows.push([ timeText, barcode ]); const workbook = XLSX.utils.book_new(); const sheet = XLSX.utils.aoa_to_sheet(rows); XLSX.utils.book_append_sheet(workbook, sheet, 'scan_records'); const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }); await this.ctx.service.systems.excel.writeAtomicBufferFile(filePath, Buffer.from(buffer)); return { filePath, timeText, barcode, totalRows: rows.length - 1, }; } /** * 扫描报文接收入口(POST /scan)。 * * 联调阶段:接收上游报文并原样打日志、回显,同时把扫描到的条码与时间 * 追加写入项目根目录 scan_records.xlsx。 */ async scan() { const { ctx } = this; const rawBody = await this.readRawRequestText(); const barcode = rawBody ? rawBody.trim() : ''; let body = null; let parseError = ''; let excelRecord = null; if (rawBody) { const trimmed = rawBody.trim(); if (trimmed.startsWith('{') || trimmed.startsWith('[')) { try { body = JSON.parse(trimmed); } catch (err) { parseError = err && err.message || String(err); body = rawBody; } } else { body = rawBody; } } if (barcode) { excelRecord = await (scanExcelWriteQueue = scanExcelWriteQueue .catch(() => {}) .then(() => this.appendScanRecordToExcel(barcode))); } ctx.logger.info('[scan] 收到请求报文', { method: ctx.method, url: ctx.url, contentType: ctx.get('content-type'), query: ctx.query, headers: ctx.headers, rawBody, rawBodyHex: rawBody ? Buffer.from(rawBody, 'utf8').toString('hex') : '', body, parseError, barcode, excelRecord, }); ctx.body = toSuccess({ contentType: ctx.get('content-type'), rawBody, body, parseError, barcode, excelRecord, }); } async index() { const { ctx, } = this; ctx.body = 'pong'; } /** * 使用授权码请求拼多多开放平台换取授权结果,并返回结构化处理结果。 * @param {string} code 平台回调返回的授权码。 * @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。 */ async pdd(code) { const pddConfig = this.app.config.pdd || {}; try { const result = await this.ctx.curl('https://open-api.pinduoduo.com/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/json', }, dataType: 'json', data: { client_id: pddConfig.client_id || '', code, grant_type: 'authorization_code', client_secret: pddConfig.client_secret || '', }, }); console.log(result); if (result && result.data && result.data.error_response) { const errorMessage = result.data.error_response.error_msg || '未知错误'; return { success: false, message: `拼多多授权失败:${errorMessage}`, result, }; } return { success: true, result, }; } catch (error) { this.ctx.logger.error('[platform-oauth][PDD] oauth/token 请求异常: %s', error); return { success: false, message: `拼多多授权请求异常:${error.message}`, result: null, }; } } /** * 使用授权码请求菜鸟授权结果,并按淘宝 OAuth 协议解析返回值。 * @param {string} code 平台回调返回的授权码。 * @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。 */ async cainiao(code) { const qimenConfig = this.app.config.qimen || {}; const redirectUri = 'http://39.100.57.68/'; const requestPayload = { code, grant_type: 'authorization_code', client_id: qimenConfig.appKey || '', client_secret: qimenConfig.security || '', redirect_uri: redirectUri, }; const formBody = new URLSearchParams(requestPayload).toString(); try { const result = await this.ctx.curl('https://oauth.taobao.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, dataType: 'json', content: formBody, }); console.log(result); const responseData = result && result.data ? result.data : null; const hasTaobaoStandardError = !!( responseData && (responseData.error !== undefined || responseData.error_description !== undefined) ); if (responseData && (responseData.error_response || hasTaobaoStandardError)) { const errorMessage = responseData.error_response && responseData.error_response.error_msg ? responseData.error_response.error_msg : responseData.error_description || responseData.error || '未知错误'; return { success: false, message: `菜鸟授权失败:${errorMessage}`, result, }; } return { success: true, result, }; } catch (error) { this.ctx.logger.error('[platform-oauth][CAINIAO] oauth/token 请求异常: %s', error); return { success: false, message: `菜鸟授权请求异常:${error.message}`, result: null, }; } } /** * 构建拼多多授权店铺回写字段。 * @param {object|null|undefined} oauthData 拼多多授权返回数据。 * @return {object} 可直接用于店铺模型回写的字段对象。 */ buildPddOauthShopUpdatePayload(oauthData) { const toDateFromUnixSeconds = value => { const seconds = Number(value); if (!Number.isFinite(seconds) || seconds <= 0) { return null; } return new Date(seconds * 1000); }; const updatePayload = { owner_id: oauthData && oauthData.owner_id !== undefined ? oauthData.owner_id : null, access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null, refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null, token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at), refresh_token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.refresh_token_expires_at), auth_expire_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at), scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null, status: 1, }; if (oauthData && oauthData.owner_name) { updatePayload.shop_name = oauthData.owner_name; } return updatePayload; } /** * 安全解码淘宝店铺昵称,解码失败时保留原值。 * @param {string|null|undefined} taobaoUserNick 淘宝返回的店铺昵称。 * @return {string|null|undefined} 解码后的店铺昵称,失败时返回原值。 */ decodeTbShopName(taobaoUserNick) { if (typeof taobaoUserNick !== 'string') { return taobaoUserNick; } try { return decodeURIComponent(taobaoUserNick); } catch (error) { return taobaoUserNick; } } /** * 构建菜鸟授权店铺回写字段。 * @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。 * @return {object} 可直接用于店铺模型回写的字段对象。 */ buildCainiaoOauthShopUpdatePayload(oauthData) { const toDateFromUnixMilliseconds = value => { const milliseconds = Number(value); if (!Number.isFinite(milliseconds) || milliseconds <= 0) { return null; } return new Date(milliseconds); }; const updatePayload = { owner_id: oauthData && oauthData.taobao_user_id !== undefined ? oauthData.taobao_user_id : null, access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null, refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null, token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time), refresh_token_expires_at: toDateFromUnixMilliseconds(oauthData && oauthData.refresh_token_valid_time), auth_expire_at: toDateFromUnixMilliseconds(oauthData && oauthData.expire_time), scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null, status: 1, }; if (oauthData && oauthData.taobao_user_nick != null) { updatePayload.shop_name = this.decodeTbShopName(oauthData.taobao_user_nick); } return updatePayload; } /** * 按仓库、平台与授权标识查找已授权的旧店铺记录。 * @param {import('sequelize').Model} shop 当前预申请店铺记录。 * @param {string|number|null|undefined} ownerId 平台主体标识。 * @param {string|null|undefined} shopName 店铺名称。 * @param {import('sequelize').Transaction} transaction 当前事务对象。 * @return {Promise} 命中的已授权店铺记录。 */ async findAuthorizedOauthShop(shop, ownerId, shopName, transaction) { const { Op } = this.app.Sequelize; const normalizedOwnerId = ownerId !== undefined && ownerId !== null ? String(ownerId).trim() : ''; const normalizedShopName = shopName !== undefined && shopName !== null ? String(shopName).trim() : ''; const matchConditions = []; if (normalizedOwnerId) { matchConditions.push({ owner_id: ownerId }); } if (normalizedShopName) { matchConditions.push({ shop_name: shopName }); } if (!matchConditions.length) { return null; } return await this.ctx.model.Shop.findOne({ where: { warehouse_id: shop.warehouse_id, platform_code: shop.platform_code, status: 1, id: { [Op.ne]: shop.id, }, [Op.or]: matchConditions, }, transaction, }); } /** * 查找与待更新店铺存在唯一约束冲突的店铺记录(不限授权状态)。 * 用于乐观重试场景:当前预授权店铺 save 触发 uk_warehouse_platform_shop_name * 冲突时,回退到此方法查找冲突记录并尝试合并。 * @param {import('sequelize').Model} shop 当前预申请店铺记录。 * @param {object} updatePayload 待回写的字段对象,需包含 shop_name。 * @param {import('sequelize').Transaction} transaction 当前事务对象。 * @return {Promise} 冲突的店铺记录,未找到返回 null。 */ async findConflictShopForOauth(shop, updatePayload, transaction) { const { Op } = this.app.Sequelize; const normalizedShopName = updatePayload.shop_name != null ? String(updatePayload.shop_name).trim() : ''; if (!normalizedShopName) { return null; } return await this.ctx.model.Shop.findOne({ where: { warehouse_id: shop.warehouse_id, platform_code: shop.platform_code, shop_name: normalizedShopName, id: { [Op.ne]: shop.id, }, }, transaction, }); } /** * 按仓库、平台与授权标识查找已授权的旧店铺记录。 * @param {import('sequelize').Model} shop 当前预申请店铺记录。 * @param {object|null|undefined} oauthData 拼多多授权返回数据。 * @param {import('sequelize').Transaction} transaction 当前事务对象。 * @return {Promise} 命中的已授权店铺记录。 */ async findAuthorizedPddOauthShop(shop, oauthData, transaction) { const ownerId = oauthData && oauthData.owner_id !== undefined && oauthData.owner_id !== null ? String(oauthData.owner_id).trim() : ''; const ownerName = oauthData && oauthData.owner_name !== undefined && oauthData.owner_name !== null ? String(oauthData.owner_name).trim() : ''; return await this.findAuthorizedOauthShop(shop, ownerId ? oauthData.owner_id : null, ownerName, transaction); } /** * 将拼多多授权成功后的关键字段回写到店铺记录。 * @param {import('sequelize').Model} shop 店铺模型实例。 * @param {object|null|undefined} oauthData 拼多多授权返回数据。 * @return {Promise} 已保存的店铺模型实例。 */ async updatePddOauthShop(shop, oauthData) { const updatePayload = this.buildPddOauthShopUpdatePayload(oauthData); const saveFields = [ 'owner_id', 'shop_name', 'access_token', 'refresh_token', 'token_expires_at', 'refresh_token_expires_at', 'auth_expire_at', 'scope', 'status', ]; return await this.ctx.model.transaction(async transaction => { const authorizedShop = await this.findAuthorizedPddOauthShop(shop, oauthData, transaction); if (authorizedShop) { authorizedShop.set(updatePayload); await authorizedShop.save({ fields: saveFields, transaction, }); await shop.destroy({ transaction }); return authorizedShop; } shop.set(updatePayload); await shop.save({ fields: saveFields, transaction, }); return shop; }); } /** * 将菜鸟授权成功后的关键字段回写到店铺记录。 * @param {import('sequelize').Model} shop 店铺模型实例。 * @param {object|null|undefined} oauthData 菜鸟授权返回数据,字段仍遵循淘宝 OAuth 协议。 * @return {Promise} 已保存的店铺模型实例。 */ async updateCainiaoOauthShop(shop, oauthData) { const updatePayload = this.buildCainiaoOauthShopUpdatePayload(oauthData); const saveFields = [ 'owner_id', 'shop_name', 'access_token', 'refresh_token', 'token_expires_at', 'refresh_token_expires_at', 'auth_expire_at', 'scope', 'status', ]; // 兜底:若 OAuth 响应未返回 shop_name,沿用数据库已有值,避免 save 时触发 allowNull 校验 if (!('shop_name' in updatePayload) || updatePayload.shop_name == null) { updatePayload.shop_name = shop.shop_name; } try { return await this.ctx.model.transaction(async transaction => { const authorizedShop = await this.findAuthorizedOauthShop( shop, updatePayload.owner_id, updatePayload.shop_name, transaction ); if (authorizedShop) { authorizedShop.set(updatePayload); await authorizedShop.save({ fields: saveFields, transaction, }); await shop.destroy({ transaction }); return authorizedShop; } shop.set(updatePayload); await shop.save({ fields: saveFields, transaction, }); return shop; }); } catch (error) { // 记录 Sequelize 验证错误的详细信息,包括每个字段的失败原因 if (error.name === 'SequelizeValidationError' && Array.isArray(error.errors)) { const fieldErrors = error.errors.map(e => `${e.path}: ${e.message}`).join('; '); this.ctx.logger.error( '[platform-oauth][CAINIAO] 店铺保存校验失败,shop_id=%s,字段详情:%s', shop && shop.id, fieldErrors ); throw error; } // 唯一约束冲突:尝试乐观重试,查找冲突记录并合并 if (error.name === 'SequelizeUniqueConstraintError') { const conflictFields = error.fields ? Object.keys(error.fields).join(', ') : 'unknown'; const conflictValues = error.fields ? JSON.stringify(error.fields) : 'unknown'; this.ctx.logger.error( '[platform-oauth][CAINIAO] 店铺保存唯一约束冲突,shop_id=%s,冲突字段:%s,冲突值:%s', shop && shop.id, conflictFields, conflictValues ); // 乐观重试:在新事务中查找冲突记录并尝试合并 try { return await this.ctx.model.transaction(async transaction => { const conflictShop = await this.findConflictShopForOauth( shop, updatePayload, transaction ); if (conflictShop) { conflictShop.set(updatePayload); await conflictShop.save({ fields: saveFields, transaction, }); await shop.destroy({ transaction }); this.ctx.logger.info( '[platform-oauth][CAINIAO] 乐观重试成功,冲突店铺已合并,conflict_shop_id=%s,pre_auth_shop_id=%s', conflictShop.id, shop.id ); return conflictShop; } // 未找到冲突记录则返回 null,由上层展示友好提示 this.ctx.logger.warn( '[platform-oauth][CAINIAO] 乐观重试未找到冲突记录,shop_id=%s,shop_name=%s', shop && shop.id, updatePayload.shop_name ); return null; }); } catch (retryError) { this.ctx.logger.error( '[platform-oauth][CAINIAO] 乐观重试失败,shop_id=%s,错误:%s', shop && shop.id, retryError.message || retryError ); return null; } } throw error; } } /** * 处理平台授权回调请求,解析 query 中的 code 与 state。 * 内部使用 try-catch 兜底,确保即使处理过程中抛出未捕获异常也能渲染错误页面而非 500。 * @return {Promise} 无返回值。 */ async platformOauthCallback() { const { ctx, app, } = this; const code = typeof ctx.query.code === 'string' ? ctx.query.code.trim() : ''; const state = typeof ctx.query.state === 'string' ? ctx.query.state.trim() : ''; const reservationCodePrefix = app.config.platformOauthReservationCodePrefix || ''; const parsedState = state ? this.parsePlatformOauthState(state, reservationCodePrefix) : null; let errorMessage = ''; let shop = null; try { if (!code) { errorMessage = 'code不能为空'; } else if (!state) { errorMessage = 'state不能为空'; } else if (!parsedState) { errorMessage = 'state解析失败'; } else { switch (parsedState.platformCode) { case 'PDD': { const pddResult = await this.pdd(code); if (pddResult.success === false) { errorMessage = pddResult.message; break; } shop = await ctx.model.Shop.findOne({ where: { auth_random_code: parsedState.authRandomCode, }, }); if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { const oauthData = pddResult.result && pddResult.result.data ? pddResult.result.data : pddResult.result; shop = await this.updatePddOauthShop(shop, oauthData); } } break; case 'CAINIAO': { const cainiaoOauthResult = await this.cainiao(code); if (!cainiaoOauthResult || cainiaoOauthResult.success === false) { errorMessage = cainiaoOauthResult && cainiaoOauthResult.message ? cainiaoOauthResult.message : '菜鸟授权失败:未知错误'; break; } shop = await ctx.model.Shop.findOne({ where: { auth_random_code: parsedState.authRandomCode, }, }); if (shop && this.isMatchedShopPlatform(shop, parsedState.platformCode)) { const oauthData = cainiaoOauthResult.result && cainiaoOauthResult.result.data ? cainiaoOauthResult.result.data : cainiaoOauthResult.result; shop = await this.updateCainiaoOauthShop(shop, oauthData); if (!shop) { errorMessage = '店铺名称已存在,请先在系统中解绑同名店铺后重试'; } } break; } default: errorMessage = '暂未接入该平台授权回调处理'; break; } } } catch (error) { ctx.logger.error('[platform-oauth] 回调处理异常: %s', error.stack || error.message || error); errorMessage = `系统内部错误:${error.message || '未知异常'}`; // 发生异常后不再信任 shop 状态,置空以避免渲染误导信息 shop = null; } const viewData = this.buildPlatformOauthCallbackViewData({ code, state, parsedState, shop, errorMessage, }); ctx.status = viewData.resultLevel === 'error' ? 400 : 200; await ctx.render('platform_oauth_callback.html', viewData); } /** * 处理拼多多绑定授权回调。 * * 流程:校验 code/state -> 解析业务 code -> 复用 pdd(code) 换取 access_token * -> 写入缓存 bind_pdd_code:{业务code} -> 返回简易成功/失败页。 * * @return {Promise} 无返回值。 */ async platformOauthBind() { const { service } = this.ctx; const code = typeof this.ctx.query.code === 'string' ? this.ctx.query.code.trim() : ''; const state = typeof this.ctx.query.state === 'string' ? this.ctx.query.state.trim() : ''; const businessCode = this.parsePlatformOauthBindBusinessCode(state); const failCacheKey = businessCode ? `bind_pdd_code_fail:${businessCode}` : ''; const markBindFailed = async reason => { if (!businessCode || !failCacheKey) { return; } try { await this.app.setCacheAsync(failCacheKey, { status: 'failed', message: reason || '绑定失败,请重新授权', }); await service.systems.platform.publishPlatformOauthBindEvent(businessCode, { status: 'failed', message: reason || '绑定失败,请重新授权', }); } catch (error) { this.ctx.logger.error('[platform-oauth-bind] 失败标记写入异常: %s', error && error.message ? error.message : error); } }; if (!code || !state) { await markBindFailed('绑定失败,请重新授权'); await this.renderPlatformOauthBindResultPage(false); return; } if (!businessCode) { await this.renderPlatformOauthBindResultPage(false); return; } const pddResult = await this.pdd(code); if (!pddResult || pddResult.success === false) { await markBindFailed('绑定失败,请重新授权'); await this.renderPlatformOauthBindResultPage(false); return; } const oauthData = pddResult.result && pddResult.result.data ? pddResult.result.data : pddResult.result; const accessToken = oauthData && typeof oauthData.access_token === 'string' ? oauthData.access_token.trim() : ''; if (!accessToken) { await markBindFailed('绑定失败,请重新授权'); await this.renderPlatformOauthBindResultPage(false); return; } try { await this.app.setCacheAsync(`bind_pdd_code:${businessCode}`, accessToken); if (typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(failCacheKey); } else { await this.app.setCacheAsync(failCacheKey, null, 1); } await service.systems.platform.publishPlatformOauthBindEvent(businessCode, { status: 'success', access_token: accessToken, }); } catch (error) { this.ctx.logger.error('[platform-oauth-bind] 缓存写入失败: %s', error && error.message ? error.message : error); await markBindFailed('绑定失败,请重新授权'); await this.renderPlatformOauthBindResultPage(false); return; } await this.renderPlatformOauthBindResultPage(true); } /** * 查询拼多多绑定授权码的轮询状态。 * * 根据 code 先查成功缓存,再查失败标记,最终返回 success / failed / pending 三态。 * * @return {Promise} 无返回值。 */ async queryPddCode() { const code = this.ctx.params && typeof this.ctx.params.code === 'string' ? this.ctx.params.code.trim() : ''; if (!code) { this.ctx.status = 400; this.ctx.body = toFailure({ httpStatus: 400, message: 'code不能为空', data: { status: 'failed', message: 'code不能为空', }, }); return; } const successCacheKey = `bind_pdd_code:${code}`; const failCacheKey = `bind_pdd_code_fail:${code}`; let accessToken = ''; try { const cachedToken = await this.app.getCacheAsync(successCacheKey); accessToken = typeof cachedToken === 'string' ? cachedToken.trim() : ''; } catch (error) { this.ctx.logger.error('[query-pdd-code] 查询 access_token 缓存异常: %s', error && error.message ? error.message : error); } if (accessToken) { this.ctx.body = toSuccess({ status: 'success', access_token: accessToken, }); return; } let failedCacheValue = null; try { failedCacheValue = await this.app.getCacheAsync(failCacheKey); } catch (error) { this.ctx.logger.error('[query-pdd-code] 查询失败标记缓存异常: %s', error && error.message ? error.message : error); } if (failedCacheValue !== null && failedCacheValue !== undefined && failedCacheValue !== '') { const failedMessage = '绑定失败,请重新授权'; this.ctx.status = 200; this.ctx.body = toFailure({ httpStatus: 200, message: failedMessage, data: { status: 'failed', message: failedMessage, }, }); return; } const failedMessage = '绑定失败,请重新授权'; this.ctx.status = 200; this.ctx.body = toFailure({ httpStatus: 200, message: failedMessage, data: { status: 'failed', message: failedMessage, }, }); } /** * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 * @return {Promise} 无返回值。 */ async qimen() { const { ctx, service, } = this; const startTime = Date.now(); const logId = 'QL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); ctx.qimenLogId = logId; // 初始化日志数据 const logData = { log_id: logId, from_key: '', to_key: this.app.config.qimen.appKey, method: '', sign: '', costomer_id: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', result: '', use_time: 0, }; const getParams = ctx.query; // 记录基础日志信息 logData.from_key = getParams.app_key || ''; logData.method = getParams.method || ''; logData.sign = getParams.sign || ''; logData.costomer_id = getParams.customerId || getParams.customer_id || ''; logData.v = getParams.v || ''; try { // 验证必要参数 if (!this.validateQimenParams(getParams)) { const errorMsg = '参数缺失或错误'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); const appkey = getParams.app_key; const customerId = getParams.customerId; // 获取XML数据 let xmlData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 xmlData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 xmlData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 xmlData 是字符串 xmlData = xmlData ? String(xmlData) : ''; if (!xmlData || xmlData.trim() === '') { throw new Error('XML数据为空'); } // 解析XML数据 const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; const warehouseCode = this.getQimenWarehouseCode(xmlArray); if (!warehouseCode) { const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode'; const responseFormat = getParams.format || 'xml'; const response = this.errorResponse(errorMsg, responseFormat); ctx.body = response; ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json'; return; } logData.body = xmlData; const erpName = await service.qimen.getErpName(appkey); let api_info = { warehouseCode: '', ownerCode: '', }; if (warehouseCode && customerId) { // 验证接口是否存在且启用 api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode); if (!api_info) { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } const currentTime = new Date(); const authEndTime = new Date(api_info.warehouse_auth_end); const authEndTime2 = new Date(api_info.auth_end); if (authEndTime2 < currentTime) { const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } if (authEndTime < currentTime) { const errorMsg = '仓库订阅过期,请联系仓库核实状态'; const response = this.errorResponse(errorMsg, 'xml'); ctx.body = response; ctx.type = 'application/xml'; return; } } // 调用业务方法 const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id, api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format); ctx.body = result; ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json'; } catch (error) { const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml'); ctx.body = response; ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json'; } finally { // 统一写入日志文件队列 logData.use_time = Date.now() - startTime; logData.result = typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body); if (logData.body && logData.body.length > 65535) { logData.body = logData.body.substring(0, 65535); } if (logData.result && logData.result.length > 65535) { logData.result = logData.result.substring(0, 65535); } // 日志落盘改为异步投递,避免阻塞主请求响应。 Promise.resolve(this.app.fileWriter.writeRecord('qimen-logs', logData)).catch(writeErr => { ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message); ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData)); }); } } /** * 归一化奇门字段值,过滤空白内容和占位符字符串。 * @param {string|number|null|undefined} value 待处理字段值。 * @return {string} 归一化后的字段值。 */ normalizeQimenFieldValue(value) { if (value === null || value === undefined) { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue || normalizedValue === 'warehouseCode') { return ''; } return normalizedValue; } /** * 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。 * @param {Object|Array|string|number|null|undefined} node 待扫描节点。 * @param {string} fieldName 目标字段名。 * @param {Set} [visited=new Set()] 循环引用保护集合。 * @return {string} 找到的有效字段值。 */ findQimenFieldValue(node, fieldName, visited = new Set()) { if (node === null || node === undefined) { return ''; } if (typeof node !== 'object') { return ''; } if (visited.has(node)) { return ''; } visited.add(node); if (Array.isArray(node)) { for (const item of node) { const value = this.findQimenFieldValue(item, fieldName, visited); if (value) { return value; } } return ''; } if (Object.prototype.hasOwnProperty.call(node, fieldName)) { const directValue = this.normalizeQimenFieldValue(node[fieldName]); if (directValue) { return directValue; } const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited); if (nestedValue) { return nestedValue; } } for (const [ key, value ] of Object.entries(node)) { if (key === fieldName) { continue; } if (value === null || value === undefined) { continue; } if (typeof value !== 'object') { continue; } const foundValue = this.findQimenFieldValue(value, fieldName, visited); if (foundValue) { return foundValue; } } return ''; } /** * 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。 * @param {Object} xmlArray 解析后的 XML 数据。 * @return {string} 有效的仓库编码。 */ getQimenWarehouseCode(xmlArray) { const request = xmlArray?.request || xmlArray || {}; const fixedPaths = [ request?.deliveryOrder?.warehouseCode, request?.entryOrder?.warehouseCode, request.warehouseCode, ]; for (const value of fixedPaths) { const normalizedValue = this.normalizeQimenFieldValue(value); if (normalizedValue) { return normalizedValue; } } return this.findQimenFieldValue(request, 'warehouseCode') || this.findQimenFieldValue(xmlArray, 'warehouseCode') || ''; } validateParams(params) { const required = [ 'method', 'v', 'format', 'timestamp' ]; for (const field of required) { if (!params[field]) { return false; } } // 验证method格式 if (typeof params.method !== 'string' || !params.method.includes('.')) { return false; } return true; } validateQimenParams(params) { const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ]; for (const field of required) { if (!params[field]) { return false; } } // 验证method格式 if (typeof params.method !== 'string' || !params.method.includes('.')) { return false; } return true; } errorResponse(message, format = 'json') { const timestamp = Math.floor(Date.now() / 1000); if (format.toLowerCase() === 'xml') { return ` failure 0 ${this.escapeXml(message)} `; } return { flag: false, message, code: 0, timestamp, }; } escapeXml(unsafe) { if (!unsafe) return ''; return unsafe.replace(/[<>&'"]/g, c => { switch (c) { case '<': return '<'; case '>': return '>'; case '&': return '&'; case '\'': return '''; case '"': return '"'; default: return c; } }); } async pda() { const { ctx, service, } = this; ctx.query_count = 1; const startTime = Date.now(); const logData = { method: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', headers: JSON.stringify(ctx.headers), result: '', use_time: 0, auth: '', store_id: null, }; try { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); if (!requestCheck.ok) { const response = toFailure({ message: requestCheck.message, httpStatus: requestCheck.status, code: requestCheck.code, }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } const authHeader = ctx.headers.authorization; // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); // 获取JSON数据 let jsonData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 jsonData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 jsonData 是字符串 jsonData = jsonData ? String(jsonData) : ''; logData.body = jsonData; if (!jsonData || jsonData.trim() === '') { throw new Error('json数据为空'); } try { jsonData = JSON.parse(jsonData); } catch (e) { throw new Error('json数据解析错误'); } // 调用业务方法 const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader); // 记录成功响应 logData.result = typeof result === 'string' ? result : JSON.stringify(result); if (ctx.user) { logData.auth = JSON.stringify(ctx.user); logData.store_id = ctx.user.store_id; } if (isLog) { service.system.saveLog(logData, startTime); } if (result.status && result.status !== 200) { ctx.body = toFailure({ message: result.message || '请求失败', httpStatus: result.status, code: result.code, data: result.data || null, }); } else { ctx.body = toSuccess(result.data); } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); const response = toFailure({ message: '接口错误: ' + error.message, httpStatus: 500, code: 500, }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; ctx.type = 'application/json'; } } async system() { const { ctx, service, } = this; ctx.query_count = 1; const startTime = Date.now(); const logData = { method: '', v: '', url: ctx.request.href, created_at: new Date(), body: '', headers: JSON.stringify(ctx.headers), result: '', use_time: 0, auth: '', store_id: null, }; try { const getParams = ctx.query; logData.method = getParams.method || ''; logData.v = getParams.v || ''; const requestCheck = service.system.validateRequestContext(getParams, ctx.headers); if (!requestCheck.ok) { const response = toFailure({ message: requestCheck.message, httpStatus: requestCheck.status, code: requestCheck.code, }); logData.result = response; service.system.saveLog(logData, startTime); ctx.body = response; ctx.status = requestCheck.status; ctx.type = 'application/json'; return; } const authHeader = ctx.headers.authorization; ctx.device = ctx.headers.device; ctx.project = ctx.headers.project; // 处理method参数 const method = getParams.method; const methods = method.split('.'); const actionName = methods.pop(); const className = methods.map((item, index) => (index === methods.length - 1 ? item : item) ).join('.'); // 获取JSON数据 let jsonData = ''; if (ctx.request.rawBody) { // 使用 rawBody 获取原始请求体 jsonData = ctx.request.rawBody; } else { // 如果没有 rawBody,尝试从流中读取 jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } // 确保 jsonData 是字符串 jsonData = jsonData ? String(jsonData) : ''; logData.body = jsonData; if (!jsonData || jsonData.trim() === '') { throw new Error('json数据为空'); } try { jsonData = JSON.parse(jsonData); } catch (e) { throw new Error('json数据解析错误'); } // 调用业务方法 const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader); // 记录成功响应 logData.result = typeof result === 'string' ? result : JSON.stringify(result); if (ctx.user) { logData.auth = JSON.stringify(ctx.user); logData.store_id = ctx.user.store_id; } if (isLog) { service.system.saveLog(logData, startTime); } if (result.status && result.status !== 200) { ctx.body = toFailure({ message: result.message || '请求失败', httpStatus: result.status, code: result.code, data: result.data || null, }); } else { ctx.body = toSuccess(result.data); } ctx.type = 'application/json'; ctx.status = result.status || 200; } catch (error) { ctx.status = 500; console.log(error); const response = toFailure({ message: '接口错误: ' + error.message, httpStatus: 500, code: 500, }); logData.result = typeof response === 'string' ? response : JSON.stringify(response); service.system.saveLog(logData, startTime); ctx.body = response; ctx.type = 'application/json'; } } } module.exports = HomeController;