[后端] 微服务添加获取&更新微信小程序access_token相关逻辑
This commit is contained in:
		@@ -0,0 +1,24 @@
 | 
			
		||||
package com.cxyxiaomo.epp.access.controller;
 | 
			
		||||
 | 
			
		||||
import com.cxyxiaomo.epp.access.service.WeChatTokenServiceImpl;
 | 
			
		||||
import com.cxyxiaomo.epp.common.response.Res;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
import org.springframework.stereotype.Controller;
 | 
			
		||||
import org.springframework.web.bind.annotation.GetMapping;
 | 
			
		||||
import org.springframework.web.bind.annotation.RequestMapping;
 | 
			
		||||
import org.springframework.web.bind.annotation.ResponseBody;
 | 
			
		||||
 | 
			
		||||
@Controller
 | 
			
		||||
@RequestMapping("/access/wechat")
 | 
			
		||||
public class WeChatTokenController {
 | 
			
		||||
 | 
			
		||||
    @Autowired
 | 
			
		||||
    private WeChatTokenServiceImpl weChatTokenService;
 | 
			
		||||
 | 
			
		||||
    @GetMapping("/getAccessToken")
 | 
			
		||||
    @ResponseBody
 | 
			
		||||
    public Res getAccessToken() {
 | 
			
		||||
        String accessToken = weChatTokenService.getAccessToken();
 | 
			
		||||
        return Res.success(accessToken);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,10 +1,13 @@
 | 
			
		||||
package com.cxyxiaomo.epp.access.dao;
 | 
			
		||||
 | 
			
		||||
import com.cxyxiaomo.epp.common.pojo.Setting;
 | 
			
		||||
import org.apache.ibatis.annotations.Mapper;
 | 
			
		||||
import org.springframework.stereotype.Repository;
 | 
			
		||||
 | 
			
		||||
@Mapper
 | 
			
		||||
@Repository
 | 
			
		||||
public interface AccessDao {
 | 
			
		||||
    Integer updateSetting(Setting setting);
 | 
			
		||||
 | 
			
		||||
    Setting getValueByKey(String key);
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -0,0 +1,5 @@
 | 
			
		||||
package com.cxyxiaomo.epp.access.service;
 | 
			
		||||
 | 
			
		||||
public interface WeChatTokenService {
 | 
			
		||||
    String getAccessToken();
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,84 @@
 | 
			
		||||
package com.cxyxiaomo.epp.access.service;
 | 
			
		||||
 | 
			
		||||
import com.alibaba.fastjson2.JSONObject;
 | 
			
		||||
import com.cxyxiaomo.epp.access.dao.AccessDao;
 | 
			
		||||
import com.cxyxiaomo.epp.access.utils.RestUtil;
 | 
			
		||||
import com.cxyxiaomo.epp.common.pojo.Setting;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
import org.springframework.http.HttpHeaders;
 | 
			
		||||
import org.springframework.stereotype.Service;
 | 
			
		||||
 | 
			
		||||
import java.time.LocalDateTime;
 | 
			
		||||
 | 
			
		||||
@Service
 | 
			
		||||
public class WeChatTokenServiceImpl implements WeChatTokenService {
 | 
			
		||||
 | 
			
		||||
    @Autowired
 | 
			
		||||
    AccessDao accessDao;
 | 
			
		||||
 | 
			
		||||
    // 数据库中该 key 保存的 time 是失效时间
 | 
			
		||||
    final String SETTING_KEY = "wechat_access_token";
 | 
			
		||||
 | 
			
		||||
    // 小程序信息
 | 
			
		||||
    final String APPID = "wxa70348746d2b562f";
 | 
			
		||||
    final String APPSECRET = "7da57703136fefb0584a5a6ab1aca152";
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public String getAccessToken() {
 | 
			
		||||
        // 首先从数据库中查询是否存在 access_token
 | 
			
		||||
        // 如果存在且没有过期,那么就直接返回(距离失效时间小于 3 分钟就当作过期)
 | 
			
		||||
        Setting atSetting = accessDao.getValueByKey(SETTING_KEY);
 | 
			
		||||
        if (atSetting != null && LocalDateTime.now().plusMinutes(3L).compareTo(atSetting.getTime()) < 0) {
 | 
			
		||||
            return atSetting.getValue();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 否则则去请求一个新的 access_token
 | 
			
		||||
        JSONObject jsonObject = getAccessTokenFromApi();
 | 
			
		||||
        String access_token = jsonObject.getString("access_token");
 | 
			
		||||
        Integer expires_in = jsonObject.getInteger("expires_in");
 | 
			
		||||
 | 
			
		||||
        // 如果请求成功,那么更新数据库中的记录
 | 
			
		||||
        if (access_token != null) {
 | 
			
		||||
            Setting setting = new Setting();
 | 
			
		||||
            setting.setKey(SETTING_KEY);
 | 
			
		||||
            setting.setValue(access_token);
 | 
			
		||||
            setting.setTime(LocalDateTime.now().plusSeconds(expires_in));
 | 
			
		||||
            accessDao.updateSetting(setting);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        return access_token;
 | 
			
		||||
 | 
			
		||||
        // Map<String, Object> map = new HashMap<>();
 | 
			
		||||
        // map.put("raw", jsonObject);
 | 
			
		||||
        // if (access_token == null) {
 | 
			
		||||
        //     // 获取失败
 | 
			
		||||
        //     Integer errcode = jsonObject.getInteger("errcode");
 | 
			
		||||
        //     String errmsg = jsonObject.getString("errmsg");
 | 
			
		||||
        //     map.put("errcode", errcode);
 | 
			
		||||
        //     map.put("errmsg", errmsg);
 | 
			
		||||
        // } else {
 | 
			
		||||
        //     // 获取成功
 | 
			
		||||
        //     map.put("access_token", access_token);
 | 
			
		||||
        //     map.put("expires_in", expires_in);
 | 
			
		||||
        // }
 | 
			
		||||
        // return map;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private JSONObject getAccessTokenFromApi() {
 | 
			
		||||
        // refer: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
 | 
			
		||||
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APPSECRET);
 | 
			
		||||
 | 
			
		||||
        HttpHeaders headers = new HttpHeaders();
 | 
			
		||||
        // headers.set("Authorization", "Token " + this.accessToken);
 | 
			
		||||
 | 
			
		||||
        String jsonStr = RestUtil.doGetRequest(url, headers);
 | 
			
		||||
        return JSONObject.parseObject(jsonStr);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
/*
 | 
			
		||||
{
 | 
			
		||||
    "success": true,
 | 
			
		||||
    "msg": "操作成功",
 | 
			
		||||
    "data": "{\"access_token\":\"63_ez5i6A4ib1-kwi-g6n_3LLqdthenpZGIHTs1tXXcYqia8mnntJlTc_Mkl8CtuiXx0oplHbEVXrkVycvNwkyXhbA2Yj5K1kCan-AjOjH_-zaleYfg-S3zDWO9uoUQWVbACALRQ\",\"expires_in\":7200}"
 | 
			
		||||
}
 | 
			
		||||
*/
 | 
			
		||||
@@ -0,0 +1,23 @@
 | 
			
		||||
package com.cxyxiaomo.epp.access.utils;
 | 
			
		||||
 | 
			
		||||
import org.springframework.http.HttpEntity;
 | 
			
		||||
import org.springframework.http.HttpHeaders;
 | 
			
		||||
import org.springframework.http.HttpMethod;
 | 
			
		||||
import org.springframework.http.ResponseEntity;
 | 
			
		||||
import org.springframework.web.client.RestTemplate;
 | 
			
		||||
 | 
			
		||||
public class RestUtil {
 | 
			
		||||
    private RestUtil() {
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static String doGetRequest(String url, HttpHeaders headers) {
 | 
			
		||||
 | 
			
		||||
        RestTemplate client = new RestTemplate();
 | 
			
		||||
        HttpMethod method = HttpMethod.GET;
 | 
			
		||||
        HttpEntity<String> requestEntity = new HttpEntity<String>("parameters", headers);
 | 
			
		||||
 | 
			
		||||
        // 执行HTTP请求,将返回的结构使用String类格式化
 | 
			
		||||
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
 | 
			
		||||
        return response.getBody();
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -3,5 +3,14 @@
 | 
			
		||||
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 | 
			
		||||
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 | 
			
		||||
<mapper namespace="com.cxyxiaomo.epp.access.dao.AccessDao">
 | 
			
		||||
 | 
			
		||||
    <insert id="updateSetting" parameterType="com.cxyxiaomo.epp.common.pojo.Setting">
 | 
			
		||||
        INSERT INTO setting (`key`, `value`, `time`)
 | 
			
		||||
        VALUES (#{key}, #{value}, #{time})
 | 
			
		||||
        ON DUPLICATE KEY UPDATE
 | 
			
		||||
        `value` = VALUES(`value`), `time` = VALUES(`time`)
 | 
			
		||||
    </insert>
 | 
			
		||||
    <select id="getValueByKey" parameterType="java.lang.String" resultType="com.cxyxiaomo.epp.common.pojo.Setting">
 | 
			
		||||
        SELECT * FROM setting
 | 
			
		||||
        WHERE `key` = #{key}
 | 
			
		||||
    </select>
 | 
			
		||||
</mapper>
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user