微信小程序开发〖二〗开发登录页面,判断授权,校验登录态 前端与后台springboot代码

一. 微信小程序登录展示(Gif图)

在这里插入图片描述

二. 微信小程序端

这里只展示一下js的逻辑,页面代码你们想看的话,等我把这个小程序做出来放源码

checksession -> userAuthorized -> onGetUserInfo ->( wx.login -> wx.request)

// pages/user/user.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    condition: true,//true为未登录,false为已登录;true就展示登录按钮
    userInfo:'' //用户信息
  },


  /**
   * 校验是否授权登录
   */
  userAuthorized() {
    const that = this
    wx.getSetting({
      success: data => {
        if (data.authSetting['scope.userInfo']) { //如果授权登录过了
          var userInfoStorage=wx.getStorageSync("userInfo") //那我直接去缓存中拿到userInfo的值
          this.setData({ //再实时的更新进去
            userInfo: userInfoStorage, 
            condition: false //控制页面条件绑定条件渲染 false就不展示登录按钮
          })
        } else {
          this.setData({
            condition: true  //控制页面条件绑定条件渲染 true  就展示登录按钮
          })
        }
      }
    })
  },

  /**
   * 校验登录态
   */
  //验证登录是否过期
  checksession: function () {
    var that=this
    wx.checkSession({
      success: res =>  {
        console.log(res, '登录未过期')
        this.userAuthorized();  //如果没过期去调用 校验是否授权登录
      },
      fail: res => {
        console.log(res, '登录过期了')
        this.setData({ condition:true }) //若过期了 就展示登录按钮
      }
    })
  },

  /**
   * 登录验证代码
   * 
   * <button type="small" class="bg-black" open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGetUserInfo">一键登录</button> 页面用一个按钮来启动登录
   */
  onGetUserInfo(event) { //登录启动!
    console.log(event)
    const userInfo = event.detail.userInfo  //获取用户基本信息(不包括openid)
    if (userInfo) {  //如果获取的用户信息不为空,那就进行下一步
      const that = this; //处理闭包函数
      wx.login({
        success: function (login_res) { //用户进行授权登录了
          wx.getUserInfo({  
            success: (res) => { 
              wx.request({ //去请求后台
                url: app.globalData.myserver_prefix + '/user/wxLogin',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  code: login_res.code, //拿到登录授权的code去后台换取openid
                  userHead: userInfo.avatarUrl,//去后台更新用户数据,下同
                  userName: userInfo.nickName,
                  // gender: userInfo.gender
                },
                success: (res) => {
                  console.log(res.data)
                  if(res.data.status=="success"){ //从后台的返回的成功的话
                    var userdata = res.data;
                    // 将返回的数据保存到全局的缓存中,方便其他页面使用
                    wx.setStorage({ key: 'userInfo', data: userdata.data })
                    app.globalData.userInfo = userdata.data //放到全局data里
                    that.setData({
                      userInfo: userdata.data, //返回的用户数据动态更新
                      condition: false 
                    })
                  }else{
                    console.log(res.data,"错误") 
                    that.setData({
                      condition: true //后台返回错误那我就重新把登录按钮调出来
                    })
                  }
                }
              })
            }
          })
        }
      })
    } else { //要是不给授权就会提醒用户
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功,不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    this.checksession() //我们在页面被加载的时候就调用判断是否授权过期
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

基本逻辑都写在注释里面了,开箱即用,毕竟我主业是后台啊~ 不可能写的很好啊~~55

三. Springboot后台

基本都是Controller层的代码,获取到openid绑定到用户,注释看看大家都会写的~

@PostMapping("/wxLogin")
    public CommonReturnType createUser(
            String code,String userHead,String userName,Integer gender
    ){
        //这一系列操作是去wx官方换取openid
        System.out.println("wx-code: "+code);
        String url="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> param=new HashMap<>();
        param.put("appid","你自己的appid");
        param.put("secret","你自己的secret");
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String wxResult= HttpClientUtil.doGet(url,param); //这里使用了HttpClientUtil工具类发送Http请求
        JSONObject jsonObject = JSON.parseObject(wxResult); //返回的Json字符串,我们使用阿里的FastJson转化
        //获取到的openid与sessionKey
        System.out.println(jsonObject);
        //从wx获得用户唯一标识
        String openid = jsonObject.getString("openid");
        //初始化一个User
        User user=new User();
        user.setUserAvatar(userHead);
        user.setUserGender(gender);
        user.setUserName(userName);
        user.setUserOpenid(openid);
        //去数据库查一下存在这个对象不
        final User findUser = userService.selectUser(user.getUserOpenid());
        if(findUser==null){
            //若数据库没存在这个对象,则插入
            //将用户注册进数据库
            final Integer isTrueInsert = userService.userLogin(user);
            System.out.println("数据库插入情况:"+isTrueInsert);
            User RtUser=userService.selectUser(user.getUserOpenid());//返回一个最新的用户数据,带自增Id
            return CommonReturnType.creat(RtUser);
        }else {
            //若对象存在,则更新
            final Integer rowByFluenced = userService.updateUser(user);
            System.out.println("数据库更新了"+rowByFluenced+"行");
            User RtUser=userService.selectUser(user.getUserOpenid());//返回一个最新的用户数据,带自增Id
            return CommonReturnType.creat(RtUser); //这里返回了通用模板
        }
    }
}

附赠HttpClient工具包

package com.fehead.community.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpClientUtil {


    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}

其实看看代码大家就都懂了~学习嘛,乐在其中,再过两天写几篇面经,美团爸爸捞我啊!!!

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值