SpringBoot中微信登录的实现

本文介绍了如何在SpringBoot应用中使用WeChatProperties配置微信小程序appid和secret,处理控制层的code获取与验证,以及在服务层通过HttpClientUtil发送GET请求实现微信登录并获取openid的过程。
摘要由CSDN通过智能技术生成

目录

1 WeChatProperties的赋值

2 控制层相关操作

3 服务层相关操作


1 WeChatProperties的赋值

现在有WeChatProperties.class如下:

@Component
@ConfigurationProperties(prefix = "xxx.wechat")
@Data
public class WeChatProperties {
    private String appid; //小程序的appid
    private String secret; //小程序的秘钥
    //其它微信支付相关内容...
}

在application.yml中,配置appid和secert,如下:

xxx: 
 wechat:
    appid: xx
    secret: yy

其中appid和 secert的获取方式,如下:

2 控制层相关操作

通过微信小程序官方文档的文档,我们可以知道我们需要获取code,如下:

 所以我们就可以设计一个DTO来接收,如下:

@Data
public class UserLoginDTO implements Serializable {
    private String code;

}

因此,我们在控制层有代码如下:

public class UserController {
    //从请求中获取code
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        // 微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为用户生成JWT令牌,这里因人而异就不提供相关代码了

        //主要返回用户数据库中的id和JWT令牌外加登录获得的的openid(用户唯一标识)
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();
        return Result.success(userLoginVO);
    }
}

3 服务层相关操作

在控制层得到code之后,我们就能向小程序官方文档指定的连接发出Get请求,如下:

https://api.weixin.qq.com/sns/jscode2session

 先整一个发送Get请求的工具类,如下:

public class HttpClientUtil {
    public static String doGet(String url,Map<String,String> paramMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try{
            URIBuilder builder = new URIBuilder(url);
            if(paramMap != null){
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}

然后我们就可以在服务层发送Get请求获取openid,请求的内容为控制层相关操作中所示请求参数

@Service
public class UserServiceImpl implements UserService {
    //get请求的链接
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务,获取openId
        String openid = getOpenId(userLoginDTO.getCode());

        //判断openId是否为空,为空则抛出异常


        //判断是否为新用户,是则插入数据库,不是则返回
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            //其它代码
        }
        return user;
    }

    /**
     * 获取openId
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        Map<String, String> 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);

        JSONObject jsonObj = JSON.parseObject(json);
        String openid = jsonObj.getString("openid");
        return openid;
    }
}

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厂里英才

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值