wxShare.js
import wx from 'weixin-js-sdk';
import {ticketUrlApi, userInfosApi} from "../api/api";
import {SessionGet, SessionPut} from "./dataStorage"; // 微信sdk 版本号是1.6.0
// 基本配置 -> 公众号开发信息 -> 开发者ID(AppID)
let appId = undefined;
let timestamp = undefined;
let nonceStr = undefined;
let signature = undefined;
let paramsList = undefined; // 初始化网址
let assessments = {
title: undefined,
content: undefined,
pic: undefined,
};
const jsApiList = ['updateTimelineShareData', 'updateAppMessageShareData', 'wx-open-launch-app'];
//要用到微信API
function getJSSDK() {
wx.config({
debug: false, // 可开启调试模式
appId: appId, // 需要后端接口返回的appId
timestamp: timestamp, // 需要后端接口返回的timeStamp
nonceStr: nonceStr,// 需要后端接口返回的nonceStr
signature: signature, // 需要后端接口返回的signature
jsApiList: jsApiList, // 注册的微信jsapi
openTagList: ['wx-open-launch-app'],
success: () => {
console.log("success...")
},
});
// 分享的展示信息
let shareData = {
title: assessments.title ? assessments.title : "漂流瓶探聊",
desc: assessments.content ? assessments.content : "快来遇见让你心动的TA!",
imgUrl: assessments.pic ? assessments.pic : "https://profile.csdnimg.cn/F/E/5/0_weixin_44653409",
link: SessionGet("shareUrl"),
};
wx.ready(() => {
wx.updateAppMessageShareData(shareData);
wx.updateTimelineShareData(shareData);
// wx.onMenuShareAppMessage(shareData);
// 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
// wx.onMenuShareTimeline(shareData);
// 监听“分享到QQ”按钮点击、自定义分享内容及分享结果接口
// wx.onMenuShareQQ(shareData);
// 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
// wx.onMenuShareWeibo(shareData);
});
wx.error((res) => { // 注册 wx.config的报错提示
console.log(JSON.stringify(res) + "微信验证-----错误信息错误信息错误信息-");
});
}
/**
* 初始化微信SDK
*/
function getWeiXinSignature() {
if (SessionGet("assessments")) assessments = SessionGet("assessments")
// 当前url
let url = window.location.href;
// 初始化微信分享跳转url
if (!SessionGet("shareUrl")) {
paramsList = new URLSearchParams(url.split('?')[1])
if (paramsList.get('state')) {
SessionPut("shareUrl", window.location.origin + paramsList.get('state'))
}
}
/**
* 获取微信SDK配置
*/
ticketUrlApi({
url: SessionGet("shareUrl")
}).then((res) => {
appId = res.appId
signature = res.signature
nonceStr = res.nonceStr
timestamp = res.timestamp
// token 登陆
if (url.includes("token")) {
// alert("token 登陆....")
getJSSDK()
} else if (SessionGet("userInfo")) {
// alert("缓存 登陆....")
getJSSDK()
} else if (url.includes("code")) { // 微信浏览器直接访问 获取用户信息
// alert("code 登陆....")
getUserInfos()
} else { // 获取用户 code 绑定用户
// alert("初始化 登陆....")
getWeixinCode(url)
}
});
}
// 微信浏览器直接访问 获取用户信息 并跳转指定页面
function getUserInfos() {
userInfosApi({
code: paramsList.get('code')
}).then((res) => {
SessionPut("userInfo", res)
window.location.href = SessionGet("shareUrl")
});
}
// 获取用户 code 并标记跳转的指定页面
function getWeixinCode(url) {
// 授权后重定向的回调链接地址,官方要求用urlEncode对链接进行处理
const callbackURL = encodeURIComponent(url)
// 重定向后会带上state参数,最多128字节
const state = encodeURIComponent(window.location.pathname + window.location.search)
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${callbackURL}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
}
export default {
getWeiXinSignature,
appId
}
页面添加微信浏览器跳转
html
<wx-open-launch-app id="wxopenLanchAppId" appid="要跳转的appid" extinfo="getExtinfo">
<script type="text/wxtag-template">
<style>
.diy-style{
color: white;
}
</style>
<span class="diy-style" :style="{width: window.outerWidth}">分享WX</span>
</script>
</wx-open-launch-app>
script
import Vue from "vue";
// 忽略自定义元素标签抛出的报错
Vue.config.ignoredElements = ['wx-open-launch-app'];
methods: {
// 判断是否是微信浏览器
getIsWeiXing() {
let wx = window.navigator.userAgent.toLowerCase();
if (wx.match(/MicroMessenger/i) == 'micromessenger') {
// console.log('是微信浏览器默认走微信')
this.$SessionPut("isWeiXing", true)
/**
* 初始化微信SDK
*/
this.$wxShare.getWeiXinSignature();
} else {
// console.log('不是微信浏览器绘制原生。');
this.$SessionPut("isWeiXing", false)
}
},
init() {
// 判断微信打开并且是安卓
this.$nextTick(() => {
const btn = document.getElementById("wxopenLanchAppId");
btn.addEventListener('error', function (e) {
this.toDownload()
});
});
}
},
created() {
// 刷新分享地址
this.getIsWeiXing()
},
mounted() {
this.init();
},
props: {
href: {
type: String,
default: ''
}
},
判断是否是微信浏览器
getIsWeiXing() {
let wx = window.navigator.userAgent.toLowerCase();
if (wx.match(/MicroMessenger/i) == 'micromessenger') {
console.log('是微信浏览器默认走微信')
return true; // 是微信端
} else {
console.log('不是微信浏览器绘制原生。');
return false; // 是微信端
}
},