WechatController.java 6.06 KB
package com.meishu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meishu.common.ResponseData;
import com.meishu.common.ResponseVO;
import com.meishu.common.configure.RestTemplateConfig;
import com.meishu.common.configure.WechatConfig;
import com.meishu.dto.wechat.AuthenRequestDTO;
import com.meishu.dto.wechat.JsSdkDTO;
import com.meishu.dto.wechat.SignDTO;
import com.meishu.mapper.AccessTokenMapper;
import com.meishu.mapper.StudentMapper;
import com.meishu.model.AccessTokenDO;
import com.meishu.model.StudentDO;
import com.meishu.util.SecretUtils;
import com.meishu.util.WechatUtil;
import com.meishu.vo.wechat.AuthenTokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/wechat")
@Api(tags = "微信授权")
public class WechatController {

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private AccessTokenMapper accessTokenMapper;

    @Autowired
    private StudentMapper studentMapper;

    @PostMapping(value = "/getJsapiTicket")
    @ApiOperation("通过token请求获得jsapi_ticket    {url}")
    public ResponseVO getJsapiTicket(@RequestBody SignDTO signVO) {

        List<AccessTokenDO> accessTokens = accessTokenMapper.selectList(null);

        String accessToken = "";
        if (accessTokens.size() == 0) {
            accessToken = WechatUtil.getAccessToken().getAccess_token();
            AccessTokenDO accessToken1 = new AccessTokenDO();
            accessToken1.setAccessToken(accessToken);
            accessToken1.setUpdateDate(LocalDateTime.now());
            accessTokenMapper.insert(accessToken1);
        } else {
            AccessTokenDO accessToken1 = accessTokens.get(0);
            int diff = LocalDateTime.now().getNano() - accessToken1.getUpdateDate().getNano();
            if (diff >= 2 * 60 * 60*1000000000 - 5*1000000000) {
                accessToken = WechatUtil.getAccessToken().getAccess_token();
                accessToken1.setAccessToken(accessToken);
                accessToken1.setUpdateDate(LocalDateTime.now());
                accessTokenMapper.updateById(accessToken1);
            } else {
                accessToken = accessToken1.getAccessToken();
            }
        }
        signVO.setAccess_token(accessToken);
        String url1 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        ResponseEntity<JsSdkDTO> response1 = restTemplateConfig.restTemplate()
                .exchange(url1, HttpMethod.GET, null, JsSdkDTO.class);

        String ticket = response1.getBody().getTicket();
        signVO.setJsapi_ticket(ticket);
        signVO.setNoncestr("Wm3WZYTPz0wzccnW");
        signVO.setTimestamp(String.valueOf(System.currentTimeMillis()));
        String signStr = "jsapi_ticket=" + signVO.getJsapi_ticket() + "&noncestr=" + signVO.getNoncestr() + "&timestamp=" + signVO.getTimestamp()
                + "&url=" + signVO.getUrl();

        signVO.setSign(SecretUtils.getSHAString(signStr));
        signVO.setAppId(wechatConfig.getAppId());
        signVO.setAgentId(wechatConfig.getAgentId());
        return ResponseData.generateCreatedResponse(0, signVO);
    }


    @PostMapping("/webAuthen")
    @ApiOperation("网页授权  通过code换取身份信息    {code   phone 手机号}")
    public ResponseVO webAuthen(@RequestBody AuthenRequestDTO authenRequestDTO) {

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatConfig.getAppId() + "&secret=" +
                wechatConfig.getAppSecret() + "&code=" + authenRequestDTO.getCode() + "&grant_type=authorization_code";
        ResponseEntity<AuthenTokenVO> response = restTemplateConfig.restTemplate()
                .exchange(url, HttpMethod.GET, null, AuthenTokenVO.class);
        AuthenTokenVO authenTokenVO = response.getBody();


        //通过openId从库里查询
        StudentDO user = studentMapper.selectOne(new QueryWrapper<StudentDO>()
                .lambda()
                .eq(StudentDO::getOpenid,authenTokenVO.getOpenid()));

        if (null==user){
            String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + authenTokenVO.getAccess_token() + "&openid=" + authenTokenVO.getOpenid() + "&lang=zh_CN";

            ResponseEntity<AuthenTokenVO> response1 = restTemplateConfig.restTemplate()
                    .exchange(url1, HttpMethod.GET, null, AuthenTokenVO.class);
            return ResponseData.generateCreatedResponse(0,response1.getBody());
        }else {
//            //该openId已存在,查出该用户的角色信息
//
//            List<UserInfoVO> userInfoVOS = new ArrayList<>();
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id",user.getId());
//            queryWrapper.eq("role_type","学生");
//            List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
//            for (UserRole userRole : userRoles){
//                UserInfoVO userInfoVO = new UserInfoVO();
//                BeanUtils.copyProperties(userRole,userInfoVO);
//                ClassesDict classesDict = classesDictMapper.selectById(userRole.getClassesId());
//                userInfoVO.setSchool(classesDict.getSchool());
//                userInfoVO.setGrade(classesDict.getGrade());
//                userInfoVO.setClasses(classesDict.getClasses());
//                userInfoVO.setSession(classesDict.getSession());
//                userInfoVO.setSubjectType(classesDict.getSubjectType());
//                userInfoVOS.add(userInfoVO);
//            }
            return null;
        }
    }

}