经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 其他 » 职业生涯 » 查看文章
JAVA实现调用微信js-sdk扫一扫
来源:cnblogs  作者:dsn727455218  时间:2018/9/25 19:25:54  对本文有异议

喜欢的朋友可以关注下。

已经很久没有给大家分享一片技术文章了,今天抽了点时间来,给大家说一说如何调用微信提供的扫一扫接口。

前提: 需要申请一个公众号:申请公众号需要的资料我就不说了,去申请微信会提示需要哪些。

准备appid(公众号的id) AppSecret (公众号的密钥) 正文: 首先,我们先来简单了解一下流程,详细的微信文档有说明。

获取Token→根据token获取Ticket→根据ticket签名→反会参数给前端→前端调起扫一扫接口 下面直接上代码

1.获取token 

  1. /**
  2. * Description: 获取微信公众号token<BR>
  3. *
  4. * @author dsn
  5. * @date 2018年9月21日 上午9:53:26
  6. * @param appid
  7. * @param secret
  8. * @return
  9. * @version 1.0
  10. */
  11. public static String getAccessToken(String appid, String secret) {
  12. String token = "";
  13. String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
  14. + "&secret=" + secret;
  15. JSONObject result = PayCommonUtil.httpsRequest(token_url, "POST");
  16. if (result.get("access_token") != null) {
  17. token = result.get("access_token").toString();
  18. }
  19. return token;
  20. }

2.获取ticket 

  1. /**
  2. * Description: 获取微信ticket<BR>
  3. *
  4. * @author dsn
  5. * @date 2018年9月21日 上午9:54:03
  6. * @param token
  7. * @return
  8. * @version 1.0
  9. */
  10. public static String getTicket(String token) {
  11. if ("".equalsIgnoreCase(token) || null == token) {
  12. return "";
  13. }
  14. String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
  15. JSONObject result = PayCommonUtil.httpsRequest(ticket_url, "POST");
  16. return result.get("ticket").toString();
  17. }

3.签名

  1. public static String getSign(String jsapi_ticket, String noncestr, Long timestamp, String url)
  2. throws NoSuchAlgorithmException {
  3. String shaStr = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
  4. + url;
  5. MessageDigest mDigest = MessageDigest.getInstance("SHA1");
  6. byte[] result = mDigest.digest(shaStr.getBytes());
  7. StringBuffer signature = new StringBuffer();
  8. for (int i = 0; i < result.length; i++) {
  9. signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
  10. }
  11. return signature.toString();
  12. }

4.action中调用

  1. /**
  2. * Description:微信扫一扫接口 <BR>
  3. *
  4. * @author ran.chunlin
  5. * @date 2017年4月11日 上午10:07:35
  6. * @param request
  7. * @return
  8. * @throws Exception
  9. * @version 1.0
  10. */
  11. @RequestMapping(params = "method=getWechatSign", method = RequestMethod.GET)
  12. public @ResponseBody Map<String, Object> getWechatSign(HttpServletRequest request) throws Exception {
  13. /* 返回的json数据 */
  14. Map<String, Object> jsonMap = new HashMap<>();
  15. // 构成子数据map
  16. Map<String, Object> subJsonMap = new HashMap<>();
  17. // 1.获取参数
  18. String url = showNull(request.getParameter("url"));
  19. String t = showNull(request.getParameter("t"));
  20. String appId = showNull(request.getParameter("appId"));
  21. String appSecret = showNull(request.getParameter("appSecret"));
  22. if (url == null || t == null || appId == null || appSecret == null) {
  23. return json4Map(jsonMap, subJsonMap, "参数为空", STATUSCODE_FAILED_BADINPUT_PARAM);
  24. } else {
  25. String accessToken = WeiXinUtils.getAccessToken(appId, appSecret);
  26. String ticket = WeiXinUtils.getTicket(accessToken);
  27. Long timestamp = System.currentTimeMillis() / 1000;
  28. String nonceStr = RandomStringUtils.randomAlphanumeric(16);
  29. String sign = getSign(ticket, nonceStr, timestamp, url);
  30. subJsonMap.put("result", "1");
  31. subJsonMap.put("timestamp", timestamp);
  32. subJsonMap.put("nonceStr", nonceStr);
  33. subJsonMap.put("appId", appId);
  34. subJsonMap.put("sign", sign);
  35. }
  36. return json4Map(jsonMap, subJsonMap, "获取sign成功", STATUSCODE_SUCCESS);
  37. }

5.前端代码

  1. // 扫一扫 进入页面时去调用
  2. $.ajax({
  3. type : 'GET',
  4. url : "你action的url",
  5. data : {
  6. appId : "",
  7. appSecret : "",
  8. url : location.href,
  9. t : Math.random()
  10. },
  11. success : function(json) {
  12. if (json.data.result == "1") {
  13. wxConfig(json.data.timestamp, json.data.nonceStr,
  14. json.data.sign, json.data.appId);
  15. }
  16. }
  17. });
  18.  
  19. function wxConfig(_timestamp, _nonceStr, _signature, _appId) {
  20. wx.config({
  21. // debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  22. appId : _appId, // 必填,公众号的唯一标识
  23. timestamp : _timestamp, // 必填,生成签名的时间戳
  24. nonceStr : _nonceStr, // 必填,生成签名的随机串
  25. signature : _signature,// 必填,签名,见附录1
  26. jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage',
  27. 'onMenuShareQQ', 'onMenuShareWeibo', 'scanQRCode' ]
  28. // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  29. });
  30. }
  31. //扫码调用
  32. function scanCode() {
  33. wx.scanQRCode({
  34. needResult : 1,
  35. scanType : [ "qrCode", "barCode" ],
  36. success : function(res) {
  37. console.log(res)
  38. //扫描返回的数据
  39. var result = res.resultStr;
  40. },
  41. fail : function(res) {
  42. layer.open({
  43. content : '请稍后再试',
  44. skin : 'msg',
  45. time : 2
  46. //2秒后自动关闭
  47. });
  48. }
  49. });
  50. }

其实就是这么的简单

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

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

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

喜欢的朋友可以关注下。   

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号