1.登录微信公众平台,在基本配置里获取AppId和AppSecret
2.获取token(token获取到存本地,后续API都要带token访问)
需要在基本配置里配置ip白名单才能获取到token
/** TokenURL */
private final static String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
/** APP_ID */
private final static String APP_ID = "wx1234567891011121";
/** APP_SECRET */
private final static String APP_SECRET = "123qgs4vg5yt67vsf8r9bri1011j1i2b";
/**
* 获取token,默认7200秒过期,所以存redis7200秒取一次
*
* @return 获取用户详情
*/
public String getToken() {
String redisKey = "Tencent:AccessToken";
String token = (String)redisUtils.get(redisKey);
if(ObjectUtils.isEmpty(token)){
token = tencentService.getToken();
//设置缓存 2小时
redisUtils.setEx(redisKey,token, 7200, TimeUnit.SECONDS);
}
return token;
}
//tencentService.getToken();
@Override
public String getToken(){
try {
HttpClient client = HttpClients.createDefault();
String tokenUrl = MessageFormat.format(GET_TOKEN_URL, APP_ID, APP_SECRET);
HttpGet request = new HttpGet(tokenUrl);
HttpResponse response = client.execute(request);
JSONObject object = getResponseJson(response);
if (object == null) {
return null;
}
return ObjectUtils.isEmpty(object) ? null : object.getString("access_token");
}catch (Exception e){ log.info(e.getMessage()); }
return null;
}
//getResponseJson();
private static JSONObject getResponseJson(HttpResponse response) throws IOException {
JSONObject json = null;
HttpEntity entity = response.getEntity();
if(entity!=null){
String result = EntityUtils.toString(entity,"UTF-8");
json = JSONObject.parseObject(result);
}
if(ObjectUtils.isEmpty(json)){
return null;
}
return json;
}
//可能用到的包
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;