chore:替换了customer-service.js

This commit is contained in:
2026-01-31 08:59:30 +08:00
parent 7599a80943
commit a464a8731f

View File

@@ -2,68 +2,13 @@
* 客服统一处理服务 * 客服统一处理服务
* 整合各种客服方式,提供统一的调用接口 * 整合各种客服方式,提供统一的调用接口
*/ */
class CustomerService { export class CustomerService {
constructor(vueInstance, externalConfig = {}) { constructor(vueInstance, externalConfig = null) {
if (!vueInstance.$lang) {
throw new Error('CustomerService 必须在 Vue 实例中初始化');
}
this.vm = vueInstance; this.vm = vueInstance;
this.externalConfig = externalConfig; // 外部传入的最新配置(优先级最高) this.externalConfig = externalConfig; // 外部传入的最新配置(优先级最高)
this.latestPlatformConfig = null; this.latestPlatformConfig = null;
} }
getSupoortKeFuList() {
if (!this.vm) return [];
const vm = this.vm;
return [
{
id: 'weixin-official',
name: vm.$lang('customer.weChatKefu'),
isOfficial: true,
type: 'weapp'
},
{
id: 'custom-kefu',
name: vm.$lang('customer.systemKefu'),
isOfficial: false
},
{
id: 'qyweixin-kefu',
name: vm.$lang('customer.weChatWorkKefu'),
isOfficial: false
},
]
}
/**
* 打开客服选择弹窗
*/
openCustomerSelectPopupDialog() {
const kefu_list = this.getSupoortKeFuList();
const kefuNames = kefu_list.map(item => item.name);
uni.showActionSheet({
itemList: kefuNames,
success: (res) => {
const kefu = kefu_list[res.tapIndex];
this.externalConfig = kefu ?? this.externalConfig ?? {};
if (kefu.isOfficial) {
uni.openCustomerServiceConversation({
sessionFrom: 'weapp',
showMessageCard: true
});
} else if (kefu.id === 'custom-kefu') {
this.handleCustomerClick();
} else if (kefu.id === 'qyweixin-kefu') {
this.handleQyWeixinKefuClick();
}
}
});
}
/** /**
* 强制刷新配置(支持传入外部配置) * 强制刷新配置(支持传入外部配置)
* @param {Object} externalConfig 外部最新配置 * @param {Object} externalConfig 外部最新配置
@@ -83,28 +28,29 @@ class CustomerService {
return this.latestPlatformConfig; return this.latestPlatformConfig;
} }
// 优先级:外部传入的最新配置 > vuex配置 > 空对象 // 优先级:外部传入 > vuex store > 空对象
const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {}; const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {};
console.log(`【实时客服配置】`, servicerConfig); console.log(`【实时客服配置】`, servicerConfig);
let platformConfig = null; let platformConfig = null;
// #ifdef H5 // #ifdef H5
platformConfig = servicerConfig.h5 ? (typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null) : null; platformConfig = servicerConfig.h5 && typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null;
// #endif // #endif
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
platformConfig = servicerConfig.weapp ? (typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null) : null; platformConfig = servicerConfig.weapp && typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null;
// #endif // #endif
// #ifdef MP-ALIPAY // #ifdef MP-ALIPAY
platformConfig = servicerConfig.aliapp ? (typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null) : null; platformConfig = servicerConfig.aliapp && typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null;
// #endif // #endif
// #ifdef PC // #ifdef PC
platformConfig = servicerConfig.pc ? (typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null) : null; platformConfig = servicerConfig.pc && typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null;
// #endif // #endif
// 处理空数组情况你的配置中pc/aliapp是空数组转为null // 防止空数组被当作有效配置
if (Array.isArray(platformConfig)) { if (Array.isArray(platformConfig)) {
platformConfig = null; platformConfig = null;
} }
@@ -144,32 +90,18 @@ class CustomerService {
warnings: [] warnings: []
}; };
if (!config) { if (!config || !config.type) {
result.isValid = false;
result.errors.push('客服配置不存在');
return result;
}
if (config.type === 'aikefu') {
return result;
}
if (!config.type) {
result.isValid = false; result.isValid = false;
result.errors.push('客服类型未配置'); result.errors.push('客服类型未配置');
return result;
} }
if (config.type === 'wxwork') { if (config.type === 'wxwork') {
if (!wxworkConfig) { if (!wxworkConfig || !wxworkConfig.enable) {
result.isValid = false; result.warnings.push('企业微信未启用');
result.errors.push('企业微信配置不存在'); }
} else { if (!wxworkConfig.contact_url) {
if (!wxworkConfig.enable) { result.warnings.push('企业微信活码链接未配置');
result.warnings.push('企业微信功能未启用');
}
if (!wxworkConfig.contact_url) {
result.warnings.push('企业微信活码链接未配置,将使用原有客服方式');
}
} }
} }
@@ -177,16 +109,39 @@ class CustomerService {
} }
/** /**
* 跳转到AI客服页面 * 跳转到 AI 客服页面Dify
*/ */
openAIKeFuService() { openDifyService() {
const vm = this.vm; try {
vm.$util.redirectTo(vm.$util.AI_CHAT_PAGE_URL); // 清除未读数(如果存在)
if (typeof this.vm.setAiUnreadCount === 'function') {
this.vm.setAiUnreadCount(0);
}
// ✅ 修正路径:必须与 pages.json 中注册的路径一致
const aiChatUrl = '/pages_tool/ai-chat/index';
// ✅ 使用 navigateTo 保留返回栈(体验更好)
uni.navigateTo({
url: aiChatUrl,
fail: (err) => {
console.error('跳转 AI 客服失败:', err);
// H5 兜底
// #ifdef H5
window.location.href = aiChatUrl;
// #endif
uni.showToast({ title: '打开客服失败', icon: 'none' });
}
});
} catch (e) {
console.error('跳转 AI 客服异常:', e);
uni.showToast({ title: '打开客服失败', icon: 'none' });
}
} }
/** /**
* 处理客服点击事件 * 处理客服点击事件(统一入口)
* @param {Object} options 选项参数 * @param {Object} options 选项参数(用于消息卡片等)
*/ */
handleCustomerClick(options = {}) { handleCustomerClick(options = {}) {
const validation = this.validateConfig(); const validation = this.validateConfig();
@@ -201,51 +156,61 @@ class CustomerService {
} }
const config = this.getPlatformConfig(); const config = this.getPlatformConfig();
const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {}; console.log('【当前客服配置】', config);
console.log('【客服类型】', config.type);
const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
if (config.type === 'none') { if (config.type === 'none') {
this.showNoServicePopup(); this.showNoServicePopup();
return; return;
} }
// 核心分支:根据最新的type处理 // 核心路由:根据 type 决定行为
switch (config.type) { switch (config.type) {
case 'aikefu': case 'aikefu':
this.openAIKeFuService(); console.log('【跳转 AI 客服】目标路径: /pages_tool/ai-chat/index');
this.openDifyService();
break; break;
case 'wxwork': case 'wxwork':
console.log('【跳转企业微信客服】');
this.openWxworkService(false, config, options); this.openWxworkService(false, config, options);
break; break;
case 'third': case 'third':
console.log('【跳转第三方客服】');
this.openThirdService(config);
break;
case 'miniprogram':
console.log('【跳转第三方小程序客服】');
this.openThirdService(config); this.openThirdService(config);
break; break;
case 'niushop': case 'niushop':
console.log('【跳转牛商客服】');
this.openNiushopService(niushop); this.openNiushopService(niushop);
break; break;
case 'weapp': case 'weapp':
console.log('【跳转微信官方客服】');
this.openWeappService(config, options); this.openWeappService(config, options);
break; break;
case 'aliapp': case 'aliapp':
console.log('【跳转支付宝客服】');
this.openAliappService(config); this.openAliappService(config);
break; break;
default: default:
console.error('【未知客服类型】', config.type);
this.makePhoneCall(); this.makePhoneCall();
} }
} }
/** // ================== 各类型客服实现 ==================
* 打开企业微信客服
* @param {boolean} useOriginalService 是否使用原有客服方式
* @param {Object} servicerConfig 客服配置
* @param {Object} options 选项参数
*/
openWxworkService(useOriginalService = false, servicerConfig = null, options = {}) { openWxworkService(useOriginalService = false, servicerConfig = null, options = {}) {
const config = servicerConfig || this.getPlatformConfig(); const config = servicerConfig || this.getPlatformConfig();
const wxworkConfig = this.getWxworkConfig(); const wxworkConfig = this.getWxworkConfig();
const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {}; const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
if (wxworkConfig?.enable && wxworkConfig?.contact_url && !useOriginalService) { if (!useOriginalService && wxworkConfig?.enable && wxworkConfig?.contact_url) {
wx.navigateToMiniProgram({ wx.navigateToMiniProgram({
appId: 'wxeb490c6f9b154ef9', appId: 'wxeb490c6f9b154ef9',
path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`, path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`,
@@ -256,9 +221,16 @@ class CustomerService {
} }
}); });
} else { } else {
// 检查是否有企业微信配置
if (!config.wxwork_url && !config.corpid) {
console.error('企业微信配置不完整,缺少 wxwork_url 或 corpid');
uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
this.fallbackToPhoneCall();
return;
}
wx.openCustomerServiceChat({ wx.openCustomerServiceChat({
extInfo: { url: config.wxwork_url }, extInfo: { url: config.wxwork_url || '' },
corpId: config.corpid, corpId: config.corpid || '',
showMessageCard: true, showMessageCard: true,
sendMessageTitle, sendMessageTitle,
sendMessagePath, sendMessagePath,
@@ -268,227 +240,181 @@ class CustomerService {
// #endif // #endif
// #ifdef H5 // #ifdef H5
if (wxworkConfig?.enable && wxworkConfig?.contact_url) { if (!useOriginalService && wxworkConfig?.enable && wxworkConfig?.contact_url) {
window.location.href = wxworkConfig.contact_url; window.location.href = wxworkConfig.contact_url;
} else if (config.wxwork_url) { } else if (config.wxwork_url) {
location.href = config.wxwork_url; window.location.href = config.wxwork_url;
} else { } else {
this.fallbackToPhoneCall(); this.fallbackToPhoneCall();
} }
// #endif // #endif
} }
/**
* 打开第三方客服
* @param {Object} config 客服配置
*/
openThirdService(config) { openThirdService(config) {
console.log('【第三方客服配置】', config);
console.log('【配置字段】', Object.keys(config));
// 支持多种可能的字段名
const miniAppId = config.mini_app_id || config.miniAppId || config.appid || config.appId || config.app_id;
const miniAppPath = config.mini_app_path || config.miniAppPath || config.path || config.page_path || '';
console.log('【解析后的小程序配置】AppID:', miniAppId, 'Path:', miniAppPath);
// 优先处理第三方微信小程序客服
if (miniAppId) {
console.log('【跳转第三方小程序】AppID:', miniAppId, 'Path:', miniAppPath);
// #ifdef MP-WEIXIN
wx.navigateToMiniProgram({
appId: miniAppId,
path: miniAppPath,
success: () => {
console.log('【跳转第三方小程序成功】');
},
fail: (err) => {
console.error('【跳转第三方小程序失败】', err);
uni.showToast({ title: '跳转失败,请稍后重试', icon: 'none' });
}
});
// #endif
// #ifdef H5
uni.showToast({ title: '第三方小程序客服仅在微信小程序中可用', icon: 'none' });
// #endif
return;
}
// 处理第三方链接客服
if (config.third_url) { if (config.third_url) {
console.log('【跳转第三方链接】', config.third_url);
// #ifdef H5
window.location.href = config.third_url; window.location.href = config.third_url;
// #endif
// #ifdef MP-WEIXIN
uni.setClipboardData({
data: config.third_url,
success: () => {
uni.showToast({ title: '链接已复制,请在浏览器打开', icon: 'none' });
}
});
// #endif
} else { } else {
console.error('【第三方客服配置不完整】缺少 mini_app_id 或 third_url');
this.fallbackToPhoneCall(); this.fallbackToPhoneCall();
} }
} }
/**
* 打开牛商客服
* @param {Object} niushop 牛商参数
*/
openNiushopService(niushop) { openNiushopService(niushop) {
if (Object.keys(niushop).length > 0) { if (Object.keys(niushop).length > 0 && this.vm.$util?.redirectTo) {
this.vm.$util.redirectTo('/pages_tool/chat/room', niushop); this.vm.$util.redirectTo('/pages_tool/chat/room', niushop);
} else { } else {
this.makePhoneCall(); this.makePhoneCall();
} }
} }
/**
* 打开微信小程序客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
openWeappService(config, options = {}) { openWeappService(config, options = {}) {
if (!this.shouldUseCustomService(config)) { // 如果 useOfficial 为 true 或 undefined则使用原生系统客服由 button open-type="contact" 触发)
console.log('使用官方微信小程序客服'); // 此方法仅用于自定义跳转(如 useOfficial: false
if (config.useOfficial !== false) {
// 不做任何事,应由 <button open-type="contact"> 触发
console.log('使用微信官方客服,请确保按钮为 <button open-type="contact">');
return; return;
} }
console.log('使用自定义微信小程序客服');
this.handleCustomWeappService(config, options); this.handleCustomWeappService(config, options);
} }
/**
* 处理自定义微信小程序客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
handleCustomWeappService(config, options = {}) { handleCustomWeappService(config, options = {}) {
const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {};
if (config.customServiceUrl) { if (config.customServiceUrl) {
let url = config.customServiceUrl; let url = config.customServiceUrl;
const params = []; const params = [];
const { sendMessageTitle, sendMessagePath, sendMessageImg } = options;
if (sendMessageTitle) params.push(`title=${encodeURIComponent(sendMessageTitle)}`); if (sendMessageTitle) params.push(`title=${encodeURIComponent(sendMessageTitle)}`);
if (sendMessagePath) params.push(`path=${encodeURIComponent(sendMessagePath)}`); if (sendMessagePath) params.push(`path=${encodeURIComponent(sendMessagePath)}`);
if (sendMessageImg) params.push(`img=${encodeURIComponent(sendMessageImg)}`); if (sendMessageImg) params.push(`img=${encodeURIComponent(sendMessageImg)}`);
if (params.length > 0) { if (params.length > 0) {
url += (url.includes('?') ? '&' : '?') + params.join('&'); url += (url.includes('?') ? '&' : '?') + params.join('&');
} }
uni.navigateTo({ url });
uni.navigateTo({
url: url,
fail: (err) => {
console.error('跳转自定义客服页面失败:', err);
this.tryThirdPartyService(config, options);
}
});
return; return;
} }
this.tryThirdPartyService(config, options); this.tryThirdPartyService(config, options);
} }
/**
* 尝试使用第三方客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
tryThirdPartyService(config, options = {}) { tryThirdPartyService(config, options = {}) {
if (config.thirdPartyServiceUrl) { // 支持第三方微信小程序客服
// #ifdef H5 if (config.thirdPartyMiniAppId || config.mini_app_id) {
window.open(config.thirdPartyServiceUrl, '_blank');
// #endif
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
if (config.thirdPartyMiniAppId) { wx.navigateToMiniProgram({
wx.navigateToMiniProgram({ appId: config.thirdPartyMiniAppId || config.mini_app_id,
appId: config.thirdPartyMiniAppId, path: config.thirdPartyMiniAppPath || config.mini_app_path || ''
path: config.thirdPartyMiniAppPath || '', });
fail: (err) => {
console.error('跳转第三方小程序失败:', err);
this.fallbackToPhoneCall();
}
});
} else {
uni.setClipboardData({
data: config.thirdPartyServiceUrl,
success: () => {
uni.showModal({
title: '客服链接已复制',
content: '客服链接已复制到剪贴板,请在浏览器中粘贴访问',
showCancel: false
});
}
});
}
// #endif // #endif
return; return;
} }
// 支持第三方链接客服
if (config.thirdPartyServiceUrl || config.third_url) {
const serviceUrl = config.thirdPartyServiceUrl || config.third_url;
// #ifdef H5
window.open(serviceUrl, '_blank');
// #endif
// #ifdef MP-WEIXIN
uni.setClipboardData({ data: serviceUrl });
uni.showToast({ title: '客服链接已复制', icon: 'none' });
// #endif
return;
}
this.fallbackToPhoneCall(); this.fallbackToPhoneCall();
} }
/**
* 降级到电话客服
*/
fallbackToPhoneCall() {
uni.showModal({
title: '联系客服',
content: '在线客服暂时不可用,是否拨打电话联系客服?',
success: (res) => {
if (res.confirm) {
this.makePhoneCall();
}
}
});
}
/**
* 打开支付宝小程序客服
* @param {Object} config 客服配置
*/
openAliappService(config) { openAliappService(config) {
console.log('支付宝小程序客服', config); if (config.type === 'aikefu') {
switch (config.type) { this.openDifyService();
case 'aikefu': } else if (config.type === 'third') {
this.openAIKeFuService(); this.openThirdService(config);
break; } else {
case 'third': // 支付宝原生客服由 button open-type="contact" 触发,此处不处理
this.openThirdService(config); console.log('使用支付宝官方客服');
break;
default:
console.log('使用支付宝官方客服');
break;
} }
} }
/** // ================== 辅助方法 ==================
* 拨打电话
*/
makePhoneCall(mobileNumber) {
if (mobileNumber) {
return uni.makePhoneCall({
phoneNumber: mobileNumber
});
}
// 从缓存中获取电话信息 makePhoneCall() {
uni.getStorage({ this.vm.$api.sendRequest({
key: 'shopInfo', url: '/api/site/shopcontact',
success: (res) => { success: res => {
const shopInfo = res.data; if (res.code === 0 && res.data?.mobile) {
const mobile = shopInfo?.mobile ?? ''; uni.makePhoneCall({ phoneNumber: res.data.mobile });
if (mobile) {
uni.makePhoneCall({
phoneNumber: mobile
});
} else { } else {
uni.showToast({ uni.showToast({ title: '暂无客服电话', icon: 'none' });
title: '暂无客服电话',
icon: 'none'
});
} }
},
fail: () => {
uni.showToast({ title: '获取客服电话失败', icon: 'none' });
} }
}); });
} }
/**
* 显示无客服弹窗
*/
showNoServicePopup() { showNoServicePopup() {
const siteInfo = this.vm.$store.state.siteInfo || {}; const siteInfo = this.vm.$store.state.siteInfo || {};
const message = siteInfo?.site_tel const message = siteInfo?.site_tel
? `请联系客服,客服电话是${siteInfo.site_tel}` ? `请联系客服,客服电话是 ${siteInfo.site_tel}`
: '抱歉,商家暂无客服,请线下联系'; : '抱歉,商家暂无客服,请线下联系';
uni.showModal({ title: '联系客服', content: message, showCancel: false });
uni.showModal({
title: '联系客服',
content: message,
showCancel: false
});
} }
/**
* 显示配置错误弹窗
* @param {Array} errors 错误列表
*/
showConfigErrorPopup(errors) { showConfigErrorPopup(errors) {
const message = errors.join('\n');
uni.showModal({ uni.showModal({
title: '配置错误', title: '客服配置错误',
content: `客服配置有误:\n${message}`, content: `配置有误:\n${errors.join('\n')}`,
showCancel: false showCancel: false
}); });
} }
/**
* 降级处理:使用原有客服方式
*/
fallbackToOriginalService() { fallbackToOriginalService() {
uni.showModal({ uni.showModal({
title: '提示', title: '提示',
content: '无法直接添加企业微信客服,是否使用其他方式联系客服?', content: '无法直接添加企业微信,是否使用其他方式联系客服?',
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
this.openWxworkService(true); this.openWxworkService(true);
@@ -497,9 +423,19 @@ class CustomerService {
}); });
} }
fallbackToPhoneCall() {
uni.showModal({
title: '提示',
content: '在线客服不可用,是否拨打电话联系客服?',
success: (res) => {
if (res.confirm) this.makePhoneCall();
}
});
}
/** /**
* 获取客服按钮配置 * 获取按钮配置(用于 template 中 v-if / open-type 判断)
* @returns {Object} 按钮配置 * @returns {Object}
*/ */
getButtonConfig() { getButtonConfig() {
const config = this.getPlatformConfig(); const config = this.getPlatformConfig();
@@ -507,39 +443,24 @@ class CustomerService {
let openType = ''; let openType = '';
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
if (config.type === 'weapp') { if (config.type === 'weapp' && config.useOfficial !== false) {
openType = config.useOfficial !== false ? 'contact' : ''; openType = 'contact';
} }
// #endif // #endif
// #ifdef MP-ALIPAY // #ifdef MP-ALIPAY
if (config.type === 'aliapp') openType = 'contact'; if (config.type === 'aliapp') openType = 'contact';
// #endif // #endif
return { ...config, openType }; return { ...config, openType };
} }
/**
* 判断是否应该使用自定义客服处理
* @param {Object} config 客服配置
* @returns {boolean} 是否使用自定义客服
*/
shouldUseCustomService(config) {
// #ifdef MP-WEIXIN
if (config?.type === 'weapp') {
return config.useOfficial === false;
}
// #endif
return true;
}
} }
/** /**
* 创建客服服务实例 * 创建客服服务实例
* @param {Object} vueInstance Vue实例 * @param {Object} vueInstance Vue 实例(通常是 this
* @param {Object} externalConfig 外部最新配置 * @param {Object} externalConfig 可选:外部传入的最新配置(如从 DIY 数据中提取)
* @returns {CustomerService} 客服服务实例 * @returns {CustomerService}
*/ */
export function createCustomerService(vueInstance, externalConfig = {}) { export function createCustomerService(vueInstance, externalConfig = null) {
return new CustomerService(vueInstance, externalConfig); return new CustomerService(vueInstance, externalConfig);
} }