WechatController.java 6.67 KB
package com.subsidy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.subsidy.common.ResponseData;
import com.subsidy.common.ResponseVO;
import com.subsidy.common.configure.RestTemplateConfig;
import com.subsidy.common.configure.WechatConfig;
import com.subsidy.dto.wechat.SignVO;
import com.subsidy.mapper.AccessTokenMapper;
import com.subsidy.mapper.MemberMapper;
import com.subsidy.model.AccessTokenDO;
import com.subsidy.model.MemberDO;
import com.subsidy.util.ConstantUtils;
import com.subsidy.util.JwtUtil;
import com.subsidy.util.Localstorage;
import com.subsidy.util.SecretUtils;
import com.subsidy.vo.administer.UserRoleVO;
import com.subsidy.vo.wechat.AccessToken;
import com.subsidy.vo.wechat.AuthenRequestVO;
import com.subsidy.vo.wechat.AuthenTokenVO;
import com.subsidy.vo.wechat.JsSdkVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
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.time.temporal.ChronoUnit;
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 MemberMapper memberMapper;

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

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

        String accessToken = "";
        if (accessTokens.size() == 0) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wechatConfig.getAppId() + "&secret=" + wechatConfig.getAppSecret();
            ResponseEntity<AccessToken> response = restTemplateConfig.restTemplate()
                    .exchange(url, HttpMethod.GET, null, AccessToken.class);
            accessToken = response.getBody().getAccess_token();
            AccessTokenDO accessToken1 = new AccessTokenDO();
            accessToken1.setAccessToken(accessToken);
            accessTokenMapper.insert(accessToken1);
        } else {
            AccessTokenDO accessToken1 = accessTokens.get(0);
            long diff = ChronoUnit.SECONDS.between(accessToken1.getCreateDate(), LocalDateTime.now());
            if (diff >= 2 * 60 * 60 * 1000 - 5 * 1000) {
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wechatConfig.getAppId() + "&secret=" + wechatConfig.getAppSecret();
                ResponseEntity<AccessToken> response = restTemplateConfig.restTemplate()
                        .exchange(url, HttpMethod.GET, null, AccessToken.class);
                accessToken = response.getBody().getAccess_token();
//                AccessToken accessToken2= new AccessToken();
                accessToken1.setAccessToken(accessToken);
                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<JsSdkVO> response1 = restTemplateConfig.restTemplate()
                .exchange(url1, HttpMethod.GET, null, JsSdkVO.class);
        String ticket = response1.getBody().getTicket();
        signVO.setJsapi_ticket(ticket);
        signVO.setNoncestr("1rtgtafNdHhxADMD");
        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));
        return ResponseData.generateCreatedResponse(0, signVO);
    }


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

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


        //通过openId从库里查询
        MemberDO memberDO = memberMapper.selectOne(new QueryWrapper<MemberDO>()
                .lambda()
                .eq(MemberDO::getOpenId, authenTokenVO.getOpenid()));

        if (null == memberDO) {
            UserRoleVO userRoleVO = new UserRoleVO();

            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);
            userRoleVO.setOpenId(response1.getBody().getOpenid());
            userRoleVO.setOpenIdFlag(false);
            return ResponseData.generateCreatedResponse(0, userRoleVO);
        } else {
            //该openId已存在,查出该用户的角色信息
            UserRoleVO userRoleVO = new UserRoleVO();

            String token = JwtUtil.generateToken(memberDO.getId(), ConstantUtils.MOBILE_TERMINATE);
            Localstorage.setUser(memberDO);
            userRoleVO.setToken(token);
            BeanUtils.copyProperties(memberDO, userRoleVO);
            userRoleVO.setOpenIdFlag(true);
            userRoleVO.setOpenId(authenRequestVO.getOpenId());
            return ResponseData.generateCreatedResponse(0, userRoleVO);
        }
    }

    public static void main(String[] args) throws Exception {
        LocalDateTime now1 = LocalDateTime.now();
        Thread.sleep(2560);
        LocalDateTime now2 = LocalDateTime.now();
        System.out.println(ChronoUnit.SECONDS.between(now1, now2));

    }

}