JS-SDK 是微信平台提供的客户端 API, 被广泛应用与基于网页的微信公众号,企业微信开发。本文演示如何在 Vue 项目中集成、使用 JS-SDK。
安装必要的依赖库
基于 JS-SDK 开发的网页项目,至少需要依赖来两个库: 1. JS-SDK 本身; 2. 需要一个访问企业后端的库, 在 Vue 项目中我们通常使用 axios。 因此,在项目目录中执行以下安装命令:
配置 JS-SDK
为了配置 JS-SDK,需要首先获取当前页面的 ticket, 示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| wxAccessor.enable_jssdk( "/jssdk/enable?url=" + path, data => { console.log("ok, data = " + JSON.stringify(data));
wx.config({ beta: true, debug: true, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: [ "chooseImage", "previewImage", "shareAppMessage", "shareWechatMessage", "onMenuShareAppMessage", "onMenuShareTimeline", "scanQRCode" ] }); }, (code, msg) => { console.log("fail code = " + code + ", msg = " + msg); } );
|
可以看到, 在代码中使用了 JS-SDK 中的对象 wx, 并通过 wx 的 config 方法来验证当前页面的签名并请求微信的相关权限(包含在 jsApiList 数组中)
而 config 中使用的参数值,又是通过后台的api来完成的,对于为 wxAccessor.enable_jssdk 这个函数,相关的定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import axios from 'axios'
var instance = axios.create({ baseURL: 'https://<你的后台系统域名>', headers: {'content-type': 'application/json'} })
var wxAccessor = {
enable_jssdk: function(path, success, fail) { instance.get(path) .then((result) => { if (result.data.succ) { success(result.data.data) } else { fail(result.data.code, result.data.msg) } }, (error) => { console.log(error) }) } }
export default wxAccessor
|
Ready 方法
如果 wx.config 方法放回正常,则 wx 中的另一个方法 - ready 会被调用,我们可以在 ready 方法中完成微信功能相关的设置。如果 config 发送异常,我们也可以在 wx.error 方法中获取错误信息,如下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| wx.ready(function() { console.log("js-sdk ready"); vm.wxReady = true; wx.onMenuShareAppMessage({ title: "通过转发按钮分享", desc: "活动很不错", link: "https://<要分享的网页>", imgUrl: "", success: function() { console.log("share successfully."); }, cancel: function() { console.log("cancel share."); } }); wx.onMenuShareTimeline({ title: "分享到朋友圈啦", link: "https://<要分享的网页", imgUrl: "", success: function() { console.log("share to timeline successfully."); }, cancel: function() { console.log("cancel share..."); } }); wx.showOptionMenu(); }); wx.error(function(res) { console.log("js-sdk error msg...: " + JSON.stringify(res)); });
|