[微信开发] – 微信开放平台的扫码登录

[微信开发] – 微信开放平台的扫码登录首先开通微信开放平台,申请网站应用,交钱通过后可以使用appid和appsecret(和公众平台的不同)之后可以生成扫码登录的二维码了,主要根据开放平台提供的api请求链接和appid,appsecret<%–测试首页–%><%@pagecontentType=”text/html;charset=UTF-8″language=”java”%&…

大家好,又见面了,我是你们的朋友全栈君。

首先开通微信开放平台,申请网站应用,交钱通过后可以使用appid和appsecret(和公众平台的不同)

之后可以生成扫码登录的二维码了,主要根据开放平台提供的api请求链接和appid,appsecret

<%--
测试首页
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>BBBGGG</title>
</head>
<body>
BBBGGG index
<a href="login">登录集</a>

${snsUser.nickname}
</body>
</html>

下面页面展示3种登录示例:

<%--
  Created by IntelliJ IDEA.
  User: SeeClanUkyo
  Date: 2018/12/10
  Time: 8:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>

    <!--BootStrap的样式文件-->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">

    <!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
    <script src="https://code.jquery.com/jquery.js"></script>

    <!-- Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


    <script src="http://www.jq22.com/jquery/jquery-3.3.1.js"></script>
    <!--微信登录二维码插件js-->
    <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
</head>
<body>


<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
该页面的目的不限于微信登录,还应该包含其它方式登录.

            snsUser
            昵称:${snsUser.nickname}
            <br>

            三种登录方式<br>
            <div class="center-block">
            <button class="btn" id="btn1">用微信登录 全屏二维码</button>
            <button id="modal-742328" href="#modal-container-742328" role="button" class="btn" data-toggle="modal">微信登录iframe</button>
            <a class="btn" href="/qrcode">登录/qrcode</a>
            </div>
            <hr>
            之下为测试
            <p>获取code</p>
            <button id="btn2">获取code</button>
            token:<p id="token"></p>
            openid:<p id="openid"></p>
            <p>获取用户信息</p>
            <button id="btn3">获取用户信息</button>
            <P>姓名:</P>
            <p id="name"></p>
            <p>头像:</p><img src="" id="img">

            <button id="btn4">直接从code获取用户信息</button>
            <p id="nickname"></p>


            <!--<div id="login_container"></div>-->



            <div class="modal fade" id="modal-container-742328" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h4 class="modal-title" id="myModalLabel">
                               微信扫码登录
                            </h4>
                        </div>
                        <div class="modal-body" style="width:500px;height:500px">
                         <!--<div id="login_container" style="width:400px;height:400px"></div>-->
                            <iframe class="center" src="qrcode.jsp" style="width:400px;height:400px"></iframe>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>





login.jsp

<%--<% String code = request.getParameter("code");%>--%>
<%--<%= code %>--%>
<%--<% Weixin weixin = new Weixin();%>--%>

<%--<% SnsUser snsUser = weixin.sns().getSnsUserByCode(code);%>--%>
<%--<%=snsUser.getNickname()%>--%>

<!-- <button id="btn">btn</button> -->
<!-- 通过ajax获取的用户信息封装在data中,可以根据需要获取不同的参数,如 -->





<script>

    //not use
    // $("#btn").click(getSnsUser);
    function getSnsUser() {
        //     alert("getSnsUser begin")
        $.ajax({
            url: "/user/getSnsUserInfoByCode",
            data: "<%=request.getParameter("code")%>",
            contentType: "application/json",
            dataType: "json",
            method: "POST",
            success: function (data) {
                alert(JSON.stringify(data));
                //将数据反填到html或jsp页面上
            }
        });
    }


    //not use
    function getOpenSnsUser() {
        //     alert("getSnsUser begin")
        $.ajax({
            url: "/user/getOpenSnsUserInfoByCode",
            data: "<%=request.getParameter("code")%>",
            contentType: "application/json",
            dataType: "json",
            method: "POST",
            success: function (data) {
                window.location.href=window.location.host;
                alert(JSON.stringify(data));
                //将数据反填到html或jsp页面上
            }
        });
    }




</script>


