微信公众号调用微信扫一扫功能实现

1、前端页面:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>扫一扫测试</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../static/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../static/layuiadmin/style/admin.css" media="all">    
    <link rel="stylesheet" href="../static/layuiadmin/style/mystyle.css" media="all">
</head>
<body>
    
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button type="button" class="layui-btn layui-btn-normal" id="scanTest">扫一扫</button>
    </div>
  </div>

<script type="text/javascript" src="../static/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="../static/jquery/plugin/jquery.cookie.js"></script>
<script type="text/javascript" src="../static/other/md5.js"></script>
<script type="text/javascript" src="../static/layuiadmin/layui/layui.js"></script>
<script type="text/javascript" src="../static/jbdp.js"></script>

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

<script type="text/javascript">


layui.use(['jquery', 'layer', 'form', 'myext'], function(){
    var form = layui.form
    , layer = layui.layer
    , $ = layui.jquery;
     
    //实始化wx    
    $.ajax({
        type:'GET',
        url:$sysroot+'jfwx/userpage/goJsPage',
        data:{"url":window.location.href},
        success: function(data){
            wx.config({
                debug: false,
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr:  data.noncestr,
                signature: data.signature,
                jsApiList: ['scanQRCode',]
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("异常信息:" + XMLHttpRequest.responseText);
        }
    });
    
    //扫一扫按钮事件
    $("#scanTest").click(function () {
    	    wx.scanQRCode({
            needResult: 1,
            scanType: [ "qrCode", "barCode" ], 
            desc: 'scanQRCode desc',
            success: function (res) {
	            	if(res){
	            		layer.msg("二维码内容:" + res.resultStr);
	            	}
            },error:function(res){
                layer.msg(res)
            }
        });
    });
	
});
</script>

</body>
</html>



如上面页面所示:
1、引入
2、实始化wx
3、在扫一扫按钮事件中调用wx.scanQRCode

二、实始化wx的请求“url:$sysroot+‘jfwx/userpage/goJsPage’,”方法后台

WeixinConfig.java

package net.sxjr.weixin;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.kit.PropKit;
import com.jfinal.template.Engine;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.WxaConfigKit;

public class WeixinConfig extends JFinalConfig {
    public void configConstant(Constants me) {
        PropKit.use("weixin_config.txt");
        me.setDevMode(PropKit.getBoolean("devMode", false));

        // ApiConfigKit 设为开发模式可以在开发阶段输出请求交互的 xml 与 json 数据
        ApiConfigKit.setDevMode(me.getDevMode());
        // 默认使用的jackson,下面示例是切换到fastJson
//      me.setJsonFactory(new FastJsonFactory());
    }

    public void configRoute(Routes me) {
                // jfinal 3.6 开始,如果有继承 MsgController 的类,则需要开启下面的配置,将超类中的 index() 映射为 action
                me.setMappingSuperClass(true);

        //me.add("/msg", WeixinMsgController.class);
        me.add("/jfwx/api", WeixinApiController.class, "/api");
        me.add("/jfwx/userpage", UserPageController.class);
    }

    public void configPlugin(Plugins me) {
        // 1.5 之后支持redis存储access_token、js_ticket,需要先启动RedisPlugin
        // RedisPlugin redisPlugin = new RedisPlugin("weixin", "127.0.0.1");
        // me.add(redisPlugin);
    }   

    public void afterJFinalStart() {
        // 1.5 之后支持redis存储access_token、js_ticket,需要先启动RedisPlugin
//        ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache());
        // 1.6新增的2种初始化
//        ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache(Redis.use("weixin")));
//        ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache("weixin"));

        ApiConfig ac = new ApiConfig();
        // 配置微信 API 相关参数
        ac.setToken(PropKit.get("token"));
        ac.setAppId(PropKit.get("appId"));
        ac.setAppSecret(PropKit.get("appSecret"));

        /**
         *  是否对消息进行加密,对应于微信平台的消息加解密方式:
         *  1:true进行加密且必须配置 encodingAesKey
         *  2:false采用明文模式,同时也支持混合模式
         */
        ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));

        /**
         * 多个公众号时,重复调用ApiConfigKit.putApiConfig(ac)依次添加即可,第一个添加的是默认。
         */
        ApiConfigKit.putApiConfig(ac);
        
        /**
         * 1.9 新增LocalTestTokenCache用于本地和线上同时使用一套appId时避免本地将线上AccessToken冲掉
         * 
         * 设计初衷:https://www.oschina.net/question/2702126_2237352
         * 
         * 注意:
         * 1. 上线时应保证此处isLocalDev为false,或者注释掉该不分代码!
         * 
         * 2. 为了安全起见,此处可以自己添加密钥之类的参数,例如:
         * http://localhost/weixin/api/getToken?secret=xxxx
         * 然后在WeixinApiController#getToken()方法中判断secret
         * 
         * @see WeixinApiController#getToken()
         */
//        if (isLocalDev) {
//            String onLineTokenUrl = "http://localhost/weixin/api/getToken";
//            ApiConfigKit.setAccessTokenCache(new LocalTestTokenCache(onLineTokenUrl));
//        }
        WxaConfig wc = new WxaConfig();
        wc.setAppId(PropKit.get("appId"));
        wc.setAppSecret(PropKit.get("appSecret"));
        WxaConfigKit.setWxaConfig(wc);
        
        AccessToken aa = AccessTokenApi.getAccessToken();
        System.out.println(aa.getAccessToken());
        String url = SnsAccessTokenApi.getAuthorizeURL(PropKit.get("appId"), "http://192.168.1.21/scanDemo", true);
        System.out.println();
    }

    public void configInterceptor(Interceptors me) {}
    public void configHandler(Handlers me) {}
    public void configEngine(Engine engine) {}
}

