1. 程式人生 > >微信公眾號開發——3、硬體裝置接入

微信公眾號開發——3、硬體裝置接入

一、為裝置新增產品

1、在認證過的服務號或訂閱號下,在微信公眾平臺新增“裝置功能”外掛。公眾測試號提供裝置功能介面,供開發者測試使用。

2、在公眾號平臺的“測試號管理”下,選擇“裝置功能介面”並對其進行設定,進入“產品管理介面”並選擇“新增產品”。

3、產品新增成功後,會為每一型別的產品提供一個產品編號,該產品編號在為裝置授權時,以product_id欄位為每個產品授權,預設分配100個測試產品。

重點引數:

每個產品唯一的二維碼:微信硬體平臺要求每一個註冊裝置都有唯一的裝置編號,裝置開發者可以呼叫微信 後臺介面生成帶裝置編號的二維碼,每個二維碼需要與每臺裝置一一對應。使用者購買產 品的同時拿到裝置二維碼,通過掃描裝置二維碼就可以在微信上直接繫結該裝置

每種型號唯一的二維碼:型號二維碼是指一個二維碼對應某一個類別/型號的產品,不包含某個具體裝置的資訊,因此在裝置生產過程中,不需要二維碼與裝置進行一一對應。使用者使用掃一掃,掃描品類二維碼時,微信客戶端會通過區域網發現技術搜尋該類別/型號的裝置,發現後再進行繫結。因此,使用型號二維碼的裝置必須支援微信AirKiss區域網發現(即AirKiss2.0)

微信配網:通過微信公眾號使用AirKiss技術為硬體裝置進行連網配置。

藍芽配網:通過微信公眾號使用AirSync技術為硬體裝置進行連網配置。

二、獲取裝置二維碼:

型號二維碼(每種型號唯一的二維碼):在新增產品時,若選擇了產品二維碼對應型別,在裝置管理的產品詳情,可以找到對應產品對應的二維碼。

一機一碼(每個產品唯一的二維碼):每授權一個裝置,產品對應授權配額將為減少減少一個。通過以下兩種方式進行授權

方案一:第三方獲取deviceid和裝置二維碼(由微信公眾平臺生成裝置id,根據產品id和公眾賬號access_token隨機授權一臺裝置,並生成deviceid),呼叫微信介面如下

	private void getqrcode(String token, String productid) throws Exception{
		String initUrl = "https://api.weixin.qq.com/device/getqrcode?access_token=" + token + "&product_id=" + productid;
		doGet(new URL(initUrl));
	}
	protected String doGet(URL url) throws Exception{
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
		StringBuffer sb = new StringBuffer();
		String line = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
			while((line = reader.readLine()) != null){
				sb.append(line);
			}
		}
		reader.close();
		connection.disconnect();
		return sb.toString();
	}
返回結果格式如下:
{
	"base_resp":
	{
		"errcode":0,
		"errmsg":"ok"
	},
	"deviceid":"deviceid",
	"qrticket":"qrticket",
	"devicelicence":"devicelicence"
}

其中,deviceid表示每個裝置對應的標識,qrticket是該裝置對應的二維碼連結,通過草料二維碼即可生成相應二維碼,devicelicence為裝置證書,可提供給裝置作為憑據。之後需要為裝置進行授權,方可在網頁中獲取裝置資訊,併為裝置配網。

該授權過程同方案2,但post資料格式不同,不需要productid為引數,op_type設為1,post資料格式如下

{
    "device_num":"1",
    "device_list":[
    {
        "id":"deviceid",
        "mac":"1cda27c12d69",
        "connect_protocol":"4",
        "auth_key":"Abcdef1234566543abcdef1234566544",
        "close_strategy":"2",
        "conn_strategy":"1",
        "crypt_method":"0",
        "auth_ver":"0",
        "manu_mac_pos":"-1",
        "ser_mac_pos":"-2",
        "ble_simple_protocol": "0"
    }
    ],
    "op_type":"1"
}
方案二:第三方公眾賬號將deviceid及其屬性提交到公眾平臺,並進行授權,之後再呼叫微信介面獲取對應裝置的獲取二維碼(需要硬體裝置提供deviceid及其他屬性資訊),post呼叫微信介面如下,其中本文post引數從檔案中讀取。

授權過程(如果deviceid已經被授權過,則不能重新授權):

	private void authorizeDevices(String token, String postFilePath ) throws Exception{
		URL url = new URL("https://api.weixin.qq.com/device/authorize_device?access_token=" + token);
		doPost(url, postFilePath);
	}
	protected void doPost(URL url, String postFilePath) throws Exception{
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setConnectTimeout(5*1000);
        connection.setReadTimeout(5*1000);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset","utf-8");
        connection.setRequestProperty("Content-Disposition","utf-8");
        String params = readfile(postFilePath);
        OutputStream os = connection.getOutputStream();
        os.write(params.getBytes());
        os.flush();
        os.close();
        if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK){
            InputStream is = connection.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] bytes = new byte[1024];
            int i = 0;
            while ((i = is.read(bytes)) != -1){
                sb.append(new String(bytes,0,i,"utf-8"));
            }
            is.close();
        }
        os.close();
        connection.disconnect();
	}
	private String readfile(String path) throws Exception{
		FileReader fileReader = new FileReader(path);
		BufferedReader reader = new BufferedReader(fileReader);
		StringBuffer sBuffer = new StringBuffer();
		String line = "";
		while((line = reader.readLine()) != null){
			sBuffer.append(line);
		}
		fileReader.close();
		reader.close();
		return sBuffer.toString();
	}
post檔案格式如下,一次授權裝置數量建議不超過5個。
{
    "device_num":"1",
    "device_list":[
    {
        "id":"test",
        "mac":"1cda27c12d69",
        "connect_protocol":"4",
        "auth_key":"Abcdef1234566543abcdef1234566544",
        "close_strategy":"2",
        "conn_strategy":"1",
        "crypt_method":"1",
        "auth_ver":"1",
        "manu_mac_pos":"-1",
        "ser_mac_pos":"-2",
        "ble_simple_protocol": "0"
    }
    ],
    "op_type":"0",
    "product_id": "40332"
}
微信伺服器返回資料格式如下:
{
	"resp":
	[{
		"base_info":
			{
				"device_type":"gh_3ec41c424",
				"device_id":"test"
			},
		"errcode":0,"errmsg":"ok"
	}]
}
其中device_type表示微信公眾號的原始id,device_id表示硬體裝置所提供的唯一標識。

根據device_id生成二維碼過程(建議獲取二維碼連結一次不超過5個):

	private void create_qrcode(String token, String postFilePath) throws Exception{
		URL url = new URL("https://api.weixin.qq.com/device/create_qrcode?access_token=" + token);
		doPost(url, postFilePath);
	}
傳送post資料格式如下:
{
    "device_num":"1",
    "device_id_list":[
		"test"
		]
}
返回對應的二維碼格式如下:
{
	"errcode":0,
	"errmsg":"ok",
	"device_num":1,
	"code_list":
	[{
		"device_id":"test",
		"ticket":"http://we.qq.com/d/AQA0CYHUzuT6DRPIo9pmjSA9yq2SPqcfv6z5"
	}]
}
通過草料二維碼即可生成相應的二維碼圖片。

三、公眾號繫結裝置

1、使用型號二維碼繫結裝置:

微信掃碼型號二維碼:將首先進入網路配置模式,裝置需要具備微信配網(Airkiss)或藍芽配網(AirSync)的功能。微信將通過區域網發現功能區藍芽發現功能搜尋相應裝置,併為裝置進行網路配置。

2、使用一機一碼繫結裝置:

掃碼繫結即可。

3、微信中檢視繫結的裝置:

路徑:"我"->"設定"->"裝置"。

四、在網頁中獲取裝置資訊

關鍵資訊:使用者openid,參考”微信網頁開發“第三部分,兩種方式獲取openid。

	public String getBindDevicesByOpenId(String token, String open_id) throws Exception{
		String url = "https://api.weixin.qq.com/device/get_bind_device?access_token=" + token + "&openid=" + open_id;
		 String connect = doGet(new URL(url));
		 return connect;
	}
獲取資料格式如下:
{
	"resp_msg":
	{
		"ret_code":0,
		"error_info":"ok"
	},
	"openid":"oNAmB1KA5ykfs09m02N0AhcUk",
	"device_list":
	[
		{
			"device_type":"gh_3154bc424",
			"device_id":"AA25799",
			"sub_device_list":[]
		},
		{
			"device_type":"gh_3154bc424",
			"device_id":"test",
			"sub_device_list":[]
		}
	]
}
五、為裝置配置網路

1、型號二維碼:

使用微信掃一掃型號二維碼,按流程即可成功為已進入網路配置模式的裝置進行配置網路。

2、一機一碼:

在網頁中呼叫JsApi介面為裝置配置網路。在jsp網頁配置如下:

<script type="text/javascript">
	 wx.config({
		beta:true,
		debug : false,
		appId : '${appid}',
		timestamp : ${sign.timestamp},
		nonceStr : '${sign.nonceStr}',
		signature : '${sign.signature}',
		jsApiList : ['configWXDeviceWiFi',
		             'openWXDeviceLib',
		             'startScanWXDevice',
		             'getWXDeviceInfos']
	});

	$(document).ready(function(){  
		wx.ready(function(){
			wx.invoke('configWXDeviceWiFi', {}, function(res){
			    var err_msg = res.err_msg;
			    if(err_msg == 'configWXDeviceWiFi:ok') {
			        alert("配網成功" + res);
			    }
			 }); 
		})
	});
</script>
注意事項:

1、注入js檔案:

<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
2、確保signature有效,保證網頁有權呼叫介面,可設定bubug:true開啟除錯模式