SpringBoot实现微信小程序登录

文章目录

        • 一、登录流程
        • 二、后端实现
          • 1、SpringBoot项目结构树
          • 2、实现auth.code2Session 接口的封装
          • 3、建立用户信息表及用户增删改查的管理
          • 4、实现登录认证及令牌生成
        • 三、前端实现与测试
          • 1、编写登录公共函数
          • 2、搭建登录页面
          • 3、登录测试

一、登录流程

首先参考小程序官方文档中的流程图:
SpringBoot实现微信小程序登录_第1张图片

根据流程图描述,主要步骤有以下几步
1、小程序端调用 wx.login()向微信接口服务获取 临时登录凭证code ,并上传至开发者服务端。
2、开发者服务端向微信服务接口服务调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 和 会话密钥 session_key。
3、开发者服务端根据session_key等信息,基于JWT标准,生成自定义的网络令牌token,返回至小程序端存储。

关于SpringBoot实现JWT的具体细节,请参考本人博文:
SpringBoot整合SpringSecurity实现JWT认证
本文将具体对微信小程序的前端与后端实现进行详细描述:

二、后端实现

1、SpringBoot项目结构树

SpringBoot实现微信小程序登录_第2张图片
SpringBoot实现微信小程序登录_第3张图片

2、实现auth.code2Session 接口的封装

WxMiniApi.java

/**
 * 微信小程序统一服务端API接口
 * @author zhuhuix
 * @date 2020-04-03
 */
public interface WxMiniApi {

    /**
     * auth.code2Session
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     * 请求参数   属性	     类型	   默认值	必填	 说明
     * @param   appId	     string		         是	   小程序 appId
     * @param   secret	     string		         是	   小程序 appSecret
     * @param   jsCode	     string		         是	   登录时获取的 code
     *          grantType	 string		         是	   授权类型,此处只需填写 authorization_code
     * 返回值
     * @return  JSON 数据包
     *           属性	     类型	   说明
     *          openid	     string	  用户唯一标识
     *          session_key	 string	  会话密钥
     *          unionid	     string	  用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
     *          errcode	     number	  错误码
     *          errmsg	     string	  错误信息
     *
     *          errcode 的合法值
     *
     *          值	         说明	                     最低版本
     *          -1	         系统繁忙,此时请开发者稍候再试
     *          0	         请求成功
     *          40029	     code 无效
     *          45011	     频率限制,每个用户每分钟100次
     */
    JSONObject authCode2Session(String appId,String secret,String jsCode);
}

WxMiniApiImpl.java

/**
 * 微信小程序Api接口实现类
 *
 * @author zhuhuix
 * @date 2020-04-03
 */

@Slf4j
@Service
public class WxMiniApiImpl implements WxMiniApi {

    @Override
    public JSONObject authCode2Session(String appId, String secret, String jsCode) {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        String str = WeChatUtil.httpRequest(url, "GET", null);
        log.info("api/wx-mini/getSessionKey:" + str);
        if (StringUtils.isEmpty(str)) {
            return null;
        } else {
            return JSONObject.parseObject(str);
        }

    }
}

WeChatUtil.java

/**
 * 微信小程序工具类
 *
 * @author zhuhuix
 * @date 2019-12-25
 */