UserPageController.java

package net.sxjr.weixin;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

public class UserPageController extends Controller{
    
    public void goJsPage() {
        String url = this.get("url");
        // 1.拼接url(当前网页的URL,不包含#及其后面部分)
        Map<String, String> _wxMap = new TreeMap<String, String>();
        String _wxShareUrl = this.getRequest().getHeader("Referer");
        if (StringUtils.isNotBlank(_wxShareUrl)) {
            _wxShareUrl = _wxShareUrl.split("#")[0];
        } else if(StringUtils.isNotBlank(url)){
            _wxShareUrl = url.split("#")[0];
        }else{            
            renderJson(_wxMap);
            return;
        }

        String appId = PropKit.get("appId");
        String appSecret = PropKit.get("appSecret");
        ApiConfig ac = new ApiConfig();
        ac.setAppId(appId);
        ac.setAppSecret(appSecret);

        ApiConfigKit.setThreadLocalAppId(appId);
        String _wxJsapiTicket = "";
        try {
            JsTicket jsTicket = JsTicketApi.getTicket(JsApiType.jsapi);
            _wxJsapiTicket = jsTicket.getTicket();
        } finally {
            ApiConfigKit.removeThreadLocalAppId();
        }

        // noncestr
        String _wxNoncestr = UUID.randomUUID().toString().replace("-", "");
        // timestamp
        String _wxTimestamp = (System.currentTimeMillis() / 1000) + "";

        // 参数封装
        _wxMap.put("noncestr", _wxNoncestr);
        _wxMap.put("timestamp", _wxTimestamp);
        _wxMap.put("jsapi_ticket", _wxJsapiTicket);
        _wxMap.put("url", _wxShareUrl);

        // 加密获取signature
        StringBuilder _wxBaseString = new StringBuilder();
        for (Entry<String, String> param : _wxMap.entrySet()) {
            _wxBaseString.append(param.getKey()).append("=")
                    .append(param.getValue()).append("&");
        }
        String _wxSignString = _wxBaseString.substring(0,
                _wxBaseString.length() - 1);
        // signature
        String _wxSignature = HashKit.sha1(_wxSignString);
        _wxMap.put("appId", appId);
        _wxMap.put("signature", _wxSignature);

        renderJson(_wxMap);
        return ;
    }
}

3、补充说明一下,工程需要导入jfinal jar包

<dependency>
   <groupId>com.jfinal</groupId>
   <artifactId>jfinal</artifactId>
   <version>4.8</version>
</dependency>
   <dependency>
   <groupId>com.jfinal</groupId>
   <artifactId>jfinal-weixin</artifactId>
   <version>2.4</version>
</dependency>

你可能感兴趣的:(微信开放平台开发)