java实现微信登录

前言

上一篇做了php的微信登录,所以也总结一下Java的微信授权登录并获取用户信息这个功能的开发流程。

配置

配置什么的就不多说了,详细的配置可以直接前往我上一篇查看。

https://www.cnblogs.com/nothavebug/p/18277732

流程实现(后端)(JAVA)(springboot)

1.首先先配置一下application.yml文件

配置一下微信小程序的Appid 和 appSecret

2.编写控制层

package com.xiangwu.controller.Wx;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiangwu.common.exception.BaseException;
import com.xiangwu.common.exception.BussinessException;
import com.xiangwu.common.exception.MessageConstant;
import com.xiangwu.common.interceptor.BaseContext;
import com.xiangwu.common.interceptor.JwtProperties;
import com.xiangwu.common.jwt.JwtClaimsConstant;
import com.xiangwu.common.response.BaseResponse;
import com.xiangwu.common.utils.JwtUtil;
import com.xiangwu.entiry.Demand;
import com.xiangwu.entiry.Member;
import com.xiangwu.entiry.Member1;
import com.xiangwu.savedto.MemberDto;
import com.xiangwu.savedto.UserLoginDto;
import com.xiangwu.savedto.UserLoginVo;
import com.xiangwu.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author nothavebug
 * @Date 2024/7/2 14:58
 * @PackageName:com.yisen.controller
 * @ClassName: MenberController
 * @Description:
 * @Version 1.0
 */
@RestController("wxMemberController")
@RequestMapping("/user")
@Api(tags = "微信登录")
@Slf4j
public class MemberController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private JwtProperties jwtProperties;
    //C端用户登录--微信登录
    @PostMapping("/user/login")
    @ApiOperation("登录")
    public BaseResponse<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto) {
        //微信登录
        Member1 member = memberService.wxLogin(userLoginDto);
        //为微信生成jwt
        Map claims = new HashMap();
        //用户唯一标识
        claims.put(JwtClaimsConstant.USER_ID, member.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //其他处理


        return new BaseResponse<>(token);
    }

}

3.编写Service层

package com.xiangwu.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xiangwu.entiry.Member;
import com.xiangwu.entiry.Member1;
import com.xiangwu.savedto.UserLoginDto;

/**
 * @Author nothavebug
 * @Date 2024/7/2 14:58
 * @PackageName:com.xiangwu.service
 * @ClassName: MemberService
 * @Description:
 * @Version 1.0
 */
public interface MemberService extends IService<Member> {
    //微信登录
    Member1 wxLogin(UserLoginDto userLoginDto);
}

4.编写Impl

package com.xiangwu.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangwu.common.exception.LoginFailedException;
import com.xiangwu.common.interceptor.WeChatProperties;
import com.xiangwu.common.utils.HttpClientUtil;
import com.xiangwu.entiry.Demand;
import com.xiangwu.entiry.Member;
import com.xiangwu.entiry.Member1;
import com.xiangwu.mapper.DemandMapper;
import com.xiangwu.mapper.Member1Mapper;
import com.xiangwu.mapper.MemberMapper;
import com.xiangwu.savedto.UserLoginDto;
import com.xiangwu.service.DemandService;
import com.xiangwu.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author nothavebug
 * @Date 2024/7/2 14:58
 * @PackageName:com.xiangwu.service.impl
 * @ClassName: MemberServiceImpl
 * @Description:
 * @Version 1.0
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private Member1Mapper member1Mapper;
    @Override
    public Member1 wxLogin(UserLoginDto userLoginDto) {
        String code = userLoginDto.getCode();
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();

             // 调用微信 API 获取用户的手机号
            WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), userLoginDto.getEncryptedData(), userLoginDto.getIv());
            String phoneNumber = phoneInfo.getPhoneNumber();
            if (openid==null){
                throw new LoginFailedException("登录失败");
            }
            Member1 member = memberMapper.getBymobile(phoneNumber);
            if (member ==null){
                Member1 member1 = new Member1();
                member1.setOpenid(openid);
                member1.setAddTime(new Date());
                member1.setMobile(phoneNumber);
                member1.setAvatar("http://springboot.itliu.top/wx/images/20220225072654_1.jpg");
                member1.setMemberType("1");

                member1Mapper.insert(member1);
            }
            //  更新openid
            LambdaUpdateWrapper<Member1> member1LambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            member1LambdaUpdateWrapper.set(Member1::getOpenid,openid)
                    .eq(Member1::getMobile,phoneNumber);
            member1Mapper.update(member,member1LambdaUpdateWrapper);
            return member;

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }


    }
    private String getOpenid(String code){
        //请求参数封装
        Map map = new HashMap();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //调用工具类,向微信接口服务发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        log.info("微信登录返回结果:{}", json);
        //解析json字符串
        JSONObject jsonObject = JSON.parseObject(json);
        log.info("jsonObject: {}",jsonObject);
        String openid = jsonObject.getString("openid");
        log.info("微信用户的openid为:{}", openid);
        return openid;
    }
}

流程实现(前端)(Vue)(uniapp)

前端微信登录流程实现请移步我上一篇:https://www.cnblogs.com/nothavebug/p/18277732

posted @ 2024-07-02 15:04  我恨bug  阅读(228)  评论(1编辑  收藏  举报