Blame view

WechatController.java 6.67 KB
涂亚平 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
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));

    }

}