首页 > 编程语言 >springboot项目后端实现小程序的登录

springboot项目后端实现小程序的登录

时间:2024-06-04 22:01:52浏览次数:28  
标签:springboot 登录 程序 token params new import com String

1.主要目的得到手机号+openid

(1)要想获取手机号 就要通过POST 请求 https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=xxx 获取

在这里插入图片描述

(2)想要得到access_token,就要通过GET请求https://api.weixin.qq.com/cgi-bin/token 响应获取

在这里插入图片描述

(3)想要获取code 通过前端的bindgetphonenumber方法获取然后传入后端的

(4)获取openid 通过GET请求

https://api.weixin.qq.com/sns/jscode2session
在这里插入图片描述

2.主要核心代码如下:

package com.zzyl.service.impl;

import cn.hutool.http.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.MemberDto;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.MemberService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Value("${wx.appid}")
    private  String appid;
    @Value("${wx.secret}")
    private  String secret;
    private static final String BASE_URL = "https://api.weixin.qq.com";

    @Override
    public LoginVo login(MemberDto dto) {
//        1.获取oppenid
        String openId = getOpenid(dto.getCode());
//        2.获取手机号凭证
        String accessToken = getAccessToken();
//        3.获取手机号
        String phone = getPhone(dto.getPhoneCode(), accessToken);
//        4.根据openid查询数据库  如果有的话就修改手机号, 没有就新增
        Member member = null;
        try {
            member = memberMapper.selectByOpenId(openId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isNull(member)) {
                String name = "微信用户" + phone.substring(7);
//               builder是简化对象的构建过程,可以理解为多参构造器
                member = Member.builder()
                        .openId(openId)
                        .phone(phone)
                        .name(name).build();
                memberMapper.insert(member);
            } else {
                member.setPhone(phone);
                memberMapper.update(member);
            }

//        5.登录成功设置令牌
        LoginVo loginVo = new LoginVo();
        Map<String, Object> clams = new HashMap<>();
        try {
            clams.put("id", member.getId());
            clams.put("name", member.getName());
            String token = JwtUtil.createJWT(secret, 24, clams);
            loginVo.setToken(token);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.SYSYTEM_FAIL);
        }
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    /**
     * 获取手机号凭证
     * @return
     */
    private String getAccessToken() {
        String url = "/cgi-bin/token";
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", appid);
        params.put("secret", secret);
        String token = null;
        try {
            String resStr = HttpUtil.get(BASE_URL + url, params);
            token = (String) JSONUtil.parseObj(resStr).get("access_token");
        } catch (Exception e) {
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        return token;
    }
    /**
     * @param phoneCode    手机号获取凭证(前端登录传入的)
     * @param accessToken 手机号接口调用凭证
     * @return
     */
    private String getPhone(String phoneCode, String accessToken) {
        String url = "/wxa/business/getuserphonenumber";
        Map<String, Object> bodys = new HashMap<>();
        bodys.put("code", phoneCode);
        String phone = null;
        try {
            HttpRequest request = HttpUtil.createRequest(Method.POST, BASE_URL + url+"?access_token="+accessToken);
            request.body(JSONUtil.toJsonStr(bodys));
            HttpResponse response = request.execute();
            String resStr =response.body();
            Object phoneInfo = JSONUtil.parseObj(resStr). get("phone_info");
            phone = JSONUtil.parseObj(phoneInfo).getStr("phoneNumber");
            return phone;
        } catch (Exception e) {
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }

    }
    /**
     * 根据code获取用户在小程序的唯一标识
     *
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        String url = "/sns/jscode2session";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        JSONObject resObj = null;
        Object errcode = null;
        try {
            HttpRequest request = HttpUtil.createRequest(Method.POST, BASE_URL + url).form(params);
            HttpResponse response = request.execute();
            resObj = JSONUtil.parseObj(response.body());
            errcode = resObj.get("errcode");
        } catch (HttpException e) {
            throw new BaseException(BasicEnum.SYSYTEM_FAIL);
        }
        log.info("resObj: {}", resObj);
        if (errcode != null) {
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }
        return (String) resObj.get("openid");
    }
}

标签:springboot,登录,程序,token,params,new,import,com,String
From: https://blog.csdn.net/pursuedream6/article/details/139437180

相关文章

  • 基于微信小程序的健身小助手打卡预约教学系统(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 基于SpringBoot+Vue的足球社区管理系统(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 基于SpringBoot+Vue的医院住院管理系统设计与实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示项目运行截图技术框架后端采用SpringBoot框架前端框架Vue可行性分析系统测试系统测试的目的系统功能测试数据库表设计代码参考数据库脚本为什么选择我?获取源码前言......
  • 设计程序,要求程序可以加入到一个多播组中并等待服务器发送数据包,并且程序还需要具有发
    目录题目分析代码结果题目小组实现,小组中的每位成员都需要设计程序,要求程序可以加入到一个多播组中并等待服务器发送数据包,并且程序还需要具有发送功能,如果收到数据包则把消息内容输出到终端,消息内容格式[消息来源IP消息时间]:消息内容分析1.发送端需设置套接字的广......
  • 基于springboot在线互动学习网站设计(11726)
     有需要的同学,源代码和配套文档领取,加文章最下方的名片哦一、项目演示项目演示视频二、资料介绍完整源代码(前后端源代码+SQL脚本)配套文档(LW+PPT+开题报告)远程调试控屏包运行三、技术介绍Java语言SSM框架SpringBoot框架Vue框架JSP页面Mysql数据库IDEA/Eclipse开发四、项......
  • 基于springboot校园资产管理系统(11725)
     有需要的同学,源代码和配套文档领取,加文章最下方的名片哦一、项目演示项目演示视频二、资料介绍完整源代码(前后端源代码+SQL脚本)配套文档(LW+PPT+开题报告)远程调试控屏包运行三、技术介绍Java语言SSM框架SpringBoot框架Vue框架JSP页面Mysql数据库IDEA/Eclipse开发四、项......
  • 基于springboot-vue的毕业论文管理系统(11728)
     有需要的同学,源代码和配套文档领取,加文章最下方的名片哦一、项目演示二、资料项目演示视频介绍完整源代码(前后端源代码+SQL脚本)配套文档(LW+PPT+开题报告)远程调试控屏包运行三、技术介绍Java语言SSM框架SpringBoot框架Vue框架JSP页面Mysql数据库IDEA/Eclipse开发四、项......
  • 按键中断驱动程序-poll机制
    前言:学东西的时候总是喜欢碎碎念,去思考该怎么学。关于嵌入式开发,以前就觉得嵌入式只是一个工具,关键还是结合专业知识赋能,比如控制、信号处理、神经网络、计算机网络、各种协议比如蓝牙、wifi,音视频,当然,如果能够把内核学的很透彻,那也是很了不起的。现在越学越觉得这个东西应该就是......
  • SpringBoot+微信支付-JSAPI
    引入微信支付SDKMaven:com.github.wechatpay-apiv3:wechatpay-java-core:0.2.12Maven:com.github.wechatpay-apiv3:wechatpay-java:0.2.12代码示例packagexxxx.cashier.payChannel.handler;importxxxx.common.domain.model.exception.BusinessException;importxxxx.c......
  • 新版校园跑腿外卖独立版+APP+小程序前端外卖配送平台源码
    源码介绍:同城校园跑腿外卖配送平台源码,支持自定义diy你可以设计你的页面,设计你自己的风格,支持多校园,独立版本,多商户,有用户端,骑手端,商家端,强大的功演示截图:安装说明:服务器2h4G5M即可,服务器系统:centos8,服务器上安装宝塔面板,不懂怎么安装宝塔的可以百度,所需环境:php7.3......