java調用微信掃一掃

步驟:javascript

1,獲取Accesstoken(參考我以前的文章html

2,獲取jsapiticket(參考我以前的文章java

3,獲取簽名jquery

4JSSDK使用步驟web

  步驟一:綁定域名(JS接口安全域名),。不然會報invalid url domain
  步驟二:引入JS文件http://res.wx.qq.com/open/js/jweixin-1.2.0.js
  步驟三:經過config接口注入權限驗證配置
  步驟四:經過ready接口處理成功驗證
  步驟五:經過error接口處理失敗驗證spring

5.調用掃一掃接口api

 

controller安全

package controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import util.AccessTokenUtil;

/**
 * @author zhangyanan
 * @todo 微信掃一掃
 * @date 2018年7月23日
 */
@Controller
@RequestMapping("/scan")
public class ScanController {
    Logger logger=LoggerFactory.getLogger(ScanController.class);
    
    /**
     * @todo 掃一掃準備操做 
     * @author zhangyanan
     * @date 2018年7月31日
     */
    @RequestMapping("/preScan")
    public String preScan(HttpServletRequest req){
        Long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr =UUID.randomUUID().toString();
        //AccessTokenUtil.getJsApiTicket()是獲取jsapi_ticket
        String sign = getSign(AccessTokenUtil.getJsApiTicket(),nonceStr,timestamp,req.getRequestURL().toString());
        req.setAttribute("timestamp", timestamp);
        req.setAttribute("nonceStr", nonceStr);
        req.setAttribute("sign", sign);
        return "scan";
    }

    /**
     * @todo 獲取簽名 注意這裏參數名必須所有小寫,且必須有序
     * @author zhangyanan
     * @date 2018年7月31日
     */
    private String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url){
        try {
            String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="+ url;
            logger.info(shaStr);
            
            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();
        } catch (NoSuchAlgorithmException e) {
            logger.error("獲取微信簽名異常",e);
            return null;
        }
    }
}
View Code

scan.jsp微信

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>微信掃一掃</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.2.1.1.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<!-- <script type="text/javascript" src="js/weixin.js"></script> -->
</head>
<body>
<button id="scanQRCode" onclick="scanCode()">掃碼</button>
<input id="timestamp" type="hidden" value="${timestamp}" />
<input id="noncestr" type="hidden" value="${nonceStr}" />
<input id="signature" type="hidden" value="${sign}" />
</body>
<!-- JSSDK使用步驟
步驟一:綁定域名
步驟二:引入JS文件http://res.wx.qq.com/open/js/jweixin-1.2.0.js
步驟三:經過config接口注入權限驗證配置
步驟四:經過ready接口處理成功驗證
步驟五:經過error接口處理失敗驗證 -->
<script type="text/javascript">
    $(function(){
        wxConfig($("#timestamp").val(),$("#noncestr").val(),$("#signature").val());
    });
    function wxConfig(_timestamp, _nonceStr, _signature) {
        //alert('獲取數據:'+_timestamp+'\n'+_nonceStr+'\n'+_signature);
        console.log('獲取數據:' + _timestamp + '\n' + _nonceStr + '\n' + _signature);
        wx.config({
            debug : true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
            appId : "wx867cb83bc6a97559", // 必填,公衆號的惟一標識
            timestamp : _timestamp, // 必填,生成簽名的時間戳
            nonceStr : _nonceStr, // 必填,生成簽名的隨機串
            signature : _signature,// 必填,簽名,見附錄1
            jsApiList : ['scanQRCode' ]// 必填,須要使用的JS接口列表,全部JS接口列表見附錄2        
        });
        wx.ready(function(){
            // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。
            alert("config完成");
        });
        wx.error(function(res){
            // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。
            alert("config失敗");
        });
    }
    function scanCode() {
        wx.scanQRCode({
            needResult : 1,
            scanType : [ "qrCode", "barCode" ],
            success : function(res) {
                console.log(res)
                alert(JSON.stringify(res));
                var result = res.resultStr;
            },
            fail : function(res) {
                console.log(res)
                alert(JSON.stringify(res));
 
            }
        });
    }
</script>
</html>
View Code

 

 

參考文章:app

官網api:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

文章1:https://blog.csdn.net/ricky73999/article/details/78588722

文章2:https://blog.csdn.net/hfhwfw/article/details/76038923

相關文章
相關標籤/搜索