一、服务器后台请求微信获取accessToken
Token两个小时以内都属于有效token,一天可从微信获取的token次数为两千次,所以最好是第一次获取token保存,每次获取token前先查询数据库保存的token是否失效,未失效直接调用,失效重新获取,更新本地token。
//获取accessToken
public static Token getToken() throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, MalformedURLException, UnsupportedEncodingException, IOException, ProtocolException {
String accessToken = null;
String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
Token token = new Token();
long expiresIn = 0;
Map
String requestUrl = token_url.replace("APPID", APP_ID).replace("APPSECRET", APP_SECRET);
// 发起GET请求获取凭证
StringBuffer SubmitResult = httpsRequest(requestUrl, "GET", null, false);
try {
JSONObject jsonObject = JSONObject.fromObject(SubmitResult.toString());
accessToken = jsonObject.getString("access_token");
expiresIn = jsonObject.getInt("expires_in");
token.setAccessToken(accessToken);
token.setExpiresIn(expiresIn);
//token.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (Exception e) {
// 获取token失败
//log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
return token;
}
//获取token的Controller
@RequestMapping(value = "/getCodeAccessToken", method=RequestMethod.POST)
public void getCodeAccessToken(HttpServletResponse response){
try {
Token token = tokenService.getLocalToken();
if(token == null || token.equals("")){
Token t = new Token();
t = WeChatUtil.getToken();
t.setId(FileTool.getUUID());
t.setCreateTime(System.currentTimeMillis());
tokenService.insertToken(t);
render(t.getAccessToken(), response);
}else{
long loseTime = token.getExpiresIn();
long createTime = token.getCreateTime();
long time = System.currentTimeMillis();
if ((time-createTime)/1000 < loseTime) {
render(token.getAccessToken(), response);
}else{
tokenService.deleteById(token.getId());
Token t = new Token();
t = WeChatUtil.getToken();
t.setId(FileTool.getUUID());
t.setCreateTime(System.currentTimeMillis());
tokenService.insertToken(t);
render(t.getAccessToken(), response);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//http请求工具类
private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output,boolean needCert)
throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
IOException, ProtocolException, UnsupportedEncodingException {
URL url = new URL(requestUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//是否需要数字证书
if(needCert){
//设置数字证书
setCert(connection);
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestMethod);
if (null != output) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(output.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
connection.disconnect();
return buffer;
}
//token实体类
public class Token {
private String id;
private String accessToken; // access_token
private long expiresIn; // expiresin
private long createTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(long expiresIn) {
this.expiresIn = expiresIn;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
二、小程序前端js
js源码:
wx.request({
url: app.globalData.url + "getCodeAccessToken.do", //请求服务器后台获取accessToken
data: {
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
console.log(res);
that.setData({
token:res.data //后台返回的accessToken
})
wx.request({
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='+that.data.token, //获取小程序B接口二维码
method: "POST",
responseType: 'arraybuffer', //这一行非常重要,重中之重
data: {
scene:'22a45fds' ,
page: "pages/login/login",
width: 280,
is_hyaline: true
},
header: {
'content-type': 'application/json;charset=utf-8'
},
success(res) {
console.log(res.data);
var base64 = wx.arrayBufferToBase64(res.data);
that.setData({ imgurl:"data:image/PNG;base64,"+ base64})
}
})
},
fail: function (res) {
},
complete: function (res) { },
})
wxml标签: