欧美三级国产三级日韩三级_亚洲熟妇丰满大屁股熟妇_欧美亚洲成人一区二区三区_国产精品久久久久久模特

SpringBoot實現(xiàn)微信小程序登錄功能 - 新聞資訊 - 云南小程序開發(fā)|云南軟件開發(fā)|云南網(wǎng)站建設(shè)-昆明葵宇信息科技有限公司

159-8711-8523

云南網(wǎng)建設(shè)/小程序開發(fā)/軟件開發(fā)

知識

不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側(cè)重于功能的便捷,營銷的便利,運營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!

您當(dāng)前位置>首頁 » 新聞資訊 » 小程序相關(guān) >

SpringBoot實現(xiàn)微信小程序登錄功能

發(fā)表時間:2020-10-19

發(fā)布人:葵宇科技

瀏覽次數(shù):68

SpringBoot實現(xiàn)微信小程序登錄

  • 微信小程序登錄流程
    • 登錄流程圖
    • 前端代碼
    • 后端代碼

微信小程序登錄流程

微信小程序官方文檔:微信小程序官方文檔
第一次學(xué)習(xí)微信小程序的登錄,以前也好奇微信小程序的授權(quán)登錄是怎么實現(xiàn)的,看過官方文檔后,這里記錄下自己學(xué)習(xí)小程序登錄的實現(xiàn)內(nèi)容。要是有不對的地方請指出來,這篇文章適合和我一樣的小白看。算是簡單的入個小門。

登錄流程圖

根據(jù)流程圖的說明,首先是微信小程序的前端調(diào)用wx.login()接口獲取到code值,然后前端使用wx.request()或者前端自己封裝的請求,來調(diào)用后臺自己寫的登錄接口,比如:login接口,后臺接收到前端傳來的code值后,后臺要調(diào)用微信接口服務(wù)里面的jscode2session接口,官方文檔有說明,詳情可看官方文檔,這個jscode2session接口會返回session_key和openid等值,一般是這二個值,unionid看滿足條件返回,然后后端在接收到這2個值后,看根據(jù)需要是否要加其他返回值,比如:token等,這里加token就是所說的自定義登錄態(tài),然后將這些值返回給前端,前端接收到返回值后,自定義登錄態(tài)存入storage,大致登錄就是這樣。
在這里插入圖片描述

前端代碼

這里你最好自己去微信公眾平臺:微信公眾平臺上面自己注冊一個微信小程序,用的測試號好像沒有secret值,所以后臺根本沒辦法正確獲取到openid值和session_key值,自己注冊了微信小程序后,你會有一個appId和secret這2個值,同時還有密鑰,這個以后再說。
這里我是自己用微信開發(fā)者工具新建的微信小程序項目,沒有加任務(wù)的東西,目錄如下:
在這里插入圖片描述
這里再app.js文件加上wx.request()代碼,代碼如下:
在這里插入圖片描述
App.js

//app.js
App({
 >: function () {
    // 展示本地存儲能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登錄
    wx.login({
      success: res => {
        // 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
        wx.login({
          success (res) {
            if (res.code) {
              //發(fā)起網(wǎng)絡(luò)請求
              wx.request({
                url: 'http://localhost:8080/WXLogin/login?code='+res.code,
                data: 'code='+res.code,
                method: "post",
                success: res => {
                  console.info(res.data);
                },
                fail:res => {
                  console.info("失敗");
                  console.info(res.data);
                }
              })
            } else {
              console.log('登錄失敗!' + res.errMsg)
            }
          }
        })
      }
    })
    // 獲取用戶信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經(jīng)授權(quán),可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會彈框
          wx.getUserInfo({
            success: res => {
              console.log("成功2!");
              // 可以將 res 發(fā)送給后臺解碼出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是網(wǎng)絡(luò)請求,可能會在 Page.onLoad 之后才返回
              // 所以此處加入 callback 以防止這種情況
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  }
})

后端代碼

可能需要的依賴

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

后臺發(fā)送get或者post請求的工具類
WeChatUtil.java 代碼如下:

package com.bowei.officialwebsite.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * 微信小程序工具類
 */
@Slf4j
public class WeChatUtil {

    public static String httpRequest(String requestUrl, String requestMethod, String output) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            if (null != output) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }
            // 從輸入流讀取返回內(nèi)容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            StringBuilder buffer = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 向指定 URL 發(fā)送POST方法的請求
     *
     * @param url  發(fā)送請求的 URL
     * @param json 請求參數(shù),請求參數(shù)應(yīng)該是 json 的形式。
     * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
     */
    public static String httpPost(String url, JSONObject json) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設(shè)置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發(fā)送POST請求必須設(shè)置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應(yīng)的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 發(fā)送請求參數(shù)

            out.print(json);
            // flush輸出流的緩沖
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應(yīng)
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result=result.concat(line);
            }
        } catch (Exception e) {
            System.out.println("發(fā)送 POST 請求出現(xiàn)異常!" + e);
            e.printStackTrace();
        }
        //使用finally塊來關(guān)閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}

在application.yml下配置微信小程序的appId和secret,這樣方便以后修改和維護(hù)
在這里插入圖片描述

后端接口代碼:
CommonResult 是自己封裝好的一個json返回對象,自己封裝的會返回code,message,data這三個值,這里你可以直接返回jsonObject。

package com.bowei.officialwebsite.controller;

import com.alibaba.fastjson.JSONObject;
import com.bowei.common.api.CommonResult;
import com.bowei.officialwebsite.utils.WeChatUtil;
import com.github.pagehelper.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Api(tags = "WXLoginController", description = "微信登錄模塊")
@Controller
@RequestMapping(value = "/WXLogin")
public class WXLoginController {

    @Value("${wxMini.appId}")
    public String appId;
    @Value("${wxMini.secret}")
    public String secret;

    @ApiOperation("登錄")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestParam(value = "code", required = false) String code){
        System.out.println("code==="+code);
        if(StringUtil.isEmpty(code)){
            return CommonResult.failed("code不能為空!");
        }
        System.out.println("appId="+appId+"|| secret="+secret);
        //微信接口服務(wù),通過調(diào)用微信接口服務(wù)中jscode2session接口獲取到openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String str = WeChatUtil.httpRequest(url, "GET", null);
        JSONObject jsonObject=JSONObject.parseObject(str);
        //將token也加進(jìn)去  先寫個假的
        jsonObject.put("token","sfskjnkjs3231311");
        System.out.println("json="+jsonObject);
        System.out.println(jsonObject.get("token"));
        return CommonResult.success(jsonObject);
    }
}

后端打印結(jié)果:
在這里插入圖片描述

前端返回結(jié)果:
在這里插入圖片描述

到這里登錄的代碼就結(jié)束了,這里主要顯示后端的代碼,畢竟本人是后端,對微信小程序不太熟悉,好了,自己的學(xué)習(xí)分享就到這里了,希望對各位有幫助吧。

相關(guān)案例查看更多