feat: 完善协议管理、师傅资质认证、分账配置并完成测试环境全量部署与同步
这个提交包含在:
@@ -4,14 +4,16 @@
|
||||
import { get, post, uploadFile } from './request';
|
||||
|
||||
export default {
|
||||
/* ---------- 公共 / 上传 ---------- */
|
||||
/* ---------- 公共 / 上传 / 字典 ---------- */
|
||||
upload: (filePath, category = 'other') => uploadFile(filePath, category),
|
||||
areas: (data = {}) => get('/common/areas', data, { silent: true }),
|
||||
expressCompanies: () => get('/common/expressCompanies', {}, { silent: true }),
|
||||
commonDicts: () => get('/common/dicts', {}, { silent: true }),
|
||||
|
||||
/* ---------- 鉴权 ---------- */
|
||||
login: (data) => post('/auth/login', data, { silent: true }),
|
||||
wxLogin: (data) => post('/auth/wxlogin', data, { silent: true }),
|
||||
wxPhoneLogin: (data) => post('/auth/wxPhoneLogin', data, { silent: true }),
|
||||
sendSms: (data) => post('/sms/send', data, { silent: true }),
|
||||
switchRole: (data) => post('/auth/switchRole', data),
|
||||
profile: () => get('/auth/profile'),
|
||||
saveAccount: (data) => post('/auth/saveAccount', data),
|
||||
@@ -28,6 +30,7 @@ export default {
|
||||
masterCount: (data) => get('/home/masterCount', data),
|
||||
orderCase: (id) => get('/home/orderCase', { id: id }, { silent: true }),
|
||||
agreement: (type, opt) => get('/home/agreement', { type: type }, opt || { silent: true }),
|
||||
agreementRead: (data, opt) => post('/home/agreementRead', data, Object.assign({ silent: true, allowConcurrent: true }, opt || {})),
|
||||
|
||||
/* ---------- 地址 ---------- */
|
||||
addressList: () => get('/address/index'),
|
||||
@@ -40,6 +43,7 @@ export default {
|
||||
orderCreate: (data) => post('/order/create', data),
|
||||
detectExpress: (data) => get('/order/detectExpress', data),
|
||||
orderPay: (data) => post('/order/pay', data),
|
||||
orderConfirmPay: (data) => post('/order/confirmPay', data, { silent: true, allowConcurrent: true }),
|
||||
orderCancel: (data) => post('/order/cancel', data),
|
||||
orderDelete: (data) => post('/order/delete', data),
|
||||
orderVerify: (data) => post('/order/verify', data),
|
||||
@@ -63,6 +67,7 @@ export default {
|
||||
|
||||
/* ---------- 师傅端 ---------- */
|
||||
masterApply: (data) => post('/master/apply', data),
|
||||
masterOcrIdCard: (data) => post('/master/ocrIdCard', data),
|
||||
masterInfo: () => get('/master/info'),
|
||||
masterHall: (data) => get('/master/hall', data),
|
||||
masterOrderDetail: (id, params) => get('/master/orderDetail', { id: id, ...(params || {}) }),
|
||||
@@ -77,14 +82,25 @@ export default {
|
||||
masterRequestDiff: (data) => post('/master/requestDiff', data),
|
||||
masterIncome: () => get('/master/income'),
|
||||
masterToggle: (data) => post('/master/toggleWork', data),
|
||||
masterUpdateLocation: (data) => post('/master/updateLocation', data),
|
||||
masterSearchLocation: (data) => get('/master/searchLocation', data, { silent: true }),
|
||||
masterLocationContext: (data) => get('/master/locationContext', data, { silent: true }),
|
||||
masterLocationStats: (data) => get('/master/locationOrderStats', data, { silent: true }),
|
||||
masterLocateCity: (data) => get('/master/locateCity', data),
|
||||
masterCredit: () => get('/master/credit'),
|
||||
masterAppeals: () => get('/master/appeals'),
|
||||
masterAppeal: (data) => post('/master/appeal', data),
|
||||
masterQuotes: () => get('/master/quotes'),
|
||||
masterQuote: (data) => post('/master/quote', data),
|
||||
masterWithdraw: (data) => post('/master/withdraw', data),
|
||||
masterTransferPackage: (data) => post('/master/transferPackage', data),
|
||||
masterSyncWithdraw: (data) => post('/master/syncWithdraw', data, { silent: true, allowConcurrent: true }),
|
||||
masterSkillDict: () => get('/master/skillDict'),
|
||||
masterSaveSkills: (data) => post('/master/saveSkills', data),
|
||||
masterCerts: () => get('/master/certs'),
|
||||
masterCertDetail: (params) => get('/master/certDetail', params),
|
||||
masterSaveCert: (data) => post('/master/saveCert', data),
|
||||
masterDeleteCert: (data) => post('/master/deleteCert', data),
|
||||
|
||||
/* ---------- 评价 ---------- */
|
||||
reviewCreate: (data) => post('/review/create', data),
|
||||
|
||||
407
yjyf-app/utils/location.js
普通文件
407
yjyf-app/utils/location.js
普通文件
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* 多端实时定位、微信小程序原生授权与定位缓存工具
|
||||
* - 微信小程序端:直接触发官方原生授权(wx.getLocation / wx.authorize)及设置页(wx.openSetting),不阻塞、不伪造假权限弹窗
|
||||
* - H5 端:调用浏览器 Geolocation API,失败或被拒时安全回传状态供上层拉起天地图地点选择面板
|
||||
* - 严禁返回假经纬度或 mock 数据
|
||||
*/
|
||||
|
||||
import { tiandituWebKey } from '@/config/config.js';
|
||||
|
||||
const MANUAL_LOC_KEY = 'yjyf_master_manual_loc_v1';
|
||||
const RECENT_LOCS_KEY = 'yjyf_master_recent_locs_v1';
|
||||
const MANUAL_LOC_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const MAX_RECENT_LOCS = 6;
|
||||
|
||||
let tiandituScriptPromise = null;
|
||||
|
||||
/**
|
||||
* 读取用户近期主动确认/选择过的接单定位
|
||||
* @returns {{ lat: number, lng: number, label: string, city: string, district?: string, serveRadius?: number, updatedAt: number } | null}
|
||||
*/
|
||||
export function getSavedManualLocation() {
|
||||
try {
|
||||
const raw = uni.getStorageSync(MANUAL_LOC_KEY);
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const lat = Number(raw.lat);
|
||||
const lng = Number(raw.lng);
|
||||
const updatedAt = Number(raw.updatedAt) || 0;
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng) || (Math.abs(lat) < 0.0001 && Math.abs(lng) < 0.0001)) {
|
||||
return null;
|
||||
}
|
||||
if (updatedAt > 0 && Date.now() - updatedAt > MANUAL_LOC_TTL_MS) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
lat,
|
||||
lng,
|
||||
label: String(raw.label || ''),
|
||||
city: String(raw.city || ''),
|
||||
district: String(raw.district || ''),
|
||||
serveRadius: Number(raw.serveRadius) || 0,
|
||||
updatedAt
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存用户主动定位或选定的真实经纬度坐标
|
||||
*/
|
||||
export function saveManualLocation({ lat, lng, label = '', city = '', district = '', serveRadius = 0 }) {
|
||||
const latNum = Number(lat);
|
||||
const lngNum = Number(lng);
|
||||
if (!Number.isFinite(latNum) || !Number.isFinite(lngNum)) return;
|
||||
try {
|
||||
uni.setStorageSync(MANUAL_LOC_KEY, {
|
||||
lat: Number(latNum.toFixed(6)),
|
||||
lng: Number(lngNum.toFixed(6)),
|
||||
label: String(label || ''),
|
||||
city: String(city || ''),
|
||||
district: String(district || ''),
|
||||
serveRadius: Number(serveRadius) || 0,
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除缓存的定位信息
|
||||
*/
|
||||
export function clearSavedManualLocation() {
|
||||
try {
|
||||
uni.removeStorageSync(MANUAL_LOC_KEY);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取最近真实使用/确认过的接单位置记录
|
||||
*/
|
||||
export function getRecentLocations() {
|
||||
try {
|
||||
const raw = uni.getStorageSync(RECENT_LOCS_KEY);
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.filter((item) => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const lat = Number(item.lat);
|
||||
const lng = Number(item.lng);
|
||||
return Number.isFinite(lat) && Number.isFinite(lng) && (Math.abs(lat) > 0.0001 || Math.abs(lng) > 0.0001);
|
||||
});
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入一条最近真实选定的位置记录(自动去重与限制数量)
|
||||
*/
|
||||
export function saveRecentLocation({ lat, lng, name = '', address = '', city = '', district = '' }) {
|
||||
const latNum = Number(lat);
|
||||
const lngNum = Number(lng);
|
||||
if (!Number.isFinite(latNum) || !Number.isFinite(lngNum)) return [];
|
||||
const normLat = Number(latNum.toFixed(6));
|
||||
const normLng = Number(lngNum.toFixed(6));
|
||||
const key = `${normLat.toFixed(4)}_${normLng.toFixed(4)}`;
|
||||
const list = getRecentLocations().filter((it) => it.key !== key && it.name !== name);
|
||||
const next = [
|
||||
{
|
||||
key,
|
||||
lat: normLat,
|
||||
lng: normLng,
|
||||
name: String(name || city || '已选位置'),
|
||||
address: String(address || ''),
|
||||
city: String(city || ''),
|
||||
district: String(district || ''),
|
||||
updatedAt: Date.now()
|
||||
},
|
||||
...list
|
||||
].slice(0, MAX_RECENT_LOCS);
|
||||
try {
|
||||
uni.setStorageSync(RECENT_LOCS_KEY, next);
|
||||
} catch (e) {}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除指定最近位置记录
|
||||
*/
|
||||
export function removeRecentLocation(key) {
|
||||
const next = getRecentLocations().filter((it) => it.key !== key);
|
||||
try {
|
||||
uni.setStorageSync(RECENT_LOCS_KEY, next);
|
||||
} catch (e) {}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空最近使用位置记录
|
||||
*/
|
||||
export function clearRecentLocations() {
|
||||
try {
|
||||
uni.removeStorageSync(RECENT_LOCS_KEY);
|
||||
} catch (e) {}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* H5 端动态加载天地图 JavaScript API v4.0
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export function loadTiandituScript() {
|
||||
// #ifdef H5
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
||||
return Promise.reject(new Error('非浏览器环境'));
|
||||
}
|
||||
if (window.T && typeof window.T.Map === 'function') {
|
||||
return Promise.resolve(window.T);
|
||||
}
|
||||
if (tiandituScriptPromise) {
|
||||
return tiandituScriptPromise;
|
||||
}
|
||||
tiandituScriptPromise = new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
tiandituScriptPromise = null;
|
||||
reject(new Error('天地图脚本加载超时'));
|
||||
}, 6500);
|
||||
|
||||
if (!document.getElementById('yjyf-tianditu-css')) {
|
||||
const link = document.createElement('link');
|
||||
link.id = 'yjyf-tianditu-css';
|
||||
link.rel = 'stylesheet';
|
||||
link.href = 'https://api.tianditu.gov.cn/v4.0/css/tianditu4.0.css';
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
const existing = document.getElementById('yjyf-tianditu-sdk');
|
||||
if (existing) {
|
||||
existing.remove();
|
||||
}
|
||||
const script = document.createElement('script');
|
||||
script.id = 'yjyf-tianditu-sdk';
|
||||
script.type = 'text/javascript';
|
||||
script.async = true;
|
||||
script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${encodeURIComponent(tiandituWebKey)}`;
|
||||
script.onload = () => {
|
||||
clearTimeout(timer);
|
||||
if (window.T && typeof window.T.Map === 'function') {
|
||||
resolve(window.T);
|
||||
} else {
|
||||
tiandituScriptPromise = null;
|
||||
reject(new Error('天地图对象初始化失败'));
|
||||
}
|
||||
};
|
||||
script.onerror = () => {
|
||||
clearTimeout(timer);
|
||||
tiandituScriptPromise = null;
|
||||
reject(new Error('天地图脚本加载失败'));
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return tiandituScriptPromise;
|
||||
// #endif
|
||||
|
||||
// #ifndef H5
|
||||
return Promise.reject(new Error('仅 H5 端加载天地图 Web SDK'));
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测当前设备位置权限状态
|
||||
* @returns {Promise<'granted'|'denied'|'prompt'|'unavailable'>}
|
||||
*/
|
||||
export function checkLocationPermissionStatus() {
|
||||
return new Promise((resolve) => {
|
||||
// #ifdef MP-WEIXIN
|
||||
uni.getSetting({
|
||||
success: (res) => {
|
||||
const setting = res && res.authSetting ? res.authSetting : {};
|
||||
if (setting['scope.userLocation'] === true) {
|
||||
resolve('granted');
|
||||
} else if (setting['scope.userLocation'] === false) {
|
||||
resolve('denied');
|
||||
} else {
|
||||
resolve('prompt');
|
||||
}
|
||||
},
|
||||
fail: () => resolve('prompt')
|
||||
});
|
||||
return;
|
||||
// #endif
|
||||
|
||||
// #ifdef H5
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
resolve('unavailable');
|
||||
return;
|
||||
}
|
||||
if (typeof window !== 'undefined' && window.isSecureContext === false) {
|
||||
resolve('unavailable');
|
||||
return;
|
||||
}
|
||||
if (navigator.permissions && typeof navigator.permissions.query === 'function') {
|
||||
navigator.permissions.query({ name: 'geolocation' })
|
||||
.then((status) => {
|
||||
const state = status && status.state ? status.state : 'prompt';
|
||||
if (state === 'granted' || state === 'denied' || state === 'prompt') {
|
||||
resolve(state);
|
||||
} else {
|
||||
resolve('prompt');
|
||||
}
|
||||
})
|
||||
.catch(() => resolve('prompt'));
|
||||
} else {
|
||||
resolve('prompt');
|
||||
}
|
||||
return;
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN || H5
|
||||
resolve('prompt');
|
||||
// #endif
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 真实获取当前设备经纬度坐标
|
||||
* 注意:在微信小程序 `prompt` 状态下调用会直接弹出微信官方底部定位授权弹窗
|
||||
* @param {{ timeout?: number, enableHighAccuracy?: boolean }} options
|
||||
* @returns {Promise<{ ok: boolean, lat?: number, lng?: number, reason?: string, message?: string }>}
|
||||
*/
|
||||
export function getCurrentCoordinates(options = {}) {
|
||||
const timeout = Number(options.timeout) > 0 ? Number(options.timeout) : 5000;
|
||||
const enableHighAccuracy = Boolean(options.enableHighAccuracy);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// #ifdef H5
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
resolve({ ok: false, reason: 'unavailable', message: '当前浏览器不支持自动定位,请在下方搜索选择位置' });
|
||||
return;
|
||||
}
|
||||
if (typeof window !== 'undefined' && window.isSecureContext === false) {
|
||||
resolve({ ok: false, reason: 'unavailable', message: '非 HTTPS 环境限制自动定位,请在下方搜索选择位置' });
|
||||
return;
|
||||
}
|
||||
let settled = false;
|
||||
const guardTimer = setTimeout(() => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve({ ok: false, reason: 'timeout', message: '获取当前位置超时,可搜索选择所在地区' });
|
||||
}
|
||||
}, timeout + 400);
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(guardTimer);
|
||||
const coords = pos && pos.coords ? pos.coords : null;
|
||||
if (coords && Number.isFinite(coords.latitude) && Number.isFinite(coords.longitude)) {
|
||||
resolve({
|
||||
ok: true,
|
||||
lat: Number(coords.latitude.toFixed(6)),
|
||||
lng: Number(coords.longitude.toFixed(6))
|
||||
});
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'error', message: '未获取到有效坐标,请手动选择位置' });
|
||||
}
|
||||
},
|
||||
(err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(guardTimer);
|
||||
const code = err && typeof err.code === 'number' ? err.code : 0;
|
||||
if (code === 1) {
|
||||
resolve({ ok: false, reason: 'denied', message: '位置权限未开启,请允许浏览器访问位置或搜索选择位置' });
|
||||
} else if (code === 3) {
|
||||
resolve({ ok: false, reason: 'timeout', message: '获取当前位置超时,可搜索选择所在地区' });
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'unavailable', message: '当前设备定位服务不可用,请直接搜索选择所在位置' });
|
||||
}
|
||||
},
|
||||
{
|
||||
enableHighAccuracy,
|
||||
timeout,
|
||||
maximumAge: 60000
|
||||
}
|
||||
);
|
||||
return;
|
||||
// #endif
|
||||
|
||||
// #ifndef H5
|
||||
uni.getLocation({
|
||||
type: 'gcj02',
|
||||
success: (res) => {
|
||||
if (res && Number.isFinite(Number(res.latitude)) && Number.isFinite(Number(res.longitude))) {
|
||||
resolve({
|
||||
ok: true,
|
||||
lat: Number(Number(res.latitude).toFixed(6)),
|
||||
lng: Number(Number(res.longitude).toFixed(6))
|
||||
});
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'error', message: '定位坐标无效' });
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
const msg = String((err && (err.errMsg || err.message)) || '').toLowerCase();
|
||||
if (msg.includes('auth') || msg.includes('deny') || msg.includes('denied') || msg.includes('permission')) {
|
||||
resolve({ ok: false, reason: 'denied', message: '您尚未开启位置权限' });
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'error', message: '定位失败,请检查手机定位开关或手动选择位置' });
|
||||
}
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接在点击手势中打开微信小程序设置页(必须同步由点击回调触发)
|
||||
* @returns {Promise<{ ok: boolean, lat?: number, lng?: number, reason?: string, message?: string }>}
|
||||
*/
|
||||
export function openMiniProgramLocationSettingSync() {
|
||||
return new Promise((resolve) => {
|
||||
// #ifdef MP-WEIXIN
|
||||
uni.openSetting({
|
||||
success: async (res) => {
|
||||
const auth = res && res.authSetting ? res.authSetting : {};
|
||||
if (auth['scope.userLocation'] === true) {
|
||||
const loc = await getCurrentCoordinates();
|
||||
resolve(loc);
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'denied', message: '位置权限仍处于关闭状态' });
|
||||
}
|
||||
},
|
||||
fail: () => {
|
||||
// 若环境限制无法直接打开 openSetting,使用原生模态框二次确认(确认回调属于有效用户点击手势)
|
||||
uni.showModal({
|
||||
title: '开启位置权限',
|
||||
content: '请在小程序设置中允许使用“位置信息”,以便为您推荐附近工单',
|
||||
confirmText: '去设置',
|
||||
confirmColor: '#F0710D',
|
||||
success: (mRes) => {
|
||||
if (!mRes.confirm) {
|
||||
resolve({ ok: false, reason: 'denied', message: '已取消' });
|
||||
return;
|
||||
}
|
||||
uni.openSetting({
|
||||
success: async (sRes) => {
|
||||
const auth = sRes && sRes.authSetting ? sRes.authSetting : {};
|
||||
if (auth['scope.userLocation'] === true) {
|
||||
const loc = await getCurrentCoordinates();
|
||||
resolve(loc);
|
||||
} else {
|
||||
resolve({ ok: false, reason: 'denied', message: '位置权限尚未开启' });
|
||||
}
|
||||
},
|
||||
fail: () => resolve({ ok: false, reason: 'error', message: '无法打开授权设置,可手动选择区域' })
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
return;
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
resolve({ ok: false, reason: 'unsupported', message: '非小程序环境' });
|
||||
// #endif
|
||||
});
|
||||
}
|
||||
251
yjyf-app/utils/pay.js
普通文件
251
yjyf-app/utils/pay.js
普通文件
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* 微信小程序真实支付(APIv3 JSAPI)与师傅端新版商家转账确认收款封装
|
||||
*/
|
||||
import api from './api.js';
|
||||
|
||||
/**
|
||||
* 安全获取当前微信登录凭证 code(非微信小程序环境或获取失败时返回空串)
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export function getSafeWxCode() {
|
||||
// #ifdef MP-WEIXIN
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finishErr = (msg) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
uni.showToast({ title: msg, icon: 'none' });
|
||||
reject(Object.assign(new Error(msg), { handledToast: true }));
|
||||
};
|
||||
const finishOk = (code) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(code);
|
||||
};
|
||||
const timer = setTimeout(() => finishErr('获取微信登录凭证超时,请检查网络后重试'), 5000);
|
||||
try {
|
||||
uni.login({
|
||||
provider: 'weixin',
|
||||
success: (res) => {
|
||||
clearTimeout(timer);
|
||||
const code = res && res.code ? String(res.code).trim() : '';
|
||||
if (!code) {
|
||||
finishErr('未能获取到微信登录凭证,请重新进入小程序再试');
|
||||
return;
|
||||
}
|
||||
finishOk(code);
|
||||
},
|
||||
fail: (err) => {
|
||||
clearTimeout(timer);
|
||||
const detail = err && err.errMsg ? `(${err.errMsg})` : '';
|
||||
finishErr(`获取微信登录凭证失败${detail},请重试`);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
clearTimeout(timer);
|
||||
finishErr('调起微信登录失败,请重试');
|
||||
}
|
||||
});
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
return Promise.resolve('');
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一发起用户端订单微信支付并完成主动查单核销
|
||||
* 适用场景:订单首次支付(api.orderPay)、选定师傅报价支付(api.orderChooseQuote)、施工现场增项补差价支付(api.orderPayDiff)
|
||||
*
|
||||
* @param {Function} createPayApiFn 后端统一下单接口方法
|
||||
* @param {Object} params 业务入参(如 { order_id } 或 { order_id, quote_id })
|
||||
* @returns {Promise<Object>}
|
||||
*/
|
||||
export async function executeOrderWxPay(createPayApiFn, params = {}) {
|
||||
const wxCode = await getSafeWxCode();
|
||||
const payload = Object.assign({}, params);
|
||||
if (wxCode) {
|
||||
payload.wx_code = wxCode;
|
||||
}
|
||||
|
||||
const res = await createPayApiFn(payload);
|
||||
|
||||
// 0 元优惠券全额抵扣或已付足无需补付时,后端直接完成核销并返回 paid: true
|
||||
if (res && (res.paid === true || res.need_wxpay === false)) {
|
||||
return res;
|
||||
}
|
||||
|
||||
if (!res || !res.pay_params) {
|
||||
const msg = '未获取到有效的微信支付参数,请稍后重试';
|
||||
uni.showToast({ title: msg, icon: 'none' });
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
const p = res.pay_params;
|
||||
await new Promise((resolve, reject) => {
|
||||
uni.requestPayment({
|
||||
provider: 'weixin',
|
||||
timeStamp: String(p.timeStamp),
|
||||
nonceStr: String(p.nonceStr),
|
||||
package: String(p.package),
|
||||
signType: String(p.signType || 'RSA'),
|
||||
paySign: String(p.paySign),
|
||||
success: () => resolve(true),
|
||||
fail: (err) => {
|
||||
const errMsg = String((err && err.errMsg) || '');
|
||||
const isCancel = errMsg.indexOf('cancel') !== -1;
|
||||
const tip = isCancel ? '已取消微信支付' : '微信支付未完成,请重试';
|
||||
uni.showToast({ title: tip, icon: 'none' });
|
||||
reject(Object.assign(new Error(tip), { cancelled: isCancel, raw: err }));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 收银台扣款成功后,主动请求后端向微信网关查单核销(绝不返回伪造的已支付状态)
|
||||
const verifyOnce = () => api.orderConfirmPay({
|
||||
out_trade_no: res.out_trade_no,
|
||||
order_id: res.order_id
|
||||
});
|
||||
|
||||
let confirmRes;
|
||||
try {
|
||||
confirmRes = await verifyOnce();
|
||||
if (confirmRes && confirmRes.paid !== true && ['USERPAYING', 'NOTPAY'].includes(confirmRes.trade_state)) {
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
confirmRes = await verifyOnce();
|
||||
}
|
||||
} catch (firstErr) {
|
||||
// 仅当为网络层临时中断(无业务响应码)时等待 900ms 复查一次;业务明确报错直接透传
|
||||
if (firstErr && firstErr.code === undefined) {
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
try {
|
||||
confirmRes = await verifyOnce();
|
||||
} catch (secondErr) {
|
||||
const errMsg = (secondErr && secondErr.message) || '向微信核销支付状态失败,请在订单详情刷新确认';
|
||||
uni.showToast({ title: errMsg, icon: 'none' });
|
||||
throw Object.assign(new Error(errMsg), { handledToast: true, raw: secondErr });
|
||||
}
|
||||
} else {
|
||||
const errMsg = (firstErr && firstErr.message) || '支付核销失败,请查看订单详情或联系客服';
|
||||
uni.showToast({ title: errMsg, icon: 'none' });
|
||||
throw Object.assign(new Error(errMsg), { handledToast: true, raw: firstErr });
|
||||
}
|
||||
}
|
||||
|
||||
if (!confirmRes || confirmRes.paid !== true) {
|
||||
const stateText = confirmRes && confirmRes.trade_state_text ? confirmRes.trade_state_text : '尚未确认到账';
|
||||
const msg = `支付暂未确认入账(${stateText}),请在订单详情刷新核实`;
|
||||
uni.showToast({ title: msg, icon: 'none' });
|
||||
throw Object.assign(new Error(msg), { handledToast: true, unconfirmed: true, data: confirmRes });
|
||||
}
|
||||
|
||||
return confirmRes;
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
uni.showModal({
|
||||
title: '请在微信小程序内支付',
|
||||
content: '当前运行环境不支持调起微信小程序收银台,请在微信小程序中打开订单完成支付。',
|
||||
showCancel: false,
|
||||
confirmText: '知道了'
|
||||
});
|
||||
throw Object.assign(new Error('请在微信小程序内完成支付'), { unsupportedEnv: true });
|
||||
// #endif
|
||||
}
|
||||
|
||||
/**
|
||||
* 师傅端调起微信官方「商家转账」确认收款页(wx.requestMerchantTransfer)并在返回后同步真实入账状态
|
||||
*
|
||||
* @param {Number} withdrawId 提现申请记录 ID
|
||||
* @returns {Promise<{ done: boolean, withdraw: Object|null }>}
|
||||
*/
|
||||
export async function invokeMerchantTransferConfirm(withdrawId) {
|
||||
const pkg = await api.masterTransferPackage({ withdraw_id: withdrawId });
|
||||
if (pkg && pkg.already_done) {
|
||||
uni.showToast({ title: '该笔提现已到账微信零钱', icon: 'none' });
|
||||
return { done: true, withdraw: pkg.withdraw || null };
|
||||
}
|
||||
|
||||
if (!pkg || !pkg.package_info || !pkg.mch_id || !pkg.app_id) {
|
||||
const msg = '未获取到收款确认凭证,请稍后刷新重试';
|
||||
uni.showToast({ title: msg, icon: 'none' });
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
const canUseTransfer = typeof wx !== 'undefined' && typeof wx.requestMerchantTransfer === 'function'
|
||||
&& (!wx.canIUse || wx.canIUse('requestMerchantTransfer'));
|
||||
if (!canUseTransfer) {
|
||||
uni.showModal({
|
||||
title: '请升级微信版本',
|
||||
content: '当前微信客户端版本过低,暂不支持商家转账确认收款,请升级至最新版微信后再试。',
|
||||
showCancel: false,
|
||||
confirmText: '知道了'
|
||||
});
|
||||
throw new Error('微信版本过低');
|
||||
}
|
||||
|
||||
let transferInvokeError = null;
|
||||
await new Promise((resolve) => {
|
||||
wx.requestMerchantTransfer({
|
||||
mchId: String(pkg.mch_id),
|
||||
appId: String(pkg.app_id),
|
||||
package: String(pkg.package_info),
|
||||
success: () => {
|
||||
resolve();
|
||||
},
|
||||
fail: (err) => {
|
||||
transferInvokeError = err || null;
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 无论用户点击确认收款还是左上角返回,均向后端发起一次真实网关状态同步,失败直接抛出真实原因
|
||||
try {
|
||||
const syncRes = await api.masterSyncWithdraw({ withdraw_id: withdrawId });
|
||||
if (syncRes && syncRes.done) {
|
||||
uni.showToast({ title: '收款成功,已入账微信零钱', icon: 'success' });
|
||||
return { done: true, withdraw: syncRes.withdraw || null };
|
||||
}
|
||||
const wd = syncRes ? syncRes.withdraw : null;
|
||||
if (wd && wd.status === 'reject') {
|
||||
const rejectReason = wd.fail_reason || wd.audit_msg || '微信转账失败或已失效';
|
||||
uni.showModal({
|
||||
title: '收款未能完成',
|
||||
content: rejectReason,
|
||||
showCancel: false,
|
||||
confirmText: '知道了'
|
||||
});
|
||||
return { done: false, withdraw: wd };
|
||||
}
|
||||
if (transferInvokeError) {
|
||||
const rawMsg = String(transferInvokeError.errMsg || '');
|
||||
const isCancel = rawMsg.indexOf('cancel') !== -1;
|
||||
uni.showToast({
|
||||
title: isCancel ? '您已取消确认收款,可随时再次点击领取' : `调起收款确认未完成(${rawMsg || '未知原因'})`,
|
||||
icon: 'none'
|
||||
});
|
||||
} else {
|
||||
const stTxt = wd && wd.status_text ? wd.status_text : '待确认收款';
|
||||
uni.showToast({ title: `当前状态:${stTxt}`, icon: 'none' });
|
||||
}
|
||||
return { done: false, withdraw: wd };
|
||||
} catch (syncErr) {
|
||||
const errMsg = (syncErr && syncErr.message) || '向微信同步收款状态失败,请稍后重试';
|
||||
uni.showToast({ title: errMsg, icon: 'none' });
|
||||
throw Object.assign(syncErr instanceof Error ? syncErr : new Error(errMsg), { handledToast: true });
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifndef MP-WEIXIN
|
||||
uni.showModal({
|
||||
title: '请在微信小程序内确认收款',
|
||||
content: '微信零钱商家转账需在微信小程序内拉起官方收款页,请使用微信小程序打开「我的钱包」领取。',
|
||||
showCancel: false,
|
||||
confirmText: '知道了'
|
||||
});
|
||||
throw Object.assign(new Error('请在微信小程序内确认收款'), { unsupportedEnv: true });
|
||||
// #endif
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import config from '@/config/config.js';
|
||||
|
||||
const BASE_URL = (config.baseUrl || config.dev).replace(/\/+$/, '') + '/api';
|
||||
export const BASE_URL = (config.baseUrl || config.dev).replace(/\/+$/, '') + '/api';
|
||||
|
||||
const TOKEN_KEY = 'yjyf_token';
|
||||
const USER_KEY = 'yjyf_user';
|
||||
|
||||
在新工单中引用
屏蔽一个用户