微信小程序前段+java后端实现登陆功能(超详细)

先说说小程序的原理

小程序登陆时获取code,然后将code传到后台,后台通过code换取openID,openID就是用户小程序的唯一标识符(在你的小程序里是唯一的,在其他小程序可能相同),然后通过openID获取密码实现登陆,这里可能有的小伙伴会问我了,至于为什么不在小程序前段获取呢?这样不是更方便吗?因为小程序官方规定,appid,secret不应该出现在网络传输上,目的是为了防止不法人员的抓包获取,而且,在前度获取,小程序线上发布审核不会通过,好了,小面就正式开工了,一起动手做个小程序吧

需要准备的东西:

appid:在微信公告号后台获取(开发->开发设置,如下图),如果没有注册请先注册,https://mp.weixin.qq.com/

secret:在微信公告号后台获取(开发->开发设置,如下图),如果没有注册请先注册,https://mp.weixin.qq.com/

js_code:动态验证码,微信小程运行时动态获取

grant_type:固定值,固定填入authorization_code

 

微信小程序代码(主要是红色部分,可以省略直接看红色部分,这里提示一下,如果访问本机的地址,一定要勾上不校验合法域名,一定要勾上,否则不成功)

wxml文件:(没什么东西,就是绑定了一个按钮)

<!--index.wxml-->

<view class="container">

  <view class="userinfo">

    <button wx:if="{ {!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>

    <block wx:else>

      <image bindtap="bindViewTap" class="userinfo-avatar" src="{ {userInfo.avatarUrl}}" mode="cover"></image>

      <text class="userinfo-nickname">{ {userInfo.nickName}}</text>

    </block>

  </view>

  <view class="usermotto">

    <button bindtap="sign">点击签到</button>

  </view>

</view>

js文件

//index.js

//获取应用实例

const app = getApp()

 

Page({

  sign:function(){

    wx.login({

      success: function (res) {

        console.log(res.code)

       var code=res.code;

       wx.request({     

        url: 'http://127.0.0.1:8080/Sign/test.servlet',  //本地服务器地址,这里会跳转到你的后台,然后后台返回数据     

           data:{           

               code:code,    //传送js_code到你的后台,用于在后台换取openID

                     },      

              method:'GET',        

               header:{             'content-type':'application/json'         },  

                      success:function(res){       //请求成功

                             console.log(res.data);  

                            if(res.data==="yes"){  ///判断返回 标识,成功跳到下一个页面

                             wx.redirectTo({

                               url: '/pages/sucess/sucess',   成功时跳转页面

                             })

                            }

                            },  

                             fail:function(res){            console.log("失败");        } 

                               }) 

    },})  

  }

 

 

 

java后台代码

@WebServlet("/test.servlet")
public class test extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public test() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");
        /*设置响应头允许ajax跨域访问*/
        response.setHeader("Access-Control-Allow-Origin", "*");

        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        //获取微信小程序get的参数值并打印
        String code = request.getParameter("code");
        读取openid(通过发送请求,得到返回的数据)
        String params="https://api.weixin.qq.com/sns/jscode2session?appid=wxba12d9bf63797022&secret=72ba21baa0597a051243c4c25998d0b7&"
                + "js_code="+code+"&grant_type=authorization_code";//网址;

通过url类读取返回值
       URL url;String openid = null;
        try {
            url= new URL(params);
             InputStream in = url.openStream();
                BufferedReader br=new BufferedReader(new InputStreamReader(in,"utf-8"));
                byte [] b= new byte[1024];
                String line;
                截取openid
                while((line=br.readLine())!=null){
                    int star=line.indexOf("\"openid\":");
                    int end=line.indexOf("}");
                    if(star>0&&end>0){

  openid=line.substring(star+10,end-1);

/*原来的数据为

{"session_key":"值","openid":"值"}

我们只要openid的值

+10是因为要去掉"openid":,后边才是值,-1是去掉最后一个  }  */   
                    
                    }
                }
            
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }      

/**

*想要的openid已经得到了,接下来就是看你自己的了,查询数据库,得到openid对应的密码(前提是你的数据库要有openid),后台验证账号密码成功返回成功标识符,失败返回标识符,这里我只做打印

*/

System.out.println(openid);

//返回数据,这里没有数据返回所以只返回成功或失败的标识符,成功为yes,失败为No,可以自行更改

/这里我假设账号密码都对,返回yes,失败的自己可以用if语句判定,然后返回
        Writer out = response.getWriter();
        out.write("yes");
        out.flush();
      
    }

}

 

 

 

 

OK,完成,睡觉,头发又少了,怕了怕了

 

2020/4/15 4:40 修改完成

Guess you like

Origin blog.csdn.net/weixin_44710155/article/details/103796780