微信小程序開發〖二〗開發登錄頁面,判斷授權,校驗登錄態 前端與後臺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;
    }
}

其實看看代碼大家就都懂了~學習嘛,樂在其中,再過兩天寫幾篇面經,美團爸爸撈我啊!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章