JAVA實現調用微信js-sdk掃一掃

喜歡的朋友可以關注下。 


已經很久沒有給大家分享一片技術文章了,今天抽了點時間來,給大家說一說如何調用微信提供的掃一掃接口。


前提: 需要申請一個公衆號:申請公衆號需要的資料我就不說了,去申請微信會提示需要哪些。 


準備appid(公衆號的id) 

AppSecret (公衆號的密鑰) 


 正文: 首先,我們先來簡單瞭解一下流程,詳細的微信文檔有說明。 


獲取Token→根據token獲取Ticket→根據ticket簽名→反會參數給前端→前端調起掃一掃接口 

下面直接上代碼 

1.獲取token 


/**
     * Description: 獲取微信公衆號token<BR>
     * 
     * @author dsn
     * @date 2018年9月21日 上午9:53:26
     * @param appid
     * @param secret
     * @return
     * @version 1.0
     */
    public static String getAccessToken(String appid, String secret) {
        String token = "";
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
                + "&secret=" + secret;
        JSONObject result = PayCommonUtil.httpsRequest(token_url, "POST");
        if (result.get("access_token") != null) {
            token = result.get("access_token").toString();
        }
        return token;
    }

2.獲取ticket 


/**
     * Description: 獲取微信ticket<BR>
     * 
     * @author dsn
     * @date 2018年9月21日 上午9:54:03
     * @param token
     * @return
     * @version 1.0
     */
    public static String getTicket(String token) {
        if ("".equalsIgnoreCase(token) || null == token) {
            return "";
        }
        String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
        JSONObject result = PayCommonUtil.httpsRequest(ticket_url, "POST");
        return result.get("ticket").toString();
 
    }


3.簽名


 public static String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url)
            throws NoSuchAlgorithmException {
        String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url="
                + url;
        MessageDigest mDigest = MessageDigest.getInstance("SHA1");
        byte[] result = mDigest.digest(shaStr.getBytes());
        StringBuffer signature = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
        }
        return signature.toString();
    }

4.action中調用 


/**
     * Description:微信掃一掃接口 <BR>
     * 
     * @author ran.chunlin
     * @date 2017年4月11日 上午10:07:35
     * @param request
     * @return
     * @throws Exception
     * @version 1.0
     */
    @RequestMapping(params = "method=getWechatSign", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> getWechatSign(HttpServletRequest request) throws Exception {
        /* 返回的json數據 */
        Map<String, Object> jsonMap = new HashMap<>();
        // 構成子數據map
        Map<String, Object> subJsonMap = new HashMap<>();
 
        // 1.獲取參數
        String url = showNull(request.getParameter("url"));
        String t = showNull(request.getParameter("t"));
        String appId = showNull(request.getParameter("appId"));
        String appSecret = showNull(request.getParameter("appSecret"));
        if (url == null || t == null || appId == null || appSecret == null) {
            return json4Map(jsonMap, subJsonMap, "參數爲空", STATUSCODE_FAILED_BADINPUT_PARAM);
        } else {
            String accessToken = WeiXinUtils.getAccessToken(appId, appSecret);
            String ticket = WeiXinUtils.getTicket(accessToken);
            Long timestamp = System.currentTimeMillis() / 1000;
            String nonceStr = RandomStringUtils.randomAlphanumeric(16);
            String sign = getSign(ticket, nonceStr, timestamp, url);
            subJsonMap.put("result", "1");
            subJsonMap.put("timestamp", timestamp);
            subJsonMap.put("nonceStr", nonceStr);
            subJsonMap.put("appId", appId);
            subJsonMap.put("sign", sign);
        }
        return json4Map(jsonMap, subJsonMap, "獲取sign成功", STATUSCODE_SUCCESS);
    }

5.前端代碼 


// 掃一掃 進入頁面時去調用
$.ajax({
	type : 'GET',
	url : "你action的url",
	data : {
			appId : "",
			appSecret : "",
			url : location.href,
			t : Math.random()
		},
		success : function(json) {
			if (json.data.result == "1") {
				wxConfig(json.data.timestamp, json.data.nonceStr,
								json.data.sign, json.data.appId);
			}
		}
});
function wxConfig(_timestamp, _nonceStr, _signature, _appId) {
			wx.config({
// 				debug : false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
				appId : _appId, // 必填,公衆號的唯一標識
				timestamp : _timestamp, // 必填,生成簽名的時間戳
				nonceStr : _nonceStr, // 必填,生成簽名的隨機串
				signature : _signature,// 必填,簽名,見附錄1
				jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage',
						'onMenuShareQQ', 'onMenuShareWeibo', 'scanQRCode' ]
			// 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
			});
		}
 
        //掃碼調用
		function scanCode() {
			wx.scanQRCode({
				needResult : 1,
				scanType : [ "qrCode", "barCode" ],
				success : function(res) {
					console.log(res)
                    //掃描返回的數據
					var result = res.resultStr;
				
				},
				fail : function(res) {
					layer.open({
						content : '請稍後再試',
						skin : 'msg',
						time : 2
					//2秒後自動關閉
					});
 
				}
			});
		}
其實就是這麼的簡單 

 這裏需要提醒大家 頁面一定要引入 <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

 不然會調用不了微信的函數 

 如有需要可以加我Q羣【308742428】大家一起討論技術。 

 後面會不定時爲大家更新文章,敬請期待。 喜歡的朋友可以關注下。

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