微信jssdk
要做到微信分享网页,必须要引入微信的jssdk,以下是npm 引入,也可以通过js文件引入; 这里是微信开发文档
npm i -s weixin-jsapi
// main.js
import wx from 'weixin-jsapi'
Vue.prototype.$wx = wx
把wx注册为全局的,这样到那个组件都不怕了哦!
分享配置
微信分享大致流程为:
- 用当前url地址向后台请求签名,
wxShare(url) {
let self = this;
this.$axios
.get(
"http://mp.youkuaiyun.com/user/pay/getWxShareSign?url=" + url
)
.then(res => {
self.wxConfig(res.data.data);
});
},
// 这里请求的url,是向自己后台请求的
- 拿到后台签名,调用微信的 config方法进行配置信息
wxConfig(wx) {
this.$wx.config({
debug: false, // true为调试模式,可在手机上观察
appId: "", // 微信的appid
timestamp: wx.timestamp, // 向后台请求的
nonceStr: wx.nonceStr, // 后台请求的
signature: wx.signature, // 后台请求的
jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"] // 是执行微信分享的方法要在这里注册
});
}
// onMenuShareTimeline 分享朋友圈
// onMenuShareAppMessage 分享给朋友
- 配置信息成功在微信的ready方法中,执行分享的方法。
this.$wx.ready(function() {
self.$wx.onMenuShareTimeline({
title: "标题",
link:"分享的url",
imgUrl:"图片", // 这里的图片最好设置为 http://mp.youkuaiyun.com/wxLogo.jpg 这样形式的,相对地址和绝对地址好像不行
success: function() {
console.log("分享朋友圈成功");
},
cancel: function() {
console.log("分享朋友圈失败");
}
});
self.$wx.onMenuShareAppMessage({
title: "标题",
desc: "简介",
link: "分享的url",
imgUrl: "图片",
success: function() {
console.log("分享到朋友成功");
},
cancel: function() {
console.log("分享到朋友失败");
}
});
});
- 分享成功
注意事项
- android和ios 的url机制不同,所以同一套代码可能会出现android成功,ios不成功。所以我们要在url请求后台的时候,做一下区分。
if (typeof window.entryUrl === "undefined" || window.entryUrl === "") {
window.entryUrl = encodeURIComponent(location.href.split("#")[0]); // ios的url
}
let url = /Android/i.test(navigator.userAgent)
? encodeURIComponent(window.location.href) // android的url
: window.entryUrl;
this.wxShare(url);
- 只要请求后台的签名不会出错,剩下可能出现的问题就是细节问题了,仔细检查代码
- ios系统下分享出去的url,一定不要出现端口号!!!!,当时被这个问题困扰了一天。
所以我的代码为:
created() {
if (typeof window.entryUrl === "undefined" || window.entryUrl === "") {
window.entryUrl = encodeURIComponent(location.href.split("#")[0]);
}
let url = /Android/i.test(navigator.userAgent)
? encodeURIComponent(window.location.href)
: window.entryUrl;
this.wxShare(url);
},
methods:{
wxShare(url) {
let self = this;
this.$axios
.get(
"http://mp.youkuaiyun.com/user/pay/getWxShareSign?url=" + url
)
.then(res => {
self.wxConfig(res.data.data);
});
},
wxConfig(wx) {
this.$wx.config({
debug: false,
appId: "appID",
timestamp: wx.timestamp,
nonceStr: wx.nonceStr,
signature: wx.signature,
jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"]
});
let self = this;
this.$wx.ready(function() {
self.$wx.onMenuShareTimeline({
title: "标题",
link:‘分享的url’
imgUrl:"图片",
success: function() {
console.log("分享朋友圈成功");
},
cancel: function() {
console.log("分享朋友圈失败");
}
});
self.$wx.onMenuShareAppMessage({
title: "标题",
desc: "简介",
link: '分享的url'
imgUrl: "图片",
success: function() {
console.log("分享到朋友成功");
},
cancel: function() {
console.log("分享到朋友失败");
}
});
});
}
}
// 一个月薪2500的狗头,只能记录+分享它的狗生了…