最近写了一个公众号 授权及分享 所遇到的问题
首先是授权问题
这个是自己去第三方调的,然后自己本地保存一下自己所需要的东西就好了
分享问题
给后台传的url是动态获取的,而且还得分割,当时没有分割,导致分享失败,在不断尝试后,最终解决了问题。
<template>
<div></div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
GetUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
getCode() {
const code = this.GetUrlParam("code");
const local = window.location.href;
if (code == null || code === "") {
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=" +
encodeURIComponent(local) +
"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
//appid是公众号id
} else {
this.getOpenId(code);
}
},
//传给后台的东西 请求数据可以用自己的方法,这个方法是我这边封装好的
getOpenId(code) {
this.$post("", {
code: code,
pid: 0
}).then(res => {
if (res.code == 200) {
localStorage.setItem("openId", res.user_id.openID);
localStorage.setItem("user_id", res.user_id.id);
localStorage.setItem('pid',res.user_id.p_id);
localStorage.setItem('token',res.user_id.id+'+'+res.user_id.openID);
this.$router.push('/home');
}
});
}
},
created() {
this.getCode();
},
mounted() {}
};
</script>
<style>
</style>
分享代码`
getshare() {
var url = window.location.href.split("#")[0];
this.$post("", {
token: localStorage.getItem("token"),
url: url
}).then(res => {
if (res.code == 200) {
//拿到后端给的这些数据
console.log(res.data);
let appId = res.data.appId;
let timestamp = res.data.timestamp;
let nonceStr = res.data.nonceStr;
let signature = res.data.signature;
// let rawString = res.data.rawString;
Toast("转发朋友圈");
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.appId, // 必填,公众号的唯一标识,填自己的!
timestamp: res.data.timestamp, // 必填,生成签名的时间戳,刚才接口拿到的数据
nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
signature: res.data.signature, // 必填,签名,见附录1
jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"]
});
wx.ready(() => {
//分享给朋友
wx.onMenuShareAppMessage({
title:'', // 分享时的标题
desc:'',// 分享时的链接
link: ''’, // 分享时的链接
imgUrl: "", // 分享时的图标
success: res => {
Toast("分享成功");
this.$post("", {
token: localStorage.getItem("token"),
}).then(res => {
if (res.code == 200) {
Toast(res.msg);
}
});
},
fail: res => {
alert(JSON.stringify(res));
},
cancel: () => {
Toast("取消分享");
}
});
//分享到朋友圈
wx.onMenuShareTimeline({
title: "", // 分享时的标题
link: "", // 分享时的链接
imgUrl: "", // 分享时的图标
success: function() {
Toast("分享成功");
this.$post("", {
token: localStorage.getItem("token"),
}).then(res => {
if (res.code == 200) {
Toast(res.msg);
}
});
},
cancel: function() {
Toast("取消分享");
}
});
});
wx.checkJsApi({
jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
success: function(res) {
console.log(res);
}
});
} else {
Toast(res.msg);
}
});
}