@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();
            }
            // 从输入流读取返回内容
            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 "";
    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        log.info("encryptDataB64:" + encryptDataB64);
        log.info("sessionKeyB64:" + sessionKeyB64);
        log.info("ivB64:" + ivB64);
        return new String(
                decryptOfDiyIv(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }

    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIv(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url  发送请求的 URL
     * @param json 请求参数,请求参数应该是 json 的形式。
     * @return 所代表远程资源的响应结果
     */
    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();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数

            out.print(json);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result=result.concat(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
3、建立用户信息表及用户增删改查的管理

User.java

/**
 * 用户表
 *
 * @author zhuhuix
 * @date 2020-04-03
 */
@Entity
@Getter
@Setter
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull(groups = Update.class)
    private Long id;


    @Column(name = "user_name", unique = true)
    private String userName;

    @JsonIgnore
    private String password;

    /**
     * 微信openId
     */
    @Column(unique = true, name = "open_id")
    private String openId;

    /**
     * 用户昵称
     */
    @Column(name="nick_name")
    private String nickName;

    /**
     * 性别 0-未知 1-male,2-female
     */
    private Integer gender;

    /**
     * 头像地址
     */
    @Column(name = "avatar_url")
    private String avatarUrl;

    @Column(name = "union_id")
    private String unionId;

    private String country;

    private String province;

    private String city;

    private String language;

    @Email
    private String email;

    private String phone;

    private String remarks;

    private Boolean enabled;

    @JsonIgnore
    @Column(name = "last_password_reset_time")
    private Timestamp lastPasswordResetTime;

    @JsonIgnore
    @Column(name = "create_time")
    @CreationTimestamp
    private Timestamp createTime;

    @JsonIgnore
    @Column(name = "update_time")
    @UpdateTimestamp
    private Timestamp updateTime;

}

UserService.java

/**
 * 用户信息接口
 *
 * @author zhuhuix
 * @date 2020-04-03
 */
public interface UserService {

    /**
     * 增加用户
     *
     * @param user 待新增的用户
     * @return 增加成功的用户
     */
    Result<User> create(User user);

    /**
     * 删除用户
     *
     * @param user 待删除的用户
     */
    void delete(User user);

    /**
     * 修改用户
     *
     * @param user 待修改的用户
     * @return 修改成功的用户
     */
    Result<User> update(User user);

    /**
     * 根据id查找用户
     *
     * @param id 用户id
     * @return id对应的用户
     */
    Result<User> findById(Long id);

    /**
     * 用于微信注册用户查找:根据openId查找用户
     *
     * @param openId 微信openId
     * @return openId对应的用户
     */
    Result<User> findByOpenId(String openId);
}

UserServiceImpl.java

/**
 * 用户接口实现类
 *
 * @author zhuhuix
 * @date 2020-04-03
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<User> create(User user) {
        return new Result<User>().ok(userRepository.save(user));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(User user) {
        userRepository.delete(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<User> update(User user) {
        return new Result<User>().ok(userRepository.save(user));
    }

    @Override
    public Result<User> findById(Long id) {
        Optional<User> optional = userRepository.findById(id);
        return optional.map(user -> new Result<User>().ok(user)).orElse(null);
    }

    @Override
    public Result<User> findByOpenId(String openId) {
        return new Result<User>().ok(userRepository.findByOpenId(openId));
    }
}

Result.java

/**
 * API统一返回基类
 * @author zhuhuix
 * @date 2020-04-03
 */
@Getter
@Setter
public class Result<T> implements Serializable {

    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 错误码
     */
    private String errCode;

    /**
     *  错误信息
     */
    private String errMsg;

    /**
     * 返回数据
     */
    private T module;


    @Override
    public String toString() {
        return "Result{" +
                "success=" + success +
                ", errCode='" + errCode + '\'' +
                ", errMsg='" + errMsg + '\'' +
                ", module=" + module +
                '}';
    }

    public Result<T> ok(T module){
        this.setSuccess(true);
        this.setErrCode("0");
        this.setErrCode("ok");
        this.setModule(module);
        return this;
    }

    public Result<T> error(String errCode,String errMsg){
        this.setSuccess(false);
        this.setErrCode(errCode);
        this.setErrMsg(errMsg);
        return this;
    }

    public Result<T> error(String errMsg){
        this.setSuccess(false);
        this.setErrCode("-1");
        this.setErrMsg(errMsg);
        return this;
    }
}
4、实现登录认证及令牌生成

AuthService.java

/**
 * 登录授权服务接口
 *
 * @author zhuhuix
 * @date 2020-04-07
 */
public interface AuthService {

    /**
     * 登录授权
     *
     * @param authUserDto 认证用户请求信息
     * @param request Http请求
     * @return 认证用户返回信息
     */
    Result<AuthUserDto> login(AuthUserDto authUserDto, HttpServletRequest request);
}

AuthServiceImpl.java

/**
 * 授权登录接口实现类
 *
 * @author zhuhuix
 * @date 2020-04-07
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AuthServiceImpl implements AuthService {

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

    private final JwtTokenUtils jwtTokenUtils;
    private final WxMiniApi wxMiniApi;
    private final UserService userService;

    public AuthServiceImpl(JwtTokenUtils jwtTokenUtils, WxMiniApi wxMiniApi, UserService userService) {
        this.jwtTokenUtils = jwtTokenUtils;
        this.wxMiniApi = wxMiniApi;
        this.userService = userService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<AuthUserDto> login(AuthUserDto authUserDto, HttpServletRequest request) {
        Result<AuthUserDto> result = new Result<>();

        //authType=1代表是微信登录
        if (!StringUtils.isEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 1) {
            JSONObject jsonObject = wxMiniApi.authCode2Session(appId, secret, authUserDto.getCode());
            if (jsonObject == null) {
                throw new RuntimeException("调用微信端授权认证接口错误");
            }
            String openId = jsonObject.getString(Constant.OPEN_ID);
            String sessionKey = jsonObject.getString(Constant.SESSION_KEY);
            String unionId = jsonObject.getString(Constant.UNION_ID);
            if (StringUtils.isEmpty(openId)) {
                return result.error(jsonObject.getString(Constant.ERR_CODE), jsonObject.getString(Constant.ERR_MSG));
            }
            authUserDto.setOpenId(openId);

            //判断用户表中是否存在该用户,不存在则进行解密得到用户信息,并进行新增用户
            Result<User> resultUser = userService.findByOpenId(openId);
            if (resultUser.getModule() == null) {
                String userInfo = WeChatUtil.decryptData(authUserDto.getEncryptedData(), sessionKey, authUserDto.getIv());
                if (StringUtils.isEmpty(userInfo)) {
                    throw new RuntimeException("解密用户信息错误");
                }
                User user = JSONObject.parseObject(userInfo, User.class);
                if (user == null) {
                    throw new RuntimeException("填充用户对象错误");
                }
                user.setUnionId(unionId);
                userService.create(user);
                authUserDto.setUserInfo(user);

            } else {
                authUserDto.setUserInfo(resultUser.getModule());
            }

            //创建token
            String token = jwtTokenUtils.createToken(openId, null);
            if (StringUtils.isEmpty(token)) {
                throw new RuntimeException("生成token错误");
            }
            authUserDto.setToken(token);

        }
        return result.ok(authUserDto);
    }
}

AuthUserDto.java

/**
 * 认证用户
 *
 * @author zhuhuix
 * @date 2020-04-03
 */
@Getter
@Setter
public class AuthUserDto {

    /**
     * 授权类型:0--WEB端 1--微信端
     */
    private Integer authType;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    @JsonIgnore
    private String password;

    /**
     * 传入参数:临时登录凭证
     */
    private String code;

    /**
     * 用户登录id
     */
    private String uuid = "";

    //**********************************
    //以下为微信类传输字段

    /**
     * 微信openId
     */
    private String openId;

    /**
     * 传入参数: 用户非敏感信息
     */
    private String rawData;

    /**
     * 传入参数: 签名
     */
    private String signature;

    /**
     * 传入参数: 用户敏感信息
     */
    private String encryptedData;

    /**
     * 传入参数: 解密算法的向量
     */
    private String iv;

    /**
     * 会话密钥
     */
    @JsonIgnore
    private String sessionKey;

    /**
     * 用户在开放平台的唯一标识符
     */
    @JsonIgnore
    private String unionId;

    //以上为微信类传输字段
    //**********************************

    /**
     * 返回:服务器jwt token
     */
    private String token;

    /**
     * 返回:userName或openId对应的用户
     */
    private User userInfo;

    @Override
    public String toString() {
        return "AuthUser{" +
                "userName='" + userName + '\'' +
                ", password='" + "*********" + '\'' +
                ", code='" + code + '\'' +
                ", uuid='" + uuid + '\'' +
                ", openId='" + openId + '\'' +
                ", token='" + token + '\'' +
                ", userInfo=" + userInfo +
                '}';
    }
}

AuthController.java

/**
 * api登录授权
 *
 * @author zhuhuix
 * @date 2020-03-30
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@Api(tags = "系统授权接口")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public ResponseEntity login(@RequestBody AuthUserDto authUserDto, HttpServletRequest request) {
        return ResponseEntity.ok(authService.login(authUserDto, request));
    }

}

三、前端实现与测试

1、编写登录公共函数
 // 公共登录动作
  doLogin: function (callback) {
    let that = this;
    wx.login({
      success: function (loginRes) {
        //console.log(loginRes, "loginRes");
        if (loginRes.code) {
          /*
           * @desc: 获取用户信息 期望数据如下
           *
           * @param: userInfo       [Object]
           * @param: rawData        [String]
           * @param: signature      [String]
           * @param: encryptedData  [String]
           * @param: iv             [String]
           **/
          wx.getUserInfo({
            withCredentials: true, // 非必填, 默认为true

            success: function (infoRes) {
              console.log("infoRes:", infoRes);
              // 请求服务端的登录接口
              wx.request({
                url: api.loginUrl,
                method: "POST",
                data: {
                  authType: 1, //1代表微信端登录
                  code: loginRes.code, // 临时登录凭证
                  rawData: infoRes.rawData, // 用户非敏感信息
                  signature: infoRes.signature, // 签名
                  encryptedData: infoRes.encryptedData, // 用户敏感信息
                  iv: infoRes.iv, // 解密算法的向量
                  token: wx.getStorageSync("loginFlag"),
                },

                success: function (res) {
                  console.log("login success:", res);
                  res = res.data;
                  if (res.success) {
                    that.globalData.userInfo = res.module.userInfo;
                    console.log(
                      "globalData.userInfo",
                      that.globalData.userInfo
                    );
                    wx.setStorageSync("userInfo", res.module.userInfo);
                    wx.setStorageSync("loginFlag", res.module.token);
                    if (callback) {
                      callback();
                    }
                  } else {
                    that.showInfo(res.errMsg);
                  }
                },

                fail: function (error) {
                  // 调用服务端登录接口失败
                  that.showInfo("调用接口失败");
                  console.log(error);
                },
              });
            },

            fail: function (error) {
              console.log(error);
              // 获取 userInfo 失败,去检查是否未开启权限
              wx.hideLoading();
              that.showInfo("调用request接口失败");
              console.log(error);
              wwx.navigateTo({
                url: "/pages/index/index",
              });
            },
          });
        } else {
          // 获取 code 失败
          that.showInfo("登录失败");
          console.log("调用wx.login获取code失败");
        }
      },

      fail: function (error) {
        // 调用 wx.login 接口失败
        that.showInfo("接口调用失败");
        console.log(error);
      },
    });
  },

