微信网页授权

照着官方教程设置好JS接口安全域名并且把文件放到服务器后

首先需要引入weixin-js-sdk

然后创建一个文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
export default function weixinShare() {
return axios
.get(`${base.BASE_URL}/share`, {
params: { url: location.href.split("#")[0] },
})
.then((res) => {
const {
data: { code, data },
} = res;
if (code === 200) {
wx.config({ // 获取微信接口的权限
appId: appId, // 必填,企业号的唯一标识,此处填写企业号corpid
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名,见附录1
jsApiList: [
"updateAppMessageShareData",
"onMenuShareTimeline",
"onMenuShareAppMessage",
], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});

let imgUrl = "imgUrl";
let title = "title";
let desc = "";
axios.get(`${base.BASE_URL}/random_link`).then((res) => {
const {
data: { data, code },
} = res;
if (code === 200) {
if (data.linkImage) {
imgUrl = data.linkImage;
}
if (data.linkTittle) {
title = data.linkTittle;
}
if (data.linkContent) {
desc = data.linkContent
}
}
//需在用户可能点击分享按钮前就先调用
wx.ready(function() {
// 分享给朋友 及 分享到QQ
wx.updateAppMessageShareData({
title: title, // 分享标题,(必填,否则失效)
desc: desc, // 分享描述
link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: imgUrl, // 分享图标(必填,否则失效)
success: function() {
console.log("success");
},
fail: function(err) {
console.log(JSON.stringify(err));
},
});
// 分享到朋友圈
wx.onMenuShareTimeline({
title: data.linkTittle, // 分享标题
link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: imgUrl, // 分享图标
success: function() {
console.log("success");
},
fail: function(err) {
console.log(JSON.stringify(err));
},
});
});
});
}
});
}
1
2
3
4
5
6
7
8
beforeEnter(to, from, next) {
weixinShare().then(() => {
next();
}).catch(res=>{
console.log('res: ', res);
next();
});
}

然后在进入页面前调用该接口

作者

Liang

发布于

2020-08-18

更新于

2021-12-25

许可协议


评论