微信小程序拉取微信登录结合springboot与redis

微信小程序登录

先来看看流程图
在这里插入图片描述

上图就是微信小程序登录的过程,我们只先看上半部分,调用拉取微信自动获取的登陆方法

  1. 首先需要在微信开发者工具里的.js的wx.login方法来获取一个存在5分钟的code
  2. 然后我们把这个code发到后台,用于下一步换取session_key+openid
  3. 我们在后端服务器中封装一些参数去请求wx换取session_key+openid
  4. 得到数据存到一个对象里,再存到数据库中,完成登录并获取用户唯一指定openid和session_key

我们来看一下具体实现

 wx.login({
      success: function(res){
        console.log(res)
        //获取临时凭证
        var code=res.code;
        //调用后端,获取微信的session_key,secret
        wx.request({
          url: 'http://127.0.0.1:8092//api/v1.0/songlists/user/wxLogin?code='+code,
          method: "POST",
          success: function(result){
            console.log(result);
          }
        })
      }
    })
  },

先调用login来获取用户code,在返回的res里面存code,然后我们加到访问请求url中’http://127.0.0.1:8092//api/v1.0/songlists/user/wxLogin?code=’+code
其中/api/v1.0/songlists/user/wxLogin这是请求后端地址
根目录
在这里插入图片描述
wxLogin方法
在这里插入图片描述
带了一个code参数在url中

后端(springboot项目)

 @PostMapping("/wxLogin")
    public CommonReturnType wxLogin(String code){
        System.out.println("wx-code: "+code);
        String url="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> param=new HashMap<>();
        param.put("appid","xxxxxxxxx");
        param.put("secret","xxxxxxxxx");
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String wxResult=HttpClientUtil.doGet(url,param);
        System.out.println(wxResult);

        WXSessionModel wxSessionModel= JSON.parseObject(wxResult,WXSessionModel.class);
        redisService.set("user-redis-session: "+wxSessionModel.getOpenid(),wxSessionModel.getSession_key());
        //
        return CommonReturnType.creat(null);
    }

这里是服务端请求微信的url
在这里插入图片描述
但是这里参数并不完全,所以我们用了工具类HttpClientUtil来封装url请求

这里给出工具类,大家自行copy

package com.fehead.songs.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;
    }
}

接着上面来说,给map里传入四个参数:appid,secret,js_code,grant_type.
这里填你自己小程序的信息,appid与secret都能在你的微信公众号开发里面找到

在这里插入图片描述
然后这一步我们调用工具类将参数传进去

 String wxResult=HttpClientUtil.doGet(url,param);

可见返回的是一个string类型的session_key与openid

存到数据库中(redis)

刚得到一个字符串类型的,但是我们需要把他转化为一个对象
这时候需要我们用到一个新建一个model类,里面放着session_key与openid,这里省略get/set方法
在这里插入图片描述
然后,我们把上面的字符串转化为对象,用到了反序列化的JSON.parseObject方法,参数前面为将要转化为的字符串,后面跟着转化为哪个类.

WXSessionModel wxSessionModel= JSON.parseObject(wxResult,WXSessionModel.class);

到了最后一步了,我们需要存到redis数据库中,这里不再讲述如何整合springboot与redis可参照springboot整合redis这篇文章,我们这边直接就用里面的方法


我们刚存到一个WXSessionModel类中,我们直接调用它取出得到的Openid与Session_key来存到redis中

  redisService.set("user-redis-session: "+wxSessionModel.getOpenid(),wxSessionModel.getSession_key());

这下我们来看下结果

这里在redis里面我们看见了已经存好的openid与session_key,可以设置过期时间.
这里就简单的实现了微信小程序的登录操作

制作不易,转载请标注~

发布了69 篇原创文章 · 获赞 54 · 访问量 9598

猜你喜欢

转载自blog.csdn.net/kingtok/article/details/101175810