微信扫码实现跳转

微信扫码实现跳转上一章介绍了通过分享好友实现微信跳转,这一章将介绍通过扫码实现微信跳转。该页面可以通过扫码进行跳转,或者复制链接在微信中打开实现跳转。

大家好,欢迎来到IT知识分享网。

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

前提:从微信公众号那边获取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 style="width: 1px;height: 1px;" 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..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..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();
    }
}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/53104.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信