1. 程式人生 > >小程式之登入授權(springboot做後端)

小程式之登入授權(springboot做後端)

小程式登入流程:

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

在onGetUserInfo中新增介面

onGetUserInfo(event) {
    const userInfo = event.detail.userInfo
    if (userInfo) {
        wx.login({
            success: function (login_res) {
                wx.getUserInfo({
                    success:
function (res) { wx.request({ url: config.api_base_url+'me/login', method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }
, data: { code:login_res.code, userHead: userInfo.avatarUrl, userName: userInfo.nickName, userGender: userInfo.gender, userCity:
userInfo.city, userProvince: userInfo.province }, success:function(res) { const userInfo = res.data.object // 將返回的資料儲存到全域性的緩衝中,方便其他頁面使用 wx.setStorage({ key: 'userInfo', data: userInfo }) } }) } }) } }) this.setData({ hasUserInfo: true, userInfo: userInfo }) } }

需要注意因為傳送的是POST請求,所以需要將請求頭設定為 ‘content-type’ : ‘application/x-www-form-urlencoded’ 並將method設定為PSOT型別。

Springboot後臺資料處理

1、首先獲取的自己小程式的appid、secret,封裝為一個介面
public interface UserConstantInterface {
	// 請求的網址
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
	// 你的appid
    public static final String WX_LOGIN_APPID = "xxxxxxxxxxxxxxxxxx";
	// 你的密匙
    public static final String WX_LOGIN_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
	// 固定引數
    public static final String WX_LOGIN_GRANT_TYPE = "authorization_code";

}
2、在pom中引入httpclient的包,分裝一個傳送get、post的請求類
<!-- httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.5</version>
</dependency>

傳送請求的工具類

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

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;

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;
    }
}
3、編寫controller
@RestController
@RequestMapping("/api")
public class UserApi {

    @Autowired
    private UserService userService;


    @PostMapping("/me/login")
    public JsonResult user_login(
            @RequestParam("code") String code,
            @RequestParam("userHead") String userHead,
            @RequestParam("userName") String userName,
            @RequestParam("userGender") String userGender,
            @RequestParam("userCity") String userCity,
            @RequestParam("userProvince") String userProvince
    ){
        // 配置請求引數
        Map<String, String> param = new HashMap<>();
        param.put("appid", UserConstantInterface.WX_LOGIN_APPID);
        param.put("secret", UserConstantInterface.WX_LOGIN_SECRET);
        param.put("js_code", code);
        param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE);
        // 傳送請求
        String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 獲取引數返回的
        String session_key = jsonObject.get("session_key").toString();
        String open_id = jsonObject.get("openid").toString();
        // 根據返回的user實體類,判斷使用者是否是新使用者,不是的話,更新最新登入時間,是的話,將使用者資訊存到資料庫
        User user = userService.selectByOpenId(open_id);
        if(user != null){
            user.setUserNewLogin(new Date());
            userService.updateById(user);
        }else{
            User insert_user = new User();
            insert_user.setUserHead(userHead);
            insert_user.setUserName(userName);
            insert_user.setUserGender(userGender);
            insert_user.setUserNewLogin(new Date());
            insert_user.setUserCity(userCity);
            insert_user.setUserProvince(userProvince);
            insert_user.setUserOpenid(open_id);
            System.out.println("insert_user:"+insert_user.toString());
            // 新增到資料庫
            Boolean flag = userService.insert(insert_user);
            if(!flag){
                return new JsonResult(ResultCode.FAIL);
            }
        }
        // 封裝返回小程式
        Map<String, String> result = new HashMap<>();
        result.put("session_key", session_key);
        result.put("open_id", open_id);
        return new JsonResult(ResultCode.SUCCESS, result);

    }

}
3、清除授權資料,驗證登入

在這裡插入圖片描述

4、獲取返回資訊

在這裡插入圖片描述

在這裡插入圖片描述

小程式段的處理請檢視我的上一篇部落格 : 小程式之登入授權(小程式端處理)