Web项目经常会用到微信,所以总结一下。
1. 引用微信的'weixin-js-sdk
import wx from 'weixin-js-sdk';
2. 获取签名
后台会给一个接口用来获取接口,比如/api/js/config?url=
+location.origin + location.pathname
,会得到如下一个返回结果
{
"code": 0,
"message": "ok",
"data": {
"debug": false,
"beta": false,
"jsApiList": [
"onMenuShareTimeline",
"onMenuShareAppMessage",
"onMenuShareQQ",
"onMenuShareWeibo",
"onMenuShareQZone",
"openLocation",
"getLocation",
"chooseImage",
"previewImage",
"uploadImage",
"downloadImage"
],
"appId": "wxb***fbab32829***",
"nonceStr": "E4lQzW2tgC",
"timestamp": 1532403602,
"url": "https://ufutx.test/wx/lecturer/1/preview",
"signature": "6b70358fa40a2940bc780b4f602714aabe57383e"
}
}
3.配置微信分享
let jsConfig = response.data.data
wx.config({
debug: false,
appId: jsConfig.appId,
timestamp: jsConfig.timestamp,
nonceStr: jsConfig.nonceStr,
signature: jsConfig.signature,
jsApiList: jsConfig.jsApiList
})
wx.showOptionMenu()
wx.ready(function() {
wx.onMenuShareTimeline({
title: self.shareTitle, // 分享标题
link: self.shareUrl, // 分享链接
desc: self.shareDesc, // 分享描述
imgUrl: self.shareImage, // 分享图标
success: function() {
console.log('分享朋友圈成功啦!')
},
cancel: function() {
console.log('分享朋友圈失败')
}
})
wx.onMenuShareQQ({
title: self.shareTitle, // 分享标题
link: self.shareUrl, // 分享链接
desc: self.shareDesc, // 分享描述
imgUrl: self.shareImage, // 分享图标
success: function() {
console.log('分享给朋友成功啦')
},
cancel: function() {
console.log('分享给朋友失败')
}
})
wx.onMenuShareAppMessage({
title: self.shareTitle, // 分享标题
link: self.shareUrl, // 分享链接
desc: self.shareDesc, // 分享描述
imgUrl: self.shareImage, // 分享图标
success: function() {
console.log('分享给朋友成功啦')
},
cancel: function() {
console.log('分享给朋友失败')
}
})
})
3.可能会遇到的问题
- 二次分享失败,这个可以通过每次在created 时候,直接跳转到
location.origin + location.pathname
- 单页面分享拉取接口时,url应该是#号之前的内容,而不是location.href
网友评论