网站链接想转发给微信好友或者群聊,让自己的分享链接看上去比较正式,这时候就需要自定义了
我这以nuxt项目为例,其他类型的项目大同小异稍微改改即可,第一次写可能会碰到很多坑,所以在这分享给大家~
1、下载官方weixin-js-sdk
npm install weixin-js-sdk
2、在nuxt目录下的plugins新建wx-share.js文件
import Vue from 'vue'
import wx from 'weixin-js-sdk'
Vue.prototype.$wechat = wx
export default ({ app, $axios, store }) => {
// 这个url必须传当前页面的url,不然会一直报签名失效
Vue.prototype.wxShare = function (shareData, url) {
// 获取微信公众号签名数据
$axios.post('/api/wx/base/signature', { url }).then(({ data }) => {
const wxData = data.data
// 注意接口返回字段大小写正确
this.$wechat.config({
debug: false,
appId: wxData.appId,
timestamp: wxData.timestamp,
nonceStr: wxData.noncestr,
signature: wxData.signature,
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
})
this.$wechat.ready(() => {
// 自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
this.$wechat.updateAppMessageShareData({
title: shareData.title,
desc: shareData.desc,
link: shareData.link,
imgUrl: shareData.imgUrl,
success () {
},
cancel () {
}
})
// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0)
this.$wechat.updateTimelineShareData({
title: shareData.title,
desc: shareData.desc,
link: shareData.link,
imgUrl: shareData.imgUrl,
success () {
},
cancel () {
}
})
})
})
}
}
3、在nuxt.config.js注册插件
export default {
plugins: [
{ src: '@/plugins/wx-share.js', ssr: false }
]
}
4、在当前分享页面中使用
mounted () {
this.wxShare({
title: '网站标题~',
desc: '网站描述~',
link: window.location.href,
imgUrl: 'https://img/xxxxx/20230310183910.png'
}, window.location.href)
}
5、关于调试
请用微信开发者工具调试,才能看到js-weixin-sdk抛出的错误