** * 获取微信参数 - 分享-扫一扫 等功能 */ @Controller @RequestMapping("/waxberry/wx") public class WechatParamController { @Autowired private CustomerService customerService; protected Logger log = LoggerFactory.getLogger(this.getClass()); //获取相关的参数,在application.properties文件中 public static final String WX_APPID_KEY = "WX_APPID"; public static final String WX_APPSECRET_KEY = "WX_APPSECRET"; public static final String ACCESSTOKEN = "access_Token"; //微信参数 private String accessToken; private String jsApiTicket; //获取参数的时刻 private Long getTiketTime = 0L; private Long getTokenTime = 0L; //参数的有效时间,单位是秒(s) private Long tokenExpireTime = 0L; private Long ticketExpireTime = 0L; //获取微信参数 @RequestMapping("/wechatParam") @ResponseBody public Map<String, String> getWechatParam(String url,String signs){ Customer customer = new Customer(); customer.setSigns(signs); Customer custo = customerService.selectOne(customer); //当前时间 long now = System.currentTimeMillis(); log.info("currentTime====>"+now+"ms"); String appId = custo.getAppId(); String appSecret =custo.getAppSecret(); //判断accessToken是否已经存在或者token是否过期 if(StringUtils.isBlank(accessToken)||(now - getTokenTime > tokenExpireTime*1000)){ JSONObject tokenInfo = getAccessToken(appId,appSecret); if(tokenInfo != null){ log.info("tokenInfo====>"+tokenInfo.toJSONString()); accessToken = tokenInfo.getString("access_token"); tokenExpireTime = tokenInfo.getLongValue("expires_in"); //获取token的时间 getTokenTime = System.currentTimeMillis(); log.info("accessToken====>"+accessToken); log.info("tokenExpireTime====>"+tokenExpireTime+"s"); log.info("getTokenTime====>"+getTokenTime+"ms"); }else{ log.info("====>tokenInfo is null~"); log.info("====>failure of getting tokenInfo,please do some check~"); } } //判断jsApiTicket是否已经存在或者是否过期 if(StringUtils.isBlank(jsApiTicket)||(now - getTiketTime > ticketExpireTime*1000)){ JSONObject ticketInfo = getJsApiTicket(accessToken); if(ticketInfo!=null){ log.info("ticketInfo====>"+ticketInfo.toJSONString()); jsApiTicket = ticketInfo.getString("ticket"); ticketExpireTime = ticketInfo.getLongValue("expires_in"); getTiketTime = System.currentTimeMillis(); log.info("jsApiTicket====>"+jsApiTicket); log.info("ticketExpireTime====>"+ticketExpireTime+"s"); log.info("getTiketTime====>"+getTiketTime+"ms"); }else{ log.info("====>ticketInfo is null~"); log.info("====>failure of getting tokenInfo,please do some check~"); } } //生成微信权限验证的参数 Map<String, String> wechatParam= makeWXTicket(jsApiTicket,url,appId); return wechatParam; } //获取accessToken private JSONObject getAccessToken(String appId, String appSecret){ String accessTokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; String requestUrl = accessTokenUrl.replace("APPID",appId).replace("APPSECRET",appSecret); log.info("getAccessToken.requestUrl====>"+requestUrl); // JSONObject result = HttpUtil.doGet(requestUrl); String str = HttpUtil.httpRequest(requestUrl,"GET",null); JSONObject result=JSONObject.parseObject(str); return result ; } //获取ticket private JSONObject getJsApiTicket(String accessToken){ String apiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; String requestUrl = apiTicketUrl.replace("ACCESS_TOKEN", accessToken); log.info("getJsApiTicket.requestUrl====>"+requestUrl); String str = HttpUtil.httpRequest(requestUrl,"GET",null); JSONObject result=JSONObject.parseObject(str); return result; } //生成微信权限验证的参数 public Map<String, String> makeWXTicket(String jsApiTicket, String url,String appId) { Map<String, String> ret = new HashMap<String, String>(); String nonceStr = createNonceStr(); String timestamp = createTimestamp(); String string1; String signature = ""; //注意这里参数名必须全部小写,且必须有序 string1 = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; log.info("String1=====>"+string1); try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); log.info("signature=====>"+signature); } catch (NoSuchAlgorithmException e) { log.error("WeChatController.makeWXTicket=====Start"); log.error(e.getMessage(),e); log.error("WeChatController.makeWXTicket=====End"); } catch (UnsupportedEncodingException e) { log.error("WeChatController.makeWXTicket=====Start"); log.error(e.getMessage(),e); log.error("WeChatController.makeWXTicket=====End"); } ret.put("url", url); ret.put("jsapi_ticket", jsApiTicket); ret.put("nonceStr", nonceStr); ret.put("timestamp", timestamp); ret.put("signature", signature); ret.put("appId", appId); System.out.println("------"+url+"------"+jsApiTicket+"------"+nonceStr+"-------"+timestamp+"-----"+signature+"-----"+appId+""); return ret; } //字节数组转换为十六进制字符串 private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } //生成随机字符串 private static String createNonceStr() { return UUID.randomUUID().toString(); } //生成时间戳 private static String createTimestamp() { return Long.toString(System.currentTimeMillis() / 1000); } }
前端 页面 js
WechatScan() 需要进页面就加载
//微信扫一扫 function WechatScan(){ var signs=$("#signs").val(); var url = window.location.href.split('#')[0].toString(); $.ajax({ type : "post", cache: false, url : "/waxberry/wx/wechatParam", data : { "url" : url, "signs":signs }, dataType : "json", success : function(data) { wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: data.appId, // 必填,公众号的唯一标识 timestamp: data.timestamp, // 必填,生成签名的时间戳 nonceStr: data.nonceStr, // 必填,生成签名的随机串 signature: data.signature,// 必填,签名,见附录1 jsApiList: [ 'checkJsApi', 'startRecord', 'stopRecord', 'translateVoice', 'scanQRCode',// 微信扫一扫接口 'openCard' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); // wx.error(function(res) { // alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。 // }); wx.ready(function() { wx.checkJsApi({ jsApiList : ['scanQRCode'], success : function(res) { } }); }); //点击按钮扫描二维码 $("#scanQRCode").click(function(){ wx.scanQRCode({ needResult : 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有 success : function(res) { var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果 console.info(result); // var serial = result.split(","); var barCode = serial[serial.length-1]; $("#couponCode").val(barCode); //$("#couponCode").val(result); }, // error : function(){ // console.log('123'); // } }); }); } }); }