二维码扫描在线识别方法

上一章介绍了通过分享好友实现微信跳转,这一章将介绍通过扫码实现微信跳转。

前提:从微信公众号那边获取appid,secret,grantType三个参数备用。

1、获取微信跳转链接接口

该接口主要是获取能重定向到扫码后页面的接口链接。

@GET@Path(value = "getData")@Produces(MediaType.APPLICATION_JSON)public Response getData() { Map<String, String> result = new HashMap<>(); try { //......业务代码...... String recUrl = "https://XXXX.com/项目名/oauth";//实现重定向的连接,该接口实现看第3节讲 result.put("url", recUrl); return Response.ok(result).build(); } catch (Exception e) { result.put("code", 0); result.put("msg", "异常"); return Response.ok(result).build(); } }

2、二维码页面

该页面可以通过扫码进行跳转,或者复制链接在微信中打开实现跳转。

<input id="url" value="" type="text" /><div id="root"> <div id="pic"> <div id="Code"></div> </div> <div id="txt">扫码跳转或者识别图片跳转</div> <div id="copyLink"> 复制链接(微信中点击链接可直接跳转) </div></div>function convertCanvasToImage() { var image = new Image(); var canvas = document.getElementsByTagName('canvas')[0]; image.src = canvas.toDataURL("image/png"); return image;}$(function() { //可以直接复制链接在微信中,然后点击链接可跳转到与扫码的同一个界面 var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + linkUrl; //linkUrl是后台getData方法的url +"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"; $("#url").val( url); $("#pic").qrcode({ render: "canvas", //table方式 width: 170, //宽度 height: 170, //高度 text: url //任意内容 }); var img = convertCanvasToImage(); $("canvas").remove(); $('#Code').append(img); $("#copyLink").click(function() { var copyText = $("#url"); copyText.select();//选择 document.execCommand("Copy");//执行复制 alert("复制成功!"); })});

微信自动调用oauth2/authorize接口,运行完接口后得到一次性的code,会自动重定向到redirect_uri?code=XXX&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect

3、跳转的oauth接口

该接口可通过一次性的code获取用户的openId,然后重定向到扫码后的页面。(微信会两次回调这个接口,第一次的code是有值的,第二次code为空!)

@GET@Path(value = "oauth")public void oauth(@Context HttpServletResponse httpResponse, @QueryParam("code") String code) { String indexUrl = "https://XXXX.com/项目名/ProduceDeatil.html"; //微信扫码跳转的页面 String wxUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=%s"; wxUrl = String.format(wxUrl, appId, secret, code, grantType); String response = HttpUtil.sendGet(wxUrl); if (response == null) { logger.error("微信access_token接收失败"); return; } JSONObject jsonObject = JSONObject.parseObject(response); String openid = (String) jsonObject.get("openid"); try { httpResponse.sendRedirect(indexUrl + "?openid=" + openid); } catch (IOException e) { e.printStackTrace(); }}

  • 91 views
    A+
发布日期:2021年09月08日 11:00:00  所属分类:知识经验
标签: