项目场景:
提示:一般用于已经分享到朋友圈的h5页面,打开之后点击右上角...再次分享给好友和朋友圈的文章标题和图片配置
微信官方开放文档
代码:
<template>
<div>测试微信二次分享</div>
</template>
<script>
import { getSign } from "@/server/api";
//在需要调用 JS 接口的页面引入如下 JS 文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js
//如需进一步提升服务稳定性,当上述资源不可访问时,可改访问:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)。
export default {
data() {
return {};
},
created() {
console.log(window.location.href, "这里的地址需要着重注意:《通过后端的接口获取微信配置的参数时,需要传递当前页面url,-----url(当前网页的URL,不包含#及其后面部分),如果没有#,则需要传递完整的url - url需要编码 encodeURIComponent(url) 》");
getSign({ shareUrl: window.location.href }).then((res) => {
console.log(res, "签名相关的东西");
wx.config({
debug: false,
appId: "*************", //必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.nonceStr, // 必填,生成签名的随机串
signature: res.signature, // 必填,签名
jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"], // 必填,需要使用的JS接口列表
success: () => {
console.log("成功");
},
});
this.wxShare();
});
},
methods: {
wxShare() {
wx.ready(function () {
wx.updateAppMessageShareData({
title: "测试微信二次分享分享给「好友」自定义标题", // 分享标题
desc: "商品正在热销!", // 分享描述
link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致(通俗来讲:就是这个页面的链接,包括后面携带的参数)
imgUrl: "https://img.zmtc.com/2020/0525/20200525104347190.jpg", // 分享图标
trigger: function trigger(res) {},
success: function success(res) {
// alert("分享好友成功");
},
cancel: function cancel(res) {
// alert("好友已取消");
},
fail: function fail(res) {
console.log(JSON.stringify(res), "好友失败"); //分享失败
},
});
wx.updateTimelineShareData({
title: "测试微信二次分享分享到「朋友圈」自定义标题", // 分享标题
desc: "商品正在热销!", // 分享描述
link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: "https://img.zmtc.com/2021/0108/20210108042212251.jpg", // 分享图标
trigger: function trigger(res) {},
success: function success(res) {
// alert("分享成功");
},
cancel: function cancel(res) {
// alert("已取消");
},
fail: function fail(res) {
console.log(JSON.stringify(res), "朋友圈失败"); //分享失败
},
});
wx.error((res) => {
alert(JSON.stringify(res), "错误");
console.log(JSON.stringify(res) + "微信验证失败");
// console.log(JSON.stringify(res) + "微信验证失败");
});
});
},
},
};
</script>
<style>
</style>
注意事项:
【1.微信公众号设置js安全域名:前端必须部署在js安全域名下才能测试】和
【2.ip白名单:后端部署在ip白名单下的域名下才能测试】