导语
在很多的场景中,需要我们在开发中生成小程序码,并且通过微信扫一扫之后可以跳转到小程序指定的页面,可以更好的增加用户体验。那么如何去实现生成小程序码的功能呢?微信官方也提供了一些文档,但是文档总归是文档,笔者结合自己的开发经历总结如下的内容。可以直接导入使用。
调用wxacode.getUnlimited 获取小程序码适用的场景是需要很多的小程序码的业务场景。通过这个接口生成的小程序码永久有效,数量暂时没有限制。
废话不多说直接上代码。
第一步 获取ACCESS_TOKEN在使用的时候记得将APPID与秘钥换成自己的APPID与秘钥。这里由于TOKEN的时效性,所以简单的使用了一个本地文件的方式做了一个缓存。是一个比较简单的操作,所以不需要用到缓存中间件等复杂操作,当然可以使用其他的例如HashMap将TOKEN放入到内存中进行缓存。为了节省内存空间,这里将TOKEN放入到外部文件中进行了简单的缓存。
@Component
public class TokenManager {
private static final long MAX_TIME = 7200 * 1000;
public synchronized String getAccessToken() {
String access_token = "";
File file = new File("access_token.json");
try {
//文件不存在,则创建文件
if (!file.exists()) {
file.createNewFile();
}
//若文件为空,则第一次访问
if (file.length() == 0) {
//获取access_token写入文件
access_token = this.get();
HashMap map = new HashMap<>();
map.put("access_token", access_token);
map.put("expires_in", System.currentTimeMillis() + "");
this.writeToken(file, map);
} else {
//从磁盘读取文件
String json = this.readToken(file);
JSONObject jsonObject = JSONObject.parseObject(json);
if (jsonObject.get("expires_in") != null) {
long saveTime = Long.parseLong((String) jsonObject.get("expires_in"));
long nowTime = System.currentTimeMillis();
long remainTime = nowTime - saveTime;
//若间隔时间小于2小时
if (remainTime < MAX_TIME) {
access_token = (String) jsonObject.get("access_token");
} else {
//若间隔时间大于等于2小时,需要刷新access_token,重新写入文件
access_token = this.get();
HashMap map = new HashMap<>();
map.put("access_token", access_token);
map.put("expires_in", System.currentTimeMillis() + "");
this.writeToken(file, map);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return access_token;
}
//手动强制刷新缓存
public String refreshAccessToken() {
File file = new File("access_token.json");
if (file.exists()) file.delete();
String newAccessToken = getAccessToken();
return newAccessToken;
}
//token持久化到磁盘
private void writeToken(File file, Map map) {
try {
FileOutputStream fos = new FileOutputStream(file, false);
String json = JSON.toJSONString(map);
fos.write(json.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//从磁盘读取token
private String readToken(File file) {
//若文件存在access_token,则读取access_token
FileInputStream fis = null;
String json = "";
try {
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
json += new String(b, 0, len);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
//发起get请求获取access_token
private String get() {
String grant_type = "client_credential";
String url = "https://api.weixin.qq.com/cgi-bin/token";
Map para = new HashMap();
para.put("grant_type", grant_type);
para.put("appId", "appID");
para.put("secret", "Secret");
String res = HttpUtil.doGet(url, para);
JSONObject jsonObject = JSONObject.parseObject(res);
String access_token = (String) jsonObject.get("access_token");
if (access_token!= null) {
return access_token;
} else {
return null;
}
}
}
第二步 编写调用Controller
@RestController
@RequestMapping("/api/qRcode")
@Api(tags = "获取小程序二维码")
public class CreateQRCodeController {
@Autowired
private TokenManager tokenManager;
@GetMapping("/createQrCode")
@ApiOperation("创建小程序二维码")
public AjaxResult createQrCode(){
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+tokenManager.getAccessToken();
JSONObject params = new JSONObject();
params.put("page","pages/news/index");
params.put("scene","a=1");
params.put("check_path",false);
params.put("env_version","trial");
HttpUtil.doPostSSLFile(url, params.toJSONString());
return AjaxResult.success();
}
}
doPostSSLFile()方法
在使用这个方法的时候需要自定义一个工具类,并且还需要引入到HTTPClient的依赖
org.apache.httpcomponents
httpcore
4.4.14
org.apache.httpcomponents
httpclient
4.5.13
Java代码部分
public static String doPostSSLFile(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
// httpStr = EntityUtils.toString(entity, "utf-8");
// System.out.println(httpStr);
InputStream content = entity.getContent();
readInputStream(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
FileOutputStream outputStream = new FileOutputStream(new File("./test.jpg"));
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
byte[] bytes = outStream.toByteArray();
outputStream.write(bytes);
outputStream.close();
return null;
}
总结
调用接口之后,就会看到在当前路径下会生成一个jpg的图片,使用微信扫一扫的功能就可以直接跳转到小程序对应的页面中。