2、搭建登录页面
<view class="index-home">
    <view class="userinfo">
        <open-data class="userinfo-avatar" background-size="cover" type="userAvatarUrl"></open-data>
        <open-data class="userinfo-nickname" type="userNickName"></open-data>
    </view>

    <!-- 需要使用 button 来授权登录 -->
    <view class="index-button_container">
        <van-button wx:if="{{canIUse}}"  type="primary" size="large" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">
            授权登录
        </van-button>
        <view class="index-home__desc" wx:else>请升级微信版本</view>
    </view>
</view>
/** index.js **/

//获取app实例
const app = getApp();

Page({
  data: {
    token: wx.getStorageSync("loginFlag"),
    userInfo: {},
    //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    // 是否登录,根据后台返回的token判断
    hasLogin: wx.getStorageSync("loginFlag") ? true : false,
  },

  onLoad: function () {},

  bindGetUserInfo: function (e) {
    console.log("用户按了允许授权按钮", e.detail.userInfo);
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      app.doLogin(app.switchTheTab);
    } else {
      //用户按了拒绝按钮
    }
  },

  onShow: function () {},
});
3、登录测试

登录页面
SpringBoot实现微信小程序登录_第4张图片
服务端返回数据:
SpringBoot实现微信小程序登录_第5张图片

你可能感兴趣的:(java,小程序,java,spring,boot,小程序)