package com.care.client.service; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.care.client.config.PlatformPinanbaoConfig; import com.care.client.config.WxConfig; import com.care.client.vo.MemberInitParams; import com.care.common.cache.RedisKeyConstant; import com.care.common.cache.RedisUtil; import com.care.common.util.Result; import com.google.gson.Gson; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.text.MessageFormat; @Slf4j @Service public class WxPassportService extends AbstractPassportService { @Resource private RedisUtil redisUtil; @Resource private PlatformPinanbaoConfig platformPinanbaoConfig; Gson gson = new Gson(); public Result login(MemberInitParams params) { WxConfig wxConfig = platformPinanbaoConfig.wxConfig(); // 解析codeUrl String codeUrl = MessageFormat.format(wxConfig.getCodeUrl(), wxConfig.getAppId(), wxConfig.getSecret(), params.getCode()); // 通过codeUrl获取openid JSONObject jsonObject = this.httpGet(codeUrl); log.warn("-----jsonObject:[{}]", jsonObject); String openid = jsonObject.getStr("openid"); String sessionKey = jsonObject.getStr("session_key"); // TODO 暂时用不到 log.warn("-----openid:[{}], session_key:[{}]", openid, sessionKey); // TODO 测试阶段先注释掉 params.setOpenid(openid); return cache(params); } private JSONObject httpGet(String url) { HttpResponse response = HttpRequest.get(url).execute(); String json = response.charset("utf-8").body(); JSONObject jsonObject = JSONUtil.parseObj(json); return jsonObject; } private String accessToken() { WxConfig wxConfig = platformPinanbaoConfig.wxConfig(); String access_token = (String) redisUtil.hget(RedisKeyConstant.WX_ACCESS_TOKEN, wxConfig.getAppId()); if (access_token != null) { return access_token; } return this.flushWxToken(); } private String flushWxToken() { WxConfig wxConfig = platformPinanbaoConfig.wxConfig(); // 解析codeUrl String tokenUrl = MessageFormat.format(wxConfig.getTokenUrl(), wxConfig.getAppId(), wxConfig.getSecret()); // 通过codeUrl获取openid JSONObject jsonObject = this.httpGet(tokenUrl); String access_token = jsonObject.getStr("access_token"); redisUtil.hset(RedisKeyConstant.WX_ACCESS_TOKEN, wxConfig.getAppId(), access_token, RedisKeyConstant.WX_ACCESS_TOKEN_TIME); return access_token; } }