1.安装weixin-js-sdk
npm install weixin-js-sdk --save-dev
2.在封装的微信js文件中引入weixin-js-sdk
import wx from 'weixin-js-sdk';
3.在utils文件夹下新建wx_share.js,封装一个微信分享js文件
import axios from './axios';
import wx from 'weixin-js-sdk';
/* 微信自定义分享 */
export const WeShare = (url, shareInfo) => {
/* url是分享链接 */
let { nameCn, shareDesc, sharePic } = shareInfo;
// 分享链接,每次分享要去除参数,以便每次打开链接都重新获取code进行授权
let shareLink = url;
if (url.indexOf('?') > -1) {
shareLink = url.substring(0, url.indexOf('?'));
}
if (url.includes('#')) {
url = url.split('#')[0];
}
let title = nameCn,
imgUrl = sharePic,
link = shareLink,
desc = shareDesc;
// 获取签名信息
axios
.get('xxxxxxxxxxxxxx', {
params: { url: decodeURIComponent(url) },
})
.then((res) => {
console.log(res.data);
let { timestamp, noncestr, signature } = res.data;
wx.config({
debug: false,
appId: 'xxxxxxxx',
timestamp: timestamp, //必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: signature, // 必填,签名
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'], // 必填,需要使用的JS接口列表
});
// 检测
wx.ready(() => {
// 自定义“分享给朋友”及“分享到QQ”(1.4.0)
wx.updateAppMessageShareData({
title: title,
desc: desc,
link: link,
imgUrl: imgUrl,
success: () => {},
});
// 自定义“分享到朋友圈”及“分享到QQ空间”(1.4.0)
wx.updateTimelineShareData({
title: title,
link: link,
imgUrl: imgUrl,
success: () => {},
});
});
})
.catch((err) => {
console.log('JSSDK share error:', err);
});
};
4.直接在app.vue中使用封装的wx_share.js
import { WeChatShare } from '@/utils/wx_share';
created() {
//获取链接地址的code值
let code = this.getQueryString('code');
if (code) {
// 微信授权;
this.getWXShowQuan(code);
} else {
let search = window.location.search,
origin = window.location.origin;
let redirect_uri = encodeURIComponent(`${origin}${search}`);
window.location.href = `https://xxxxxxxxxxxxxx.com/xxxxxxxxxxxxxx?appid=xxxxxxxxxxxxxxx&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
//appid=xxxxxxxx;是公众号的appid
return;
}
},
mounted() {
// 微信分享
let authUrl = window.location.href;//页面链接
let logoStr = 'http://XXX.com/img/logo.png';//分享图标
setTimeout(() => {
WeChatShare(authUrl, {
nameCn: '标题',
shareDesc: '详细介绍',
sharePic: logoStr,
});
}, 400);
},
methods: {
// 获取地址栏参数
getQueryString(n) {
let r,
reg = new RegExp('(^|&)' + n + '=([^&]*)(&|$)');
r = window.location.search.substring(1).match(reg);
return r ? decodeURI(r[2]) : null;
},
getWXShowQuan(code){....授权请求.....}
}
5.需要注意的地方
注意: 分享链接link可以做处理,但是向后端获取签名时传的url必须是当前页面的地址,也就是 window.location.href,同时要对url解码,也就是decodeURIComponent(url),url不能带‘#’,反正这里获取签名很严格;请求链接域名还要和公众号配置的域名一致; 本人开发过程中遇到的坑,绕了很多弯路啊。。。分享过程中各种情况出现。
主要原因:分享链接不正确;weixin-js-sdk引入错误,不能
//<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
重复引用