其实微信获取ticket和获取JSSDK代码是一样的这里只是做了优化。
首先是配置类
package com.kk.demo.api.settings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* @author kk
* 配置信息类
*/
@Component
@PropertySource({"classpath:config.properties"})
@ConfigurationProperties(prefix="pz")
@Data
public class Settings {
@Value("${pz.access_token_url}")
String accessTokenUrl;
@Value("${pz.appID}")
String appID;
@Value("${pz.appSecret}")
String appSecret;
@Value("${pz.ticketUrl}")
String ticketUrl;
@Value("${pz.codeUrl}")
String codeUrl;
@Value("${pz.infoUrl}")
String infoUrl;
}
http请求的工具类
package com.kk.demo.api.tool;
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.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import net.sf.json.JSONObject;
@Component
public class AuthUtil {
public JSONObject doGetJson_HttpClient(String url) {
JSONObject jsonObject = null;
HttpGet httpGet = null;
try {
// 获取DefaultHttpClient请求
HttpClient client = HttpClientBuilder.create().build();
httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(null != entity){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
// 释放连接
httpGet.releaseConnection();
}
return jsonObject;
}
}
然后就是调微信接口了,没什么好说的,在代码里添加了本地缓存微信默认是7200秒我设置的少了一些,算是
性能上的一些优化吧。
package com.kk.demo.api;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.kk.demo.api.settings.Settings;
import com.kk.demo.api.tool.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
/**
* @author kk
* 获取微信 JsSDK, ticket, access_token
*/
@Slf4j
@Component
public class WeChatVoucher {
@Autowired
Settings settings;
@Autowired
AuthUtil authUtil;
// 本地缓存
public static LoadingCache<String, String> caches = CacheBuilder
.newBuilder()
// 设置过期时间
.expireAfterWrite(7180000, TimeUnit.SECONDS)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return null;
}
});
public Map<String, String> voucher() {
Map<String, String> dataMap = Maps.newLinkedHashMap();
// 缓存access_token
String cache_access = "";
// 缓存jsapi_ticket
String cache_ticket = "";
String accessTokenUrl = settings.getAccessTokenUrl().replace("APPID", settings.getAppID())
.replace("APPSECRET", settings.getAppSecret());
// 获取access_token,并放入缓存
try {
// 有则赋值,没有则调用微信接口获取access_token在赋值
cache_access = caches.get("access_token");
} catch (Exception e) {
try {
// 发送请求,获取access_token
JSONObject accessData = authUtil.doGetJson_HttpClient(accessTokenUrl);
String access_token = accessData.getString("access_token");
// 放入缓存
caches.put("access_token", access_token);
cache_access = caches.get("access_token");
} catch (Exception e2) {
e2.printStackTrace();
}
}
log.info("cache_access{}值是:",cache_access);
//拿到了access_token 使用access_token 获取到jsapi_ticket
String ticketUrl = settings.getTicketUrl().replace("ACCESS", cache_access);
// 获取jsapi_ticket,并放入缓存
try {
// 有则赋值,没有则调用微信接口获取ticket在赋值
cache_ticket = caches.get("jsapi_ticket");
} catch (Exception e) {
try {
//调用jsapi_ticket_url 请求拿到jsapi_ticket
JSONObject ticketData = authUtil.doGetJson_HttpClient(ticketUrl);
String jsapi_ticket = ticketData.getString("ticket");
// 放入缓存
caches.put("jsapi_ticket", jsapi_ticket);
cache_ticket = caches.get("jsapi_ticket");
} catch (Exception e2) {
e2.printStackTrace();
}
}
log.info("cache_ticket{}值是:",cache_ticket);
// 返回结果
dataMap.put("ticket", cache_ticket);
dataMap.put("accessTtoken", cache_access);
log.info("返回结果{}值是:",dataMap);
return dataMap;
}
}
获取JSSD的代码我在这篇文章写了,如果有需求直接拿过来用了获取微信JSSDK
配置文件我也贴出来
#-----------------------------------------------微信相关-------------------------------------------
#获取access_token,url
pz.access_token_url=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
#使用access_token 获取到jsapi_ticket
pz.ticketUrl=https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ACCESS+"&type=jsapi";
pz.codeUrl=https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code
pz.infoUrl=https://api.weixin.qq.com/sns/userinfo?access_token=TOKEN&openid=OPENID&lang=zh_CN0
#微信的appID,appSecret换成自己的就行了
pz.appID=xxxxxx
pz.appSecret=xxxxxx
依赖一下jar
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0-jre</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
这个是springboot的项目环境,配置方面了许多