<script>

    // var obj = new WxLogin({
    
    
    //     self_redirect: true,
    //     id: "login_container",
    //     appid: APPID,
    //     scope: "",
    //     redirect_uri: "",
    //     state: "",
    //     style: "",
    //     href: ""
    // });

</script>


<script>
    //开放平台参数
    //开放平台appid
    var APPID = "wxxxxxxxxxxxxxxxxx";
    //开放平台请求作用域
    var SCOPE = "snsapi_login";
    //回调页面 URL 进行utf cncode
    var REDIRECT_URI = encodeURIComponent("http://baige.free.idcfengye.com/callback");
    //开放平台appsecret

    //
    var STATE = "state";


    // 快捷方式
    // var obj = new WxLogin({
    
    
    //     self_redirect: true,
    //     id: "login_container",
    //     appid: APPID,
    //     scope: SCOPE,
    //     redirect_uri: REDIRECT_URI,
    //     state: STATE,
    //     style: "",
    //     href: ""
    // });






    //第一步,获取code
    //用微信登录按钮
    var btn1 = $("#btn1");




    //微信登录
    btn1.click(getOpenCode);


    function getOpenCode() {
        alert("getOpenCode");
        window.open("https://open.weixin.qq.com/connect/qrconnect?appid=" + APPID + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=" + SCOPE + "&state=STATE#wechat_redirect");
    }

    //第二步,获取access_token
    var btn2 = $("#btn2");

    var btn4 = $("#btn4");


    btn4.click(getUserInfoByCode);
    function getUserInfoByCode(){
            alert("getUserInfoByCode begin");
            $.ajax({
                url: "/user/getOpenSnsUserInfoByCode",
                // url: "/callBackLogin",
                data: "<%=request.getParameter("code")%>",
                contentType: "application/json",
                dataType: "json",
                method: "POST",
                success: function (data) {
                    alert(JSON.stringify(data));
                    var nickname = data.SnsUser.nickname;
                    $("#nickname").html(nickname);
                    alert(data.SnsUser.nickname);
                    //将数据反填到html或jsp页面上
                }
            });

    }

    btn2.click(getAccessToken);

    function getAccessToken() {
        var CODE = "<%=request.getParameter("code")%>";
        var tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + CODE + "&grant_type=authorization_code";
        $.ajax({
            url: tokenUrl,
            type: "POST",
            data:{
    
    "":1},
            dataType: "json",
            success: function (data) {
                alert(JSON.stringify(data));
                var token = data.access_token;
                var openid = data.openid;
                $("#token").html(token);
                $("#openid").html(openid);
            }

        })
    }

    //第三步,获取用户信息
    var btn3 = $("#btn3");
    btn3.click(getUserInfo);

    function getUserInfo() {
        var token3 = $("#token").html();
        var openid3 = $("#openid").html();
        var ajaxUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token3 + "&openid=" + openid3;
        $.ajax({
            url: ajaxUrl,
            type: "get",
            dataType: "JSONP",
            success: function (data) {
                alert(JSON.stringify(data));
                var name = $("#name");
                var img = $("#img");
                $(name).html(data.nickname);
                $(img).attr("src", data.headimgurl);
            }
        })
    }


</script>

</body>
</html>

 

调用的callback页面,同时也是回调页面:

<%--
  回调页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>callback</title>
    <script src="http://www.jq22.com/jquery/jquery-3.3.1.js"></script>
</head>
<body>

正在跳转...

<script>
    $.ajax({
        // url: "/user/getOpenSnsUserInfoByCode",
        url: "/user/callBackLogin",
        data: "<%=request.getParameter("code")%>",
        contentType: "application/json",
        dataType: "json",
        method: "POST",
        success: function (data) {


            if(data===1){
                window.location.href="http://baige.free.idcfengye.com";
            }else{
                window.location.href="http://baige.free.idcfengye.com/error";
            }

        }
    });
</script>

</body>
</html>

之下的控制层方法:

package com.baigehuidi.demo.controller;

import com.baigehuidi.demo.loader.WeixinInsLoader;
import com.baigehuidi.demo.weixin4j.WeixinException;
import com.baigehuidi.demo.weixin4j.model.sns.SnsUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class WeixinUserInfoController {

    @RequestMapping("/getSnsUserInfoByCode")
    public Map getSnsUserInfoByCode(@RequestBody String code) throws WeixinException {
        if(code==null || code==""){
            return null;
        }
        Map map = new HashMap();
        System.out.println("code:"+code);
        SnsUser snsUser = WeixinInsLoader.getWeixinInstance().sns().getSnsUserByCode(code);
        map.put("SnsUser",snsUser);
        return map;
    }

    @RequestMapping("/getOpenSnsUserInfoByCode")
    public Map getOpenSnsUserInfoByCode(@RequestBody String code) throws WeixinException {
        if(code==null || code==""){
            return null;
        }
        Map map = new HashMap();
        System.out.println("code:"+code);
        SnsUser snsUser = WeixinInsLoader.getWeixinInstance().open().getOpenSnsUserByCode(code);
        map.put("SnsUser",snsUser);
        return map;
    }

    //微信扫码登录回调
    @RequestMapping("/callBackLogin")
    public Integer callBackLogin(@RequestBody String code, HttpSession session) throws WeixinException, ServletException, IOException {
        System.out.println("callback method");
        System.out.println("code:"+code);
        SnsUser snsUser = WeixinInsLoader.getWeixinInstance().open().getOpenSnsUserByCode(code);
        System.out.println("snsUser:"+snsUser);
        session.setAttribute("snsUser",snsUser);
        if(session!=null){
            return 1;
        }else{
            return 0;
        }

    }

}

最终效果: (因为用的内网穿透不太稳定,响应稍慢)

[微信开发] - 微信开放平台的扫码登录

转载于:https://www.cnblogs.com/ukzq/p/10111363.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/133353.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 列举数据挖掘领域的十大挑战问题

    列举数据挖掘领域的十大挑战问题

    2021年8月23日
    77
  • 网吧服务器发消息,网吧盗号常见途径总结以及解决办法

    网吧服务器发消息,网吧盗号常见途径总结以及解决办法近期有部分网吧反馈,网吧随机出现盗号问题,主要反馈现像是:QQ提示账号异常登录和乱发消息等、CF/wegame/吃鸡账号被盗等目前发现盗号问题主要有以下几种途径:一.网吧本地内部环境中毒引起的盗号问题1.服务器中毒处理方法:服务器安装火绒,查杀下C盘和内存,查完杀完毒后把火绒卸载掉以免识杀游戏文件2.服务器被入侵,加入了开机启动项带第三方增值引起处理方法:将启动项先关掉,一项一项加上去测试,直到…

    2022年7月26日
    24
  • jpeg图像压缩算法流程详解_图像压缩最快算法

    jpeg图像压缩算法流程详解_图像压缩最快算法JPEG是Joint Photographic Exports Group的英文缩写,中文称之为联合图像专家小组。该小组隶属于ISO国际标准化组织,主要负责定制静态数字图像的编码方法,即所谓的JPEG算法。JPEG专家组开发了两种基本的压缩算法、两种熵编码方法、四种编码模式。如下所示:压缩算法:(1)有损的离散余弦变换DCT(Discrete Cosine Transform)(2)无

    2025年7月6日
    2
  • 解压war包工具_rar解压下载

    解压war包工具_rar解压下载解压war,要用jar命令jar-xfdemo.war

    2022年10月5日
    3
  • webstorm激活码2021年-激活码分享

    (webstorm激活码2021年)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.htmlMLZPB5EL5Q-eyJsaWN…

    2022年3月20日
    138
  • C# 串口通信 stm32 电机

    C# 串口通信 stm32 电机前几天已经完成了stm32通过PWM对电机的控制,这几天趁上班之余,也完成了c#通过串口通信控制电机的运行。界面如下好久没写文章了,发现非常不擅长分享和表达,第一反应是演示出来,可惜这里不能有动画,功能不强大啊。哪天有空了,把上位机代码和下位机代码上传上来。代码已经上传,请查看我的资源页。…

    2022年6月3日
    33

发表回复

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

关注全栈程序员社区公众号