//微信获取token 生成小程序二维码
@RequestMapping("/cs/getQrcode")
public @ResponseBody
Map<String, Object> getWxaqrcode(HttpServletRequest request, HttpServletResponse response, int id, int width) {
log.info("======> /cs/getQrcode");
Map<String, Object> Token = getaccessToken();
String path="pages/cs";
byte[] qrcode=getWxaCreateQrcode(Token.get("accessToken").toString(),path,width,"?id="+id);
String ewm_qrcode=base64StringToImage(qrcode);
map.put("qrcodeAddr",ewm_qrcode);
return map;
}
//数量无限制接口
public static final String unlimit= "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
private final static String wxappid = "你自己的id";
private final static String wxappsecret = "你自己的密码";
public byte[] getWxaCreateQrcode(String accesstoken,String path,int width,String scene){
net.sf.json.JSONObject jsonObject= new net.sf.json.JSONObject();
jsonObject.put("width",width);
jsonObject.put("page",path);
//二维码里传递参数
jsonObject.put("scene",scene);
org.apache.http.client.HttpClient client = HttpClients.createDefault();
String url = unlimit+"?access_token="+accesstoken;
HttpPost post = new HttpPost(url);
byte[] result = null;
try {
// 设置通用属性
StringEntity s = new StringEntity(jsonObject.toString(),"UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
// 设置发送的数据(数据尽量为json格式)
post.setEntity(s);
post.addHeader("content-type", "application/json;charset=UTF-8");
// 获取数据
HttpResponse res = client.execute(post);
// 判断网络请求的是否成功,成功的状态码为200
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// HttpEntity为消息实体,内容是http传送的报文,获取数据
HttpEntity entity = res.getEntity();
result=EntityUtils.toByteArray(entity);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
// 释放连接
post.releaseConnection();
}
return result;
}
/**
* 获取小程序接口调用凭据
* */
public Map<String, Object> getAccessToken() {
Map<String, Object> ReturnMap=new HashMap<String,Object>();
Map<String, Object> Cache_Token=new HashMap<String,Object>();
Map<String,Object> Database_Token=new HashMap<String,Object>();
String mapKey=wxappid+wxappsecret;
long token_id=0;
try{
Cache_Token= WxTokenMapManager.getWxToken(mapKey);
if(Cache_Token==null)
Cache_Token=new HashMap<String,Object>();
if(isAccessTokenExpired(Cache_Token)){
int updatetime=0;
while(true){
if(updatetime<10 &&(isAccessTokenExpired(Cache_Token) || isDbTokenExpired(Cache_Token,Database_Token))){
updatetime++;
//调用获取token
String requestUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxappid+ "&secret=" + wxappsecret;
net.sf.json.JSONObject jsonObject = null;
log.info("requestUrl"+requestUrl);
try {
jsonObject = httpRequest(requestUrl, "GET", null);
} catch (Exception e) {
log.info("getAccessToken[Error]::[通讯异常]:["+e.getMessage()+"]["+requestUrl+"]");
return Cache_Token;
}
// 如果请求成功
if (null != jsonObject) {
try {
log.info(jsonObject.toString());
Cache_Token.put("accessToken", jsonObject.getString("access_token"));
Cache_Token.put("expiresIn", jsonObject.getInt("expires_in"));
Cache_Token.put("validTime", jsonObject.getInt("expires_in")*1000+System.currentTimeMillis());
Cache_Token.put("errorToken", null);
WxTokenMapManager.updateWxToken(mapKey,Cache_Token);
} catch (JSONException e){
log.info("getAccessToken[Error]::[接口错误码读取异常]");
}
}else{//jsonObject==null
log.info("getAccessToken[Error]::[接口读取异常]:["+jsonObject+"]["+requestUrl+"]");
}
break;
}
else
{//数据库中正确
Cache_Token.put("accessToken", Database_Token.get("accessToken").toString());
Cache_Token.put("expiresIn", Database_Token.get("expiresIn").toString());
Cache_Token.put("validTime", Database_Token.get("validTime").toString());
Cache_Token.put("errorToken", null);
WxTokenMapManager.updateWxToken(mapKey, Cache_Token);
break;
}
}
}
}catch(Exception e){
log.info("getAccessToken[Error]::[操作异常]:["+e.getMessage()+"]["+Cache_Token+"]["+Database_Token+"]");
return Cache_Token;
}
ReturnMap=Cache_Token;
return ReturnMap;
}
/**
* 判断缓存accesstoken过期
*/
public boolean isAccessTokenExpired(Map<String, Object> params){
return (params.get("validTime")==null ||
(Long.parseLong(params.get("validTime").toString())-System.currentTimeMillis()<=20000) ||
params.get("errorToken")!=null);
}
/**
* 判断数据库中accesstoken过期
*/
public boolean isDbTokenExpired(Map<String, Object> catch_params , Map<String, Object> db_params){
return (db_params == null ||
(catch_params.get("errorToken")!=null && db_params.get("accessToken")!=null &&
catch_params.get("errorToken").toString().equals(db_params.get("accessToken").toString())));
}
java后台微信获取验证token 生成没有数量限制的小程序二维码
最新推荐文章于 2024-10-14 15:50:22 发布