You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
3.1 KiB

/*
* 微信JS-SDK工具
* 用于H5端的微信分享功能
*/
import { ROOTPATH, WECHAT_APPID } from '@/common/config.js'
let wx = null
// 动态加载微信JS-SDK
const loadWxSDK = () => {
return new Promise((resolve, reject) => {
// #ifdef H5
if (typeof window !== 'undefined' && !window.wx) {
const script = document.createElement('script')
script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js'
script.onload = () => {
wx = window.wx
resolve(wx)
}
script.onerror = () => {
reject(new Error('加载微信JS-SDK失败'))
}
document.head.appendChild(script)
} else if (window.wx) {
wx = window.wx
resolve(wx)
} else {
reject(new Error('不支持的环境'))
}
// #endif
// #ifndef H5
resolve(null)
// #endif
})
}
// 获取微信JS-SDK签名
const getWxSignature = () => {
return new Promise((resolve, reject) => {
// #ifdef H5
const url = window.location.href.split('#')[0]
uni.request({
url: `${ROOTPATH}/api/mobile/user/wechat-share`,
method: 'GET',
data: {
url: url,
activity_tag: 'walksz',
activity_list_id: 13
},
success: (res) => {
if (res.data && res.data.signature) {
resolve(res.data)
} else {
reject(new Error('获取签名失败'))
}
},
fail: (err) => {
reject(err)
}
})
// #endif
// #ifndef H5
resolve(null)
// #endif
})
}
// 初始化微信JS-SDK
const initWxSDK = (shareConfig = {}) => {
return new Promise((resolve, reject) => {
// #ifdef H5
loadWxSDK().then(() => {
getWxSignature().then((signatureData) => {
const { signature, timestamp, nonceStr } = signatureData
wx.config({
debug: false,
appId: WECHAT_APPID,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
})
wx.ready(() => {
// 分享到朋友
wx.updateAppMessageShareData({
title: shareConfig.title || '打卡苏州市党史教育基地',
desc: shareConfig.desc || '打卡苏州市党史教育基地',
link: shareConfig.link || window.location.href,
1 month ago
imgUrl: shareConfig.imgUrl || `${window.location.origin}/h5walksz/static/share.jpg`,
success: () => {
console.log('分享到朋友成功')
}
})
// 分享到朋友圈
wx.updateTimelineShareData({
title: shareConfig.title || '打卡苏州市党史教育基地',
link: shareConfig.link || window.location.href,
1 month ago
imgUrl: shareConfig.imgUrl || `${window.location.origin}/h5walksz/static/share.jpg`,
success: () => {
console.log('分享到朋友圈成功')
}
})
resolve(wx)
})
wx.error((res) => {
console.error('微信JS-SDK配置失败', res)
reject(res)
})
}).catch((err) => {
console.error('获取签名失败', err)
reject(err)
})
}).catch((err) => {
console.error('加载微信JS-SDK失败', err)
reject(err)
})
// #endif
// #ifndef H5
resolve(null)
// #endif
})
}
export {
loadWxSDK,
getWxSignature,
initWxSDK
}