1.引入JS库javascript
<script type='text/javascript' src='//res.wx.qq.com/open/js/jweixin-1.0.0.js'></script>
2.为页面注入配置信息java
wx.config({ beta: true, // 开启内测接口调用,注入wx.invoke方法,很是重要!!必须有这个 debug: true,//开启调试接口,alert运行结果 appId: '',//必填,公众号的惟一标识, timestamp: '',//必填,生成签名的时间戳 nonceStr: '',//必填,生成签名的随机串 signature: '',//必填,签名 jsApiList: []//要调用的js函数,必须把函数名字写入数组 });
这里个人jsApiList为git
jsApiList: [ 'openWXDeviceLib',//初始化设备库(只支持蓝牙设备) 'closeWXDeviceLib',//关闭设备库(只支持蓝牙设备) 'getWXDeviceInfos',//获取设备信息(获取当前用户已绑定的蓝牙设备列表) 'sendDataToWXDevice',//发送数据给设备 'startScanWXDevice',//扫描设备(获取周围全部的设备列表,不管绑定仍是未被绑定的设备都会扫描到) 'stopScanWXDevice',//中止扫描设备 'connectWXDevice',//链接设备 'disconnectWXDevice',//断开设备链接 'getWXDeviceTicket',//获取操做凭证 'onWXDeviceBindStateChange',//微信客户端设备绑定状态被改变时触发此事件 'onWXDeviceStateChange',//监听链接状态,能够监听链接中、链接上、链接断开 'onReceiveDataFromWXDevice',//接收到来自设备的数据时触发 'onScanWXDeviceResult',//扫描到某个设备时触发 'onWXDeviceBluetoothStateChange',//手机蓝牙打开或关闭时触发 ]
若是想要测一下微信版本是否是支持这几个api,能够这样写:github
wx.checkJsApi({ jsApiList: ['openWXDeviceLib', 'onScanWXDevicesResult', 'getWXDeviceInfos'], // 须要检测的JS接口列表,全部JS接口列表见附录2, success: function (res) { console.log(res); } });
3.初始化设备库函数api
经过ready接口处理成功验证数组
wx.ready(function () { wx.invoke('openWXDeviceLib', {connType: 'blue'}, function (res) { console.debug('openWXDeviceLib从新打开设备库==>'); console.log(res); }); })
坑:从新扫描设备根本什么都扫不出来,即便是刷新页面也不顶用安全
解决方法:每次扫描前,先调用closeWXDeviceLib关闭设备库,再调用openWXDeviceLib打开设备库。这样就至关于从新初始化了一遍设备库,你如今再从新扫描,就能够扫描到设备了。微信
代码:app
wx.invoke("stopScanWXDevice", {}, function (res) { console.debug('stopScanWXDevice'); console.log(res); }); wx.invoke("closeWXDeviceLib", {}, function (res) { console.debug('closeWXDeviceLib关闭设备库==>'); console.log(res); }); wx.invoke('openWXDeviceLib', {connType: 'blue'}, function (res) { console.debug('openWXDeviceLib从新打开设备库==>'); console.log(res); });
4.监听设备返回的信息函数
wx.on('onReceiveDataFromWXDevice', function (res) { console.warn('onReceiveDataFromWXDevice=>'); console.log(JSON.stringify(res)); });
5.发送消息到设备
收发数据前需进行 base64 的编解码。
这里,我用到一个库:
<script type='text/javascript' src='base64.js'></script>
出处:
https://github.com/dankogai/j...
var data={"deviceId":deviceId,"base64Data": Base64.encode('你要发送的数据')}; console.log(data); wx.invoke('sendDataToWXDevice',data , function(res){ //回调 console.info('发消息到设备sendMsg'); console.log(data); console.log(res); $('#dataFromDevice').append('发送消息的结果:'+JSON.stringify(res)); alert('已发送 请查看控制板'); });
说明:
1.须要在微信对应设备号内才能使用对应的api。
2.必需要在设备号设置的安全域名下才能正常使用api
3.本篇内全部的console.log 等输出到控制台 都是用的vconsole调试工具实现。