zoukankan      html  css  js  c++  java
  • java调用微信扫一扫

    步骤:

    1,获取Accesstoken(参考我之前的文章

    2,获取jsapiticket(参考我之前的文章

    3,获取签名

    4JSSDK使用步骤

      步骤一:绑定域名(JS接口安全域名),。否则会报invalid url domain
      步骤二:引入JS文件http://res.wx.qq.com/open/js/jweixin-1.2.0.js
      步骤三:通过config接口注入权限验证配置
      步骤四:通过ready接口处理成功验证
      步骤五:通过error接口处理失败验证

    5.调用扫一扫接口

    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+'
    '+_nonceStr+'
    '+_signature);
            console.log('获取数据:' + _timestamp + '
    ' + _nonceStr + '
    ' + _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

    参考文章:

    官网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

  • 相关阅读:
    js 仿 asp中的 asc 和 chr 函数的代码
    escape,encodeURI,encodeURIComponent
    从项目从SVN上check下来,用idea打开后,idea没有SVN的工具栏解决方法
    idea中导入SVN的项目时,连接失败,报“Cannot run program "svn"
    spring基础----事件(Applicaition Event)
    idea在导入项目时遇到的问题
    Spring基础---bean的初始化和销毁
    spring基础----EL和资源调用
    spring基础----Bean的Scope
    面试题-------------js三种信息框
  • 原文地址:https://www.cnblogs.com/yanan7890/p/9396635.html
Copyright © 2011-2022 走看看