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 + "&timestamp=" + 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秒后自动关闭
					});
 
				}
			});
		}

其实就是这么的简单

扫描二维码关注公众号,回复: 3272499 查看本文章

这里需要提醒大家 页面一定要引入 不然会调用不了微信的函数

如有需要可以加我Q群【308742428】大家一起讨论技术。

后面会不定时为大家更新文章,敬请期待。

喜欢的朋友可以关注下。   

猜你喜欢

转载自www.cnblogs.com/dsn727455218/p/9687636.html