微信 JS-SDK 是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。
通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。
此文档面向网页开发者介绍微信 JS-SDK 如何使用及相关注意事项。
注意:入口记得引入JS文件:
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
//=====wxlogin.js=====
import ajax from '@/lib/network';
export const postWxchatJssdkApi = ({url}={}) => {
return ajax.post('/wechat_open/jssdk',{
url
})
}
//=======login.js======
export const getLoginLink = (redirectUrl) => {
return `${window.location.origin}/wechat_official_login?url=${encodeURIComponent(redirectUrl)}`;
}
//=======wxBridge.js=======
import { postWxchatJssdkApi } from '@/api';
import { getLoginLink, isWeiXin, notifyError, notifyWarn } from '@/utils';
const API_LIST = [
'previewImage',
'chooseWXPay',
'scanQRCode',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'showMenuItems',
'updateAppMessageShareData',
'updateTimelineShareData',
'chooseImage',
'getLocalImgData',
'uploadImage',
'wx-open-launch-weapp'
];
let configCache = {};
const handleLink = link => {
if (!link) {
//登录后跳转的链接
link = window.location.href;
}
return getLoginLink(link);
};
export const wxShare = {
async register() {
if (!isWeiXin()) {
return;
}
// 微信SDK注册接口
const res = await postWxchatJssdkApi({
url: location.href.split('#')[0]
});
const jsConfig = res.data.data;
this.config(jsConfig);
},
configMenuItems(items) {
try {
wx.hideAllNonBaseMenuItem();
wx.showMenuItems({
menuList: items
? items
: [
'menuItem:share:appMessage',
'menuItem:share:timeline',
'menuItem:favorite',
'menuItem:copyUrl'
]
});
} catch (error) {}
},
config({ appId, timestamp, nonceStr, signature } = {}) {
return new Promise((resolve, reject) => {
// if (signature !== configCache.signature) {
configCache = { appId, timestamp, nonceStr, signature };
// }
// if (!configCache.signature) {
// throw new Error('appId, timestamp, nonceStr, signature 不能为空');
// }
try {
wx.config({
...configCache,
debug: false,
jsApiList: API_LIST,
openTagList: ['wx-open-launch-weapp']
});
wx.error(res => {
reject(res);
Loger.error(res);
});
wx.ready(() => {
this.configMenuItems();
// configSuccessFlag = 1;
resolve();
});
} catch (error) {
Loger.error(error);
reject(error);
}
});
},
updateShareData({ title, desc, link, imgUrl, success }) {
// link = handleLink(link);
console.log({ title, desc, link, imgUrl });
if(!isWeiXin()){
Loger.warn('非微信环境,已取消调用分享')
return;
}
try {
//自定义“分享给朋友”及“分享到QQ”按钮的分享内容
wx.updateAppMessageShareData({
title,
desc,
link,
imgUrl,
success
});
} catch (error) {
Loger.error(error);
}
try {
//**自定义“分享到朋友圈”及“分享到 QQ 空间”按钮的分享内容(1.4.0)
wx.updateTimelineShareData({ title, desc, link, imgUrl, success });
} catch (error) {
Loger.error(error);
}
}
};
在入口文件main.js中注册wxShare.register();使用