設備功能
在“設備功能”處添加產品,接入方案選擇“平臺基礎接入方案”
添加成功後,就有100個配額
服務器配置
URL是後臺回調接口地址,Token是爲了驗證回調信息的合法性的,EncodingAESKey隨機生成即可
服務器配置回調校驗開發
配置校驗回調是以GET方式回調的,同消息事件回調是一個地址,只是請求方式不同。
如果驗證成功,則響應回調請求的echostr值,否則啥也不返回。
代碼示例:
/**
* 微信硬件平臺配置校驗
*
* @param appId
* @param request
* @param response
*/
@RequestMapping(value = "/hardware/{appId}", method = RequestMethod.GET)
@ApiOperation(value="微信硬件平臺配置校驗回調", notes="微信硬件平臺配置校驗回調")
public void receiveIotMsg(@PathVariable("appId") String appId, HttpServletRequest request, HttpServletResponse response) {
logger.info("收到微信硬件消息回調GET:{}", appId);
// 微信加密簽名
String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機數
String nonce = request.getParameter("nonce");
// 隨機字符串
String echostr = request.getParameter("echostr");
Map<String, String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> entry : map.entrySet()) {
logger.info("{}={}", entry.getKey(), entry.getValue() != null ? entry.getValue()[0] : "");
}
// 獲取公衆號信息
SingleParamRequest<String> singleParamRequest = new SingleParamRequest<>();
singleParamRequest.setData(appId);
ServiceJsonBean<OfficialAccount> officialAccountJsonBean = weiXinOfficialAccountService.getOfficialAccountByAppId(singleParamRequest);
String iotToken = "";
if (officialAccountJsonBean.getCode() == ErrorCode.SUCCESS.getCode() && officialAccountJsonBean.getData() != null) {
iotToken = officialAccountJsonBean.getData().getIotToken();
}
String curSign = SecurityUtils.encryptSHA1(iotToken, timestamp, nonce);
if (StringUtils.isEquals(signature, curSign) && StringUtils.isNotEmpty(echostr)) {
logger.info("驗證成功!");
try {
response.getWriter().write(echostr);
} catch (IOException e) {
logger.error("response輸出異常", e);
}
}
}
設備消息、事件回調開發
消息、事件回調跟校驗回調是同一個接口地址,但是請求方式爲POST,Content-Type: application/json
消息、事件會以json格式的傳輸到後臺
/**
* 微信硬件平臺消息回調接口
*
* @param appId
* @return
*/
@RequestMapping(value = "/hardware/{appId}", method = {RequestMethod.POST}, headers = "Accept=application/json")
@ResponseBody
@ApiOperation(value="微信硬件平臺消息回調", notes="微信硬件平臺消息回調")
public WebJsonBean receiveIotMsg(@PathVariable("appId") String appId, @RequestBody DeviceBindMsg deviceBindMsg) {
logger.info("收到微信硬件消息回調POST:{}", JSONObject.toJSONString(deviceBindMsg));
HardwareMsgEvent hardwareMsgEvent = new HardwareMsgEvent(applicationContext, deviceBindMsg, appId);
applicationContext.publishEvent(hardwareMsgEvent);
return new WebJsonBean(ErrorCode.SUCCESS);
}