springBoot 微信AirKiss 配網界面調起Demo

 

第一步 :WeiXinController 

    @RequestMapping("index")
	public String homeIndex(){
		return "index";
	}




/**
	 * 配置信息
	 * @return
	 */
	@RequestMapping("readInfo")
	@ResponseBody
	public String readInfo(){
		try {
			String reStr = JSONObject.toJSONString(
					WebApi.createConfig("訪問頁面的地址")) ;
			System.out.println("配置信息 : "+reStr);
			return reStr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

 

第二步: 獲取jsapi_ticket

 

package com.openwan.weixin.util.wifi;

import com.alibaba.fastjson.JSONObject;
import com.openwan.weixin.util.WeixinAccessTokenUtil;


import java.io.IOException;

import java.util.UUID;

/**
 * 網站配置相關 API
 */
public class WebApi {
	private static final String JsapiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=ACCESS_TOKEN";

	public static void main(String[] args) throws IOException {
		getJsTicket();
	}


	/**
	 * 生成JsAPIConfig
	 * 
	 * @Title: createConfig
	 * @Description: TODO
	 * @param @param link 使用AirKiss的鏈接地址
	 * @param @return
	 * @param @throws Exception
	 * @return JsAPIConfig
	 * @throws
	 */
	public static JsAPIConfig createConfig(String link) throws Exception {
		JsAPIConfig config = new JsAPIConfig();
		config.setLink(link);
		String nonce = UUID.randomUUID().toString();
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		String src = "jsapi_ticket=" + getJsTicket() +
				   "&noncestr=" + nonce +
				   "&timestamp=" + timestamp +
				   "&url=" + config.getLink();
		String signature = SHA1.gen(src);
		config.setAppId(WeixinAccessTokenUtil.APPID);
		config.setDebug(true);
		config.setNonce(nonce);
		config.setTimestamp(timestamp);
		config.setSignature(signature);
		return config;
	}




	/**
	 * 獲取jsapi_ticket
	 * 
	 * @return
	 */
	public static String getJsTicket() throws IOException {
		String token = WeixinAccessTokenUtil.timeOutNewsGetToken();

		String url = JsapiTicketUrl.replace("ACCESS_TOKEN",token);
		System.out.println("請求ticketUrl:"+ url);
		JSONObject codeJson = WeixinAccessTokenUtil.doGetStr(url);
		System.out.println("ticket :" + codeJson.toJSONString());
		String ticket = codeJson.getString("ticket");
		System.out.println("ticket=" + ticket);
		return ticket;

	}

}







--------------------------------------------

package com.openwan.util;

import java.security.MessageDigest;

/**
 * sha1 加密
 * @author liujt
 *
 */
public class SHA {
	

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',  
                           '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};  
  
    /** 
     * Takes the raw bytes from the digest and formats them correct. 
     * 
     * @param bytes the raw bytes from the digest. 
     * @return the formatted bytes. 
     */  
    private static String getFormattedText(byte[] bytes) {  
        int len = bytes.length;  
        StringBuilder buf = new StringBuilder(len * 2);  
        // 把密文轉換成十六進制的字符串形式  
        for (int j = 0; j < len; j++) {  
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);  
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);  
        }  
        return buf.toString();  
    }  
  
    public static String encode(String str) {  
        try {  
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");  
            messageDigest.update(str.getBytes());  
            return getFormattedText(messageDigest.digest());  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

}

 

第三步:index頁面

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta charset="UTF-8"/>
    <title>微信JS-SDK測試</title>
    <script src="https://sqimg.qq.com/qq_product_operations/jslib/jquery-1.9.1.min.js"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script>

        window.onload = function() {

            $(function(){
                $.ajax({
                    type : "get",
                    url : "./readInfo",
                    success : function(result) {
                        var jsObject = JSON.parse(result);

                        wx.config({
                            beta : true, // 開啓內測接口調用,注入wx.invoke方法
                            debug : false, // 開啓調試模式
                            appId : jsObject.appId, // 第三方app唯一標識
                            timestamp : jsObject.timestamp, // 生成簽名的時間戳
                            nonceStr : jsObject.nonce,  // 生成簽名的隨機串
                            signature : jsObject.signature, // 簽名
                            url: jsObject.link,
                            jsApiList : ['configWXDeviceWiFi'] // 需要使用的jsapi列表
                        });
                    },
                    error : function(e){
                        console.log(e.status);
                        console.log(e.responseText);
                    }
                });
            });

        };



        function jump(){
            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['configWXDeviceWiFi'],
                    success: function (res) {
                        wx.invoke('configWXDeviceWiFi', {},
                            function (res) {
                                var err_msg = res.err_msg;
                                if (err_msg == 'configWXDeviceWiFi:ok') {
                                    alert("配置 WIFI成功")
                                    WeixinJSBridge.call('closeWindow');
                                    return;
                                } else {
                                    alert("配置 WIFI失敗");
                                }
                            });

                    }
                });
            });
        }



    </script>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <div style="width:100%;height:25rem;font-size:5rem;"></div>
        <p  style="text-align:center;font-size:40px;">1.確定手機已經連接wifi</p>
        <p  style="text-align:center;font-size:40px;">2.請長按模塊上的網絡配置按鈕</p>
        <p  style="text-align:center;font-size:40px;">3.請等待wifi配置指示燈閃爍後鬆開</p>
        <div align="center">
            <input style="color:white;width:90%;height:8rem;font-size:4rem;" type="button" value="繼續配置" οnclick='javascrtpt:jump()'/>
        </div>

    </div>
</form>
</body>
</html>

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章