chore:实现后台控制哪个客服,H5可以正常切换客服

This commit is contained in:
2025-12-19 17:07:57 +08:00
parent b34003e2c0
commit 95375d5476
2 changed files with 700 additions and 661 deletions

View File

@@ -1,485 +1,511 @@
/** /**
* 客服统一处理服务 * 客服统一处理服务
* 整合各种客服方式,提供统一的调用接口 * 整合各种客服方式,提供统一的调用接口
*/ */
export class CustomerService {
export class CustomerService { constructor(vueInstance, externalConfig = null) {
constructor(vueInstance) { this.vm = vueInstance;
this.vm = vueInstance; this.externalConfig = externalConfig; // 外部传入的最新配置(优先级最高)
} this.latestPlatformConfig = null;
}
/**
* 获取平台配置 /**
* @returns {Object} 平台对应的客服配置 * 强制刷新配置(支持传入外部配置
*/ * @param {Object} externalConfig 外部最新配置
getPlatformConfig() { */
const servicerConfig = this.vm.$store.state.servicerConfig; refreshConfig(externalConfig = null) {
console.log(`客服配置:`, servicerConfig) this.externalConfig = externalConfig || this.externalConfig;
if (!servicerConfig) return null; this.latestPlatformConfig = null;
return this.getPlatformConfig();
// #ifdef H5 }
return servicerConfig.h5;
// #endif /**
* 获取平台配置
// #ifdef MP-WEIXIN * @returns {Object} 平台对应的客服配置
return servicerConfig.weapp; */
// #endif getPlatformConfig() {
if (this.latestPlatformConfig) {
// #ifdef MP-ALIPAY return this.latestPlatformConfig;
return servicerConfig.aliapp; }
// #endif
// 优先级:外部传入的最新配置 > vuex配置 > 空对象
return null; const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {};
} console.log(`【实时客服配置】`, servicerConfig);
/** let platformConfig = null;
* 获取企业微信配置 // #ifdef H5
* @returns {Object} 企业微信配置 platformConfig = servicerConfig.h5 ? (typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null) : null;
*/ // #endif
getWxworkConfig() {
return this.vm.$store.state.wxworkConfig; // #ifdef MP-WEIXIN
} platformConfig = servicerConfig.weapp ? (typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null) : null;
// #endif
/**
* 检查客服配置是否可用 // #ifdef MP-ALIPAY
* @returns {boolean} 是否有可用配置 platformConfig = servicerConfig.aliapp ? (typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null) : null;
*/ // #endif
isConfigAvailable() {
const config = this.getPlatformConfig(); // #ifdef PC
return config && typeof config === 'object' && config.type; platformConfig = servicerConfig.pc ? (typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null) : null;
} // #endif
/** // 处理空数组情况你的配置中pc/aliapp是空数组转为null
* 验证客服配置完整性 if (Array.isArray(platformConfig)) {
* @returns {Object} 验证结果 platformConfig = null;
*/ }
validateConfig() {
const config = this.getPlatformConfig(); this.latestPlatformConfig = platformConfig;
const wxworkConfig = this.getWxworkConfig(); return platformConfig;
}
const result = {
isValid: true, /**
errors: [], * 获取企业微信配置
warnings: [] * @returns {Object} 企业微信配置
}; */
getWxworkConfig() {
if (!config) { return this.vm.$store.state.wxworkConfig || {};
result.isValid = false; }
result.errors.push('客服配置不存在');
return result; /**
} * 检查客服配置是否可用
* @returns {boolean} 是否有可用配置
if (!config.type) { */
result.isValid = false; isConfigAvailable() {
result.errors.push('客服类型未配置'); const config = this.getPlatformConfig();
} return config && typeof config === 'object' && config.type;
}
// 验证企业微信配置
if (config.type === 'wxwork') { /**
if (!wxworkConfig) { * 验证客服配置完整性
result.isValid = false; * @returns {Object} 验证结果
result.errors.push('企业微信配置不存在'); */
} else { validateConfig() {
if (!wxworkConfig.enable) { const config = this.getPlatformConfig();
result.warnings.push('企业微信功能未启用'); const wxworkConfig = this.getWxworkConfig();
}
if (!wxworkConfig.contact_url) { const result = {
result.warnings.push('企业微信活码链接未配置,将使用原有客服方式'); isValid: true,
} errors: [],
} warnings: []
} };
return result; if (!config) {
} result.isValid = false;
result.errors.push('客服配置不存在');
/** return result;
* 获取客服类型 }
* @returns {string} 客服类型
*/ if (config.type === 'aikefu') {
getServiceType() { return result;
const config = this.getPlatformConfig(); }
return config?.type || 'none';
} if (!config.type) {
result.isValid = false;
/** result.errors.push('客服类型未配置');
* 处理客服点击事件 }
* @param {Object} options 选项参数
* @param {Object} options.niushop 牛商客服参数 if (config.type === 'wxwork') {
* @param {string} options.sendMessageTitle 消息标题 if (!wxworkConfig) {
* @param {string} options.sendMessagePath 消息路径 result.isValid = false;
* @param {string} options.sendMessageImg 消息图片 result.errors.push('企业微信配置不存在');
*/ } else {
handleCustomerClick(options = {}) { if (!wxworkConfig.enable) {
// 验证配置 result.warnings.push('企业微信功能未启用');
const validation = this.validateConfig(); }
if (!validation.isValid) { if (!wxworkConfig.contact_url) {
console.error('客服配置验证失败:', validation.errors); result.warnings.push('企业微信活码链接未配置,将使用原有客服方式');
this.showConfigErrorPopup(validation.errors); }
return; }
} }
// 显示警告(如果有) return result;
if (validation.warnings.length > 0) { }
console.warn('客服配置警告:', validation.warnings);
} /**
* 跳转到Dify客服页面
const config = this.getPlatformConfig(); */
const { openDifyService() {
niushop = {}, try {
sendMessageTitle = '', if (this.vm.setAiUnreadCount) {
sendMessagePath = '', this.vm.setAiUnreadCount(0);
sendMessageImg = '' }
} = options; // 强制跳转,忽略框架层的封装
uni.redirectTo({
// 检查是否为无客服类型 url: '/pages_tool/ai-chat/index',
if (config.type === 'none') { fail: (err) => {
this.showNoServicePopup(); // 兜底使用window.location跳转H5
return; // #ifdef H5
} window.location.href = '/pages_tool/ai-chat/index';
// #endif
// 根据类型处理客服 console.error('跳转Dify客服失败:', err);
switch (config.type) { uni.showToast({
case 'wxwork': title: '跳转客服失败',
this.openWxworkService(false, config, options); icon: 'none'
break; });
case 'third': }
this.openThirdService(config); });
break; } catch (e) {
case 'niushop': console.error('跳转Dify客服异常:', e);
this.openNiushopService(niushop); uni.showToast({
break; title: '跳转客服失败',
case 'weapp': icon: 'none'
this.openWeappService(config, options); });
break; }
case 'aliapp': }
this.openAliappService(config);
break; /**
default: * 处理客服点击事件
this.makePhoneCall(); * @param {Object} options 选项参数
} */
} handleCustomerClick(options = {}) {
const validation = this.validateConfig();
/** if (!validation.isValid) {
* 打开企业微信客服 console.error('客服配置验证失败:', validation.errors);
* @param {boolean} useOriginalService 是否使用原有客服方式 this.showConfigErrorPopup(validation.errors);
* @param {Object} servicerConfig 客服配置 return;
*/ }
openWxworkService(useOriginalService = false, servicerConfig = null, options = {}) {
const config = servicerConfig || this.getPlatformConfig(); if (validation.warnings.length > 0) {
const wxworkConfig = this.getWxworkConfig(); console.warn('客服配置警告:', validation.warnings);
}
const {
sendMessageTitle = '', const config = this.getPlatformConfig();
sendMessagePath = '', const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
sendMessageImg = ''
} = options; if (config.type === 'none') {
this.showNoServicePopup();
// #ifdef MP-WEIXIN return;
if (wxworkConfig?.enable && wxworkConfig?.contact_url && !useOriginalService) { }
// 使用活码链接跳转到企业微信
wx.navigateToMiniProgram({ // 核心分支根据最新的type处理
appId: 'wxeb490c6f9b154ef9', // 企业微信官方小程序AppID switch (config.type) {
path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`, case 'aikefu':
success: () => { this.openDifyService();
console.log('跳转企业微信成功'); break;
}, case 'wxwork':
fail: (err) => { this.openWxworkService(false, config, options);
console.error('跳转企业微信失败:', err); break;
this.fallbackToOriginalService(); case 'third':
} this.openThirdService(config);
}); break;
} else { case 'niushop':
// 使用原有的客服会话方式 this.openNiushopService(niushop);
wx.openCustomerServiceChat({ break;
extInfo: { url: config.wxwork_url }, case 'weapp':
corpId: config.corpid, this.openWeappService(config, options);
showMessageCard: true, break;
sendMessageTitle, case 'aliapp':
sendMessagePath, this.openAliappService(config);
sendMessageImg break;
}); default:
} this.makePhoneCall();
// #endif }
}
// #ifdef H5
if (wxworkConfig?.enable && wxworkConfig?.contact_url) { /**
window.location.href = wxworkConfig.contact_url; * 打开企业微信客服
} else { * @param {boolean} useOriginalService 是否使用原有客服方式
location.href = config.wxwork_url; * @param {Object} servicerConfig 客服配置
} * @param {Object} options 选项参数
// #endif */
} openWxworkService(useOriginalService = false, servicerConfig = null, options = {}) {
const config = servicerConfig || this.getPlatformConfig();
/** const wxworkConfig = this.getWxworkConfig();
* 打开第三方客服 const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
* @param {Object} config 客服配置
*/ // #ifdef MP-WEIXIN
openThirdService(config) { if (wxworkConfig?.enable && wxworkConfig?.contact_url && !useOriginalService) {
if (config.third_url) { wx.navigateToMiniProgram({
location.href = config.third_url; appId: 'wxeb490c6f9b154ef9',
} path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`,
} success: () => console.log('跳转企业微信成功'),
fail: (err) => {
/** console.error('跳转企业微信失败:', err);
* 打开牛商客服 this.fallbackToOriginalService();
* @param {Object} niushop 牛商参数 }
*/ });
openNiushopService(niushop) { } else {
if (Object.keys(niushop).length > 0) { wx.openCustomerServiceChat({
this.vm.$util.redirectTo('/pages_tool/chat/room', niushop); extInfo: { url: config.wxwork_url },
} else { corpId: config.corpid,
this.makePhoneCall(); showMessageCard: true,
} sendMessageTitle,
} sendMessagePath,
sendMessageImg
/** });
* 打开微信小程序客服 }
* @param {Object} config 客服配置 // #endif
* @param {Object} options 选项参数
*/ // #ifdef H5
openWeappService(config, options = {}) { if (wxworkConfig?.enable && wxworkConfig?.contact_url) {
// 如果是官方客服,由 open-type="contact" 自动处理 window.location.href = wxworkConfig.contact_url;
if (!this.shouldUseCustomService(config)) { } else if (config.wxwork_url) {
console.log('使用官方微信小程序客服'); location.href = config.wxwork_url;
return; } else {
} this.fallbackToPhoneCall();
}
// 自定义客服处理 // #endif
console.log('使用自定义微信小程序客服'); }
// 这里可以实现自定义的客服逻辑 /**
// 例如:跳转到自定义客服页面、显示客服弹窗等 * 打开第三方客服
const { * @param {Object} config 客服配置
sendMessageTitle = '', */
sendMessagePath = '', openThirdService(config) {
sendMessageImg = '' if (config.third_url) {
} = options; window.location.href = config.third_url;
} else {
// 实现自定义客服逻辑 this.fallbackToPhoneCall();
this.handleCustomWeappService(config, options); }
} }
/** /**
* 处理自定义微信小程序客服 * 打开牛商客服
* @param {Object} config 客服配置 * @param {Object} niushop 牛商参数
* @param {Object} options 选项参数 */
*/ openNiushopService(niushop) {
handleCustomWeappService(config, options = {}) { if (Object.keys(niushop).length > 0) {
const { this.vm.$util.redirectTo('/pages_tool/chat/room', niushop);
sendMessageTitle = '', } else {
sendMessagePath = '', this.makePhoneCall();
sendMessageImg = '' }
} = options; }
// 优先级1: 如果有自定义客服页面URL跳转到自定义页面 /**
if (config.customServiceUrl) { * 打开微信小程序客服
// 构建带参数的URL * @param {Object} config 客服配置
let url = config.customServiceUrl; * @param {Object} options 选项参数
const params = []; */
openWeappService(config, options = {}) {
if (sendMessageTitle) params.push(`title=${encodeURIComponent(sendMessageTitle)}`); if (!this.shouldUseCustomService(config)) {
if (sendMessagePath) params.push(`path=${encodeURIComponent(sendMessagePath)}`); console.log('使用官方微信小程序客服');
if (sendMessageImg) params.push(`img=${encodeURIComponent(sendMessageImg)}`); return;
}
if (params.length > 0) {
url += (url.includes('?') ? '&' : '?') + params.join('&'); console.log('使用自定义微信小程序客服');
} this.handleCustomWeappService(config, options);
}
uni.navigateTo({
url: url, /**
fail: (err) => { * 处理自定义微信小程序客服
console.error('跳转自定义客服页面失败:', err); * @param {Object} config 客服配置
this.tryThirdPartyService(config, options); * @param {Object} options 选项参数
} */
}); handleCustomWeappService(config, options = {}) {
return; const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
}
if (config.customServiceUrl) {
// 优先级2: 尝试第三方客服 let url = config.customServiceUrl;
this.tryThirdPartyService(config, options); const params = [];
} if (sendMessageTitle) params.push(`title=${encodeURIComponent(sendMessageTitle)}`);
if (sendMessagePath) params.push(`path=${encodeURIComponent(sendMessagePath)}`);
/** if (sendMessageImg) params.push(`img=${encodeURIComponent(sendMessageImg)}`);
* 尝试使用第三方客服
* @param {Object} config 客服配置 if (params.length > 0) {
* @param {Object} options 选项参数 url += (url.includes('?') ? '&' : '?') + params.join('&');
*/ }
tryThirdPartyService(config, options = {}) {
// 如果配置了第三方客服URL uni.navigateTo({
if (config.thirdPartyServiceUrl) { url: url,
// #ifdef H5 fail: (err) => {
window.open(config.thirdPartyServiceUrl, '_blank'); console.error('跳转自定义客服页面失败:', err);
// #endif this.tryThirdPartyService(config, options);
}
// #ifdef MP-WEIXIN });
// 微信小程序可以使用web-view或者跳转到第三方小程序 return;
if (config.thirdPartyMiniAppId) { }
wx.navigateToMiniProgram({
appId: config.thirdPartyMiniAppId, this.tryThirdPartyService(config, options);
path: config.thirdPartyMiniAppPath || '', }
fail: (err) => {
console.error('跳转第三方小程序失败:', err); /**
this.fallbackToPhoneCall(); * 尝试使用第三方客服
} * @param {Object} config 客服配置
}); * @param {Object} options 选项参数
} else { */
// 设置到剪贴板,让用户手动访问 tryThirdPartyService(config, options = {}) {
uni.setClipboardData({ if (config.thirdPartyServiceUrl) {
data: config.thirdPartyServiceUrl, // #ifdef H5
success: () => { window.open(config.thirdPartyServiceUrl, '_blank');
uni.showModal({ // #endif
title: '客服链接已复制',
content: '客服链接已复制到剪贴板,请在浏览器中粘贴访问', // #ifdef MP-WEIXIN
showCancel: false if (config.thirdPartyMiniAppId) {
}); wx.navigateToMiniProgram({
} appId: config.thirdPartyMiniAppId,
}); path: config.thirdPartyMiniAppPath || '',
} fail: (err) => {
// #endif console.error('跳转第三方小程序失败:', err);
return; this.fallbackToPhoneCall();
} }
});
// 降级到电话客服 } else {
this.fallbackToPhoneCall(); uni.setClipboardData({
} data: config.thirdPartyServiceUrl,
success: () => {
/** uni.showModal({
* 降级到电话客服 title: '客服链接已复制',
*/ content: '客服链接已复制到剪贴板,请在浏览器中粘贴访问',
fallbackToPhoneCall() { showCancel: false
uni.showModal({ });
title: '联系客服', }
content: '在线客服暂时不可用,是否拨打电话联系客服?', });
success: (res) => { }
if (res.confirm) { // #endif
this.makePhoneCall(); return;
} }
}
}); this.fallbackToPhoneCall();
} }
/** /**
* 打开支付宝小程序客服 * 降级到电话客服
* @param {Object} config 客服配置 */
*/ fallbackToPhoneCall() {
openAliappService(config) { uni.showModal({
// 支付宝小程序客服会由 contact-button 组件自动处理 title: '联系客服',
console.log('支付宝小程序客服'); content: '在线客服暂时不可用,是否拨打电话联系客服?',
} success: (res) => {
if (res.confirm) {
/** this.makePhoneCall();
* 拨打电话 }
*/ }
makePhoneCall() { });
this.vm.$api.sendRequest({ }
url: '/api/site/shopcontact',
success: res => { /**
if (res.code === 0 && res.data?.mobile) { * 打开支付宝小程序客服
uni.makePhoneCall({ * @param {Object} config 客服配置
phoneNumber: res.data.mobile */
}); openAliappService(config) {
} console.log('支付宝小程序客服', config);
} switch (config.type) {
}); case 'aikefu':
} this.openDifyService();
break;
/** case 'third':
* 显示无客服弹窗 this.openThirdService(config);
*/ break;
showNoServicePopup() { default:
const siteInfo = this.vm.$store.state.siteInfo; console.log('使用支付宝官方客服');
const message = siteInfo?.site_tel break;
? `请联系客服,客服电话是${siteInfo.site_tel}` }
: '抱歉,商家暂无客服,请线下联系'; }
uni.showModal({ /**
title: '联系客服', * 拨打电话
content: message, */
showCancel: false makePhoneCall() {
}); this.vm.$api.sendRequest({
} url: '/api/site/shopcontact',
success: res => {
/** if (res.code === 0 && res.data?.mobile) {
* 显示配置错误弹窗 uni.makePhoneCall({
* @param {Array} errors 错误列表 phoneNumber: res.data.mobile
*/ });
showConfigErrorPopup(errors) { } else {
const message = errors.join('\n'); uni.showToast({
uni.showModal({ title: '暂无客服电话',
title: '配置错误', icon: 'none'
content: `客服配置有误:\n${message}`, });
showCancel: false }
}); },
} fail: () => {
uni.showToast({
/** title: '获取客服电话失败',
* 降级处理:使用原有客服方式 icon: 'none'
*/ });
fallbackToOriginalService() { }
uni.showModal({ });
title: '提示', }
content: '无法直接添加企业微信客服,是否使用其他方式联系客服?',
success: (res) => { /**
if (res.confirm) { * 显示无客服弹窗
console.log('降级处理:使用原有客服方式'); */
this.openWxworkService(true); showNoServicePopup() {
} const siteInfo = this.vm.$store.state.siteInfo || {};
} const message = siteInfo?.site_tel
}); ? `请联系客服,客服电话是${siteInfo.site_tel}`
} : '抱歉,商家暂无客服,请线下联系';
/** uni.showModal({
* 获取客服按钮配置 title: '联系客服',
* @returns {Object} 按钮配置 content: message,
*/ showCancel: false
getButtonConfig() { });
const config = this.getPlatformConfig(); }
if (!config) return { openType: '' };
/**
let openType = ''; * 显示配置错误弹窗
* @param {Array} errors 错误列表
// #ifdef MP-WEIXIN */
if (config.type === 'weapp') { showConfigErrorPopup(errors) {
// 检查是否使用官方客服 const message = errors.join('\n');
if (config.useOfficial !== false) { // 默认为true使用官方客服 uni.showModal({
openType = 'contact'; title: '配置错误',
} content: `客服配置有误:\n${message}`,
} showCancel: false
// #endif });
}
// #ifdef MP-ALIPAY
if (config.type === 'aliapp') openType = 'contact'; /**
// #endif * 降级处理:使用原有客服方式
*/
return { fallbackToOriginalService() {
...config, uni.showModal({
openType title: '提示',
}; content: '无法直接添加企业微信客服,是否使用其他方式联系客服?',
} success: (res) => {
if (res.confirm) {
/** this.openWxworkService(true);
* 判断是否应该使用自定义客服处理 }
* @param {Object} config 客服配置 }
* @returns {boolean} 是否使用自定义客服 });
*/ }
shouldUseCustomService(config) {
// #ifdef MP-WEIXIN /**
// 如果是微信小程序且type为weapp检查useOfficial配置 * 获取客服按钮配置
if (config?.type === 'weapp') { * @returns {Object} 按钮配置
return config.useOfficial === false; // 明确设置为false才使用自定义 */
} getButtonConfig() {
// #endif const config = this.getPlatformConfig();
if (!config) return { openType: '' };
// 其他平台或类型都使用自定义处理
return true; let openType = '';
} // #ifdef MP-WEIXIN
} if (config.type === 'weapp') {
openType = config.useOfficial !== false ? 'contact' : '';
/** }
* 创建客服服务实例 // #endif
* @param {Object} vueInstance Vue实例
* @returns {CustomerService} 客服服务实例 // #ifdef MP-ALIPAY
*/ if (config.type === 'aliapp') openType = 'contact';
export function createCustomerService(vueInstance) { // #endif
return new CustomerService(vueInstance);
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} externalConfig 外部最新配置
* @returns {CustomerService} 客服服务实例
*/
export function createCustomerService(vueInstance, externalConfig = null) {
return new CustomerService(vueInstance, externalConfig);
} }

View File

@@ -1,60 +1,49 @@
<template> <template>
<!-- 悬浮按钮 --> <view v-if="pageCount == 1 || need" class="fixed-box" :style="{ height: fixBtnShow ? (isH5 ? '180rpx' : '330rpx') : '120rpx' }">
<view v-if="pageCount == 1 || need" class="fixed-box" :style="{ height: fixBtnShow ? '330rpx' : '120rpx' }">
<!-- 微信小程序区分官方客服和自定义客服 -->
<!-- #ifdef MP-WEIXIN --> <!-- #ifdef MP-WEIXIN -->
<!-- 官方客服使用open-type="contact" --> <!-- 微信小程序根据配置自动选择官方客服/自定义客服 -->
<button <button
class="btn-item" class="btn-item"
v-if="fixBtnShow && useOfficialService" v-if="fixBtnShow"
hoverClass="none" hoverClass="none"
open-type="contact" :open-type="weappOfficialService ? 'contact' : ''"
sessionFrom="weapp" @click="weappOfficialService ? '' : handleWeappCustomerService"
showMessageCard="true"
:style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }"
>
<text class="icox icox-kefu" v-if="!kefuimg"></text>
</button>
<!-- 自定义客服点击触发contactServicer -->
<button
class="btn-item"
v-if="fixBtnShow && !useOfficialService"
hoverClass="none"
@click="contactServicer"
:style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }" :style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }"
> >
<text class="icox icox-kefu" v-if="!kefuimg"></text> <text class="icox icox-kefu" v-if="!kefuimg"></text>
</button> </button>
<!-- #endif --> <!-- #endif -->
<!-- H5自定义客服按钮 -->
<!-- #ifdef H5 --> <!-- #ifdef H5 -->
<!-- H5逻辑保持不变 -->
<button <button
class="btn-item" class="btn-item"
v-if="fixBtnShow" v-if="fixBtnShow"
hoverClass="none" hoverClass="none"
@click="contactServicer" @click="handleCustomerService"
:style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }" :style="{ backgroundImage: 'url(' + (kefuimg ? kefuimg : '') + ')', backgroundSize: '100% 100%' }"
> >
<text class="icox icox-kefu" v-if="!kefuimg"></text> <text class="icox icox-kefu" v-if="!kefuimg"></text>
<view v-if="unreadCount > 0 && isDifyService" class="unread-badge">
<text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
</view>
</button> </button>
<!-- #endif --> <!-- #endif -->
<!-- AI智能助手 --> <!-- #ifndef H5 -->
<view <view
class="btn-item" class="btn-item"
v-if="fixBtnShow && enableAIKefuButton" v-if="fixBtnShow && isDifyService"
@click="openAIChat" @click="handleCustomerService"
:style="{ backgroundImage: 'url(' + (aiAgentimg ? aiAgentimg : '') + ')', backgroundSize: '100% 100%' }" :style="{ backgroundImage: 'url(' + (aiAgentimg ? aiAgentimg : '') + ')', backgroundSize: '100% 100%' }"
> >
<text class="ai-icon" v-if="!aiAgentimg">🤖</text> <text class="ai-icon" v-if="!aiAgentimg">🤖</text>
<!-- 未读消息小红点 -->
<view v-if="unreadCount > 0" class="unread-badge"> <view v-if="unreadCount > 0" class="unread-badge">
<text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text> <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
</view> </view>
</view> </view>
<!-- #endif -->
<!-- 电话 -->
<view <view
class="btn-item" class="btn-item"
v-if="fixBtnShow" v-if="fixBtnShow"
@@ -86,31 +75,36 @@ export default {
kefuimg: '', kefuimg: '',
phoneimg: '', phoneimg: '',
customerService: null, customerService: null,
buttonConfig: null buttonConfig: null,
isH5: false,
platformConfig: null,
latestConfig: null,
weappOfficialService: false // 微信小程序是否使用官方客服
}; };
}, },
created() { created() {
// 1. 判断平台类型
// #ifdef H5
this.isH5 = true;
// #endif
// #ifdef MP-WEIXIN
this.isH5 = false;
// #endif
// 2. 初始化资源
this.kefuimg = this.$util.getDefaultImage().kefu; this.kefuimg = this.$util.getDefaultImage().kefu;
this.phoneimg = this.$util.getDefaultImage().phone; this.phoneimg = this.$util.getDefaultImage().phone;
this.pageCount = getCurrentPages().length; this.pageCount = getCurrentPages().length;
this.customerService = createCustomerService(this); // 3. 获取店铺电话
this.buttonConfig = this.customerService.getButtonConfig(); this.getShopTel();
console.log(`buttonConfig: `, this.buttonConfig);
const that = this; // 4. 首次加载获取最新配置
uni.getStorage({ this.getLatestConfig().then(config => {
key: 'shopInfo', this.latestConfig = config;
success(e) { this.initCustomerService(config);
// 校验手机号是否有效 // 微信小程序:判断是否使用官方客服
if (e.data && e.data.mobile && /^1[3-9]\d{9}$/.test(e.data.mobile)) { this.initWeappServiceType();
that.tel = e.data.mobile;
}
},
fail() {
console.warn('未获取到店铺信息');
}
}); });
}, },
computed: { computed: {
@@ -118,26 +112,15 @@ export default {
'globalAIKefuConfig', 'globalAIKefuConfig',
'aiUnreadCount' 'aiUnreadCount'
]), ]),
enableAIKefuButton() { isDifyService() {
return this.buttonConfig?.type === 'aikefu' && this.enableAIChat; const serviceType = this.platformConfig?.type || '';
return serviceType === 'aikefu';
}, },
aiAgentimg() { aiAgentimg() {
return this.globalAIKefuConfig?.icon || this.$util.getDefaultImage().aiAgent || ''; return this.globalAIKefuConfig?.icon || this.$util.getDefaultImage().aiAgent || '';
}, },
unreadCount() { unreadCount() {
return this.aiUnreadCount; return this.aiUnreadCount;
},
enableAIChat() {
return this.globalAIKefuConfig?.enable || true;
},
useOfficialService() {
if (!this.buttonConfig) return true;
// #ifdef MP-WEIXIN
if (this.buttonConfig.type === 'weapp') {
return this.buttonConfig.useOfficial !== false;
}
// #endif
return false;
} }
}, },
methods: { methods: {
@@ -145,154 +128,184 @@ export default {
'setAiUnreadCount' 'setAiUnreadCount'
]), ]),
/** /**
* 拨打电话逻辑:增加手机号校验和异常处理 * 获取最新配置H5禁用缓存小程序保留默认
*/ */
call() { async getLatestConfig() {
// 1. 校验手机号是否存在且有效 return new Promise((resolve) => {
if (!this.tel || !/^1[3-9]\d{9}$/.test(this.tel)) { // H5强制请求最新配置小程序优先用vuex缓存
uni.showToast({ if (this.isH5) {
title: '暂无有效联系电话', this.$api.sendRequest({
icon: 'none', url: '/api/site/getServicerConfig',
duration: 2000 header: {
}); 'Cache-Control': 'no-cache, no-store, must-revalidate',
return; 'Pragma': 'no-cache',
} 'Expires': '0'
},
// 2. 调用系统拨号API data: { t: new Date().getTime() },
uni.makePhoneCall({ success: (res) => {
phoneNumber: this.tel, const config = res.code === 0 ? res.data : this.$store.state.servicerConfig || {};
fail(err) { this.$store.commit('UPDATE_SERVICER_CONFIG', config);
console.log('拨号操作失败:', err); resolve(config);
// 非用户取消的情况,给出提示 },
if (err.errMsg !== 'makePhoneCall:fail cancel') { fail: () => resolve(this.$store.state.servicerConfig || {})
uni.showToast({ });
title: '拨号失败,请稍后重试', } else {
icon: 'none', // 小程序直接用vuex缓存后台修改后需重启开发者工具
duration: 2000 resolve(this.$store.state.servicerConfig || {});
}); }
});
},
/**
* 初始化客服服务
*/
initCustomerService(config = null) {
this.customerService = createCustomerService(this, config || this.latestConfig);
this.platformConfig = this.customerService.refreshConfig(config || this.latestConfig);
this.buttonConfig = this.customerService.getButtonConfig();
},
/**
* 微信小程序:初始化服务类型(官方/自定义)
*/
initWeappServiceType() {
// #ifdef MP-WEIXIN
// 从buttonConfig中获取官方客服标识
this.weappOfficialService = this.buttonConfig?.openType === 'contact';
// #endif
},
/**
* 获取店铺电话
*/
getShopTel() {
uni.getStorage({
key: 'shopInfo',
success: (e) => {
if (e.data && e.data.mobile && /^1[3-9]\d{9}$/.test(e.data.mobile)) {
this.tel = e.data.mobile;
} }
} }
}); });
}, },
openAIChat() { /**
if (this.enableAIChat) { * 拨打电话
this.setAiUnreadCount(0); */
call() {
if (!this.tel || !/^1[3-9]\d{9}$/.test(this.tel)) {
uni.showToast({ title: '暂无有效联系电话', icon: 'none' });
return;
} }
this.$util.redirectTo('/pages_tool/ai-chat/index'); uni.makePhoneCall({
phoneNumber: this.tel,
fail: (err) => {
if (err.errMsg !== 'makePhoneCall:fail cancel') {
uni.showToast({ title: '拨号失败,请稍后重试', icon: 'none' });
}
}
});
}, },
/** /**
* 处理客服点击:调用客服服务的统一处理方法 * H5客服点击逻辑(保持不变)
*/ */
contactServicer() { async handleCustomerService() {
// 移除错误的js路径跳转直接调用客服服务的处理方法 if (this.isH5) {
this.customerService.handleCustomerClick({ uni.showLoading({ title: '加载中...', mask: true });
// 可传递自定义参数,例如牛商客服参数、消息卡片参数 try {
// niushop: { /* 牛商客服参数 */ }, const newConfig = await this.getLatestConfig();
// sendMessageTitle: '客服消息标题', this.latestConfig = newConfig;
// sendMessagePath: '/pages/index/index', this.initCustomerService(newConfig);
// sendMessageImg: 'https://example.com/img.png' this.customerService.handleCustomerClick();
}); } catch (e) {
uni.showToast({ title: '操作失败', icon: 'none' });
} finally {
uni.hideLoading();
}
} else {
// 小程序:直接调用客服逻辑
this.customerService.handleCustomerClick();
}
},
/**
* 微信小程序自定义客服点击逻辑
*/
handleWeappCustomerService() {
// #ifdef MP-WEIXIN
this.customerService.handleCustomerClick();
// #endif
} }
} }
}; };
</script> </script>
<style lang="scss"> <style scoped>
.container-box {
width: 100%;
.item-wrap {
border-radius: 10rpx;
.image-box {
border-radius: 10rpx;
}
image {
width: 100%;
height: auto;
border-radius: 10rpx;
will-change: transform;
}
}
}
//悬浮按钮
.fixed-box { .fixed-box {
position: fixed; position: fixed;
right: 0rpx; right: 0;
bottom: 200rpx; bottom: 200rpx;
z-index: 10; z-index: 10;
border-radius: 120rpx; border-radius: 120rpx;
padding: 20rpx 0; padding: 20rpx 0;
display: flex; display: flex;
justify-content: center;
flex-direction: column; flex-direction: column;
justify-content: center;
align-items: center;
width: 100rpx; width: 100rpx;
box-sizing: border-box; box-sizing: border-box;
transition: 0.3s; }
overflow: hidden;
.btn-item { /* 核心修改:确保按钮背景是正圆 */
display: flex; .btn-item {
justify-content: center; display: flex;
align-items: center; justify-content: center;
text-align: center; align-items: center;
flex-direction: column; width: 80rpx;
line-height: 1; height: 80rpx;
margin: 14rpx 0; margin: 14rpx 0;
transition: 0.1s; /* 强制正圆使用远大于宽高的固定值比50%更稳定 */
background: #fff; border-radius: 100rpx;
border-radius: 50rpx; /* 确保背景色是白色(即使图片加载失败也能看到正圆) */
width: 80rpx; background-color: #ffffff;
height: 80rpx; /* 防止边框/内边距影响宽高比 */
padding: 0; box-sizing: border-box;
position: relative; /* 移除默认边框button标签可能有默认边框 */
border: none;
/* 清除默认内边距 */
padding: 0;
position: relative;
transition: all 0.1s ease;
/* 防止背景图片拉伸导致视觉上的非正圆 */
background-position: center;
background-repeat: no-repeat;
}
text { /* 清除button标签的默认点击样式微信小程序/浏览器) */
font-size: 36rpx; .btn-item::after {
font-weight: bold; border: none !important;
} }
view { .unread-badge {
font-size: 26rpx; position: absolute;
font-weight: bold; top: -5rpx;
} right: -5rpx;
background: #ff4544;
color: #fff;
border-radius: 20rpx;
min-width: 30rpx;
height: 30rpx;
line-height: 30rpx;
text-align: center;
font-size: 10rpx;
padding: 0 8rpx;
box-shadow: 0 2rpx 10rpx rgba(255, 73, 72, 0.3);
z-index: 1;
}
// 未读消息小红点 /* 微信小程序字体适配 */
.unread-badge { /* #ifdef MP-WEIXIN */
position: absolute; .unread-badge {
top: -5rpx; font-size: 20rpx;
right: -5rpx; }
background-color: #ff4544; /* #endif */
color: white;
border-radius: 20rpx;
min-width: 30rpx;
height: 30rpx;
font-size: 10rpx;
line-height: 30rpx;
text-align: center;
padding: 0 8rpx;
z-index: 1;
box-shadow: 0 2rpx 10rpx rgba(255, 69, 68, 0.3);
.badge-text { .ai-icon {
font-size: 8rpx; font-size: 40rpx;
// #ifdef MP-WEIXIN
font-size: 20rpx;
// #endif
}
}
// AI图标样式优化
.ai-icon {
font-size: 40rpx;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
}
} }
</style> </style>