java生成跳转小程序的二维码
学习内容:
主要是实现跳转小程序的二维码,
主要分为两步,第一步:接口接口调用凭证 access_token
第二步:获取小程序码,并上传oss, 获取小程序码
-
获取不限制的小程序码
微信官方文档https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html -
代码实现
@Slf4j
public class CreateQrCode {
//这是微信小程序的APP_ID,APP_SECRET
private static String APP_ID = "";
private static String APP_SECRET = "";
/**
* 接口调用凭证 access_token
*/
public static String postToken() throws Exception {
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
URL url = new URL(requestUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("");
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in;
if (requestUrl.contains("nlp"))
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
else
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String getLine;
while ((getLine = in.readLine()) != null) {
result.append(getLine);
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(result.toString());
return jsonObject.getString("access_token");
}
/**
* 获取小程序码,并上传oss, 获取小程序码 B 暂时无限
* @param query
* @param path
* @return
*/
public static String getQrCode(Map<String,Object> query, String path) throws Exception {
return getQrCode(postToken(), query, path);
}
public static String getQrCode(String token, Map<String,Object> query, String path) throws Exception {
String id = String.valueOf(query.getOrDefault("id","0"));
String type = String.valueOf(query.getOrDefault("t",""));
// 预览id. 活动二维码.
String pid = String.valueOf(query.getOrDefault("pid","0"));
String tenantId = String.valueOf(query.getOrDefault("tenantId","0"));
/** 注意:scene参数必须小于32位,且无中文,所以只保留id与type的缩写 */
Map<String,Object> params = new HashMap<>();
params.put("id",id);
// pid不为默认则说明有值.
if (!ObjectUtil.equal(pid, "0")){
params.put("pid",pid);
}
//params.put("auto_color", true);
String queryStr = HttpUtil.toParams(params);
if (queryStr.length() > 32){
log.error("小程序二维码参数过长 参数:{}", queryStr);
}
String url = "";
GetwxacodeunlimitReq getwxacodeunlimit = new GetwxacodeunlimitReq();
// 增加二维码链入小程序环境的区分. 要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
// 如果是测试环境,生成体验版小程序
//getwxacodeunlimit.setEnv_version("trial");
getwxacodeunlimit.setEnv_version("trial");
getwxacodeunlimit.setPage(path);
getwxacodeunlimit.setScene(queryStr);
// 调用接口,获取小程序image
BufferedImage bufferedImage = WxaAPI.getwxacodeunlimit(token, getwxacodeunlimit);
if (bufferedImage != null) {
// 上传oss.获取到二维码oss链接.并返回
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
// 把文件加上随机数,防止文件重复
String uuid = IdUtil.randomUUID().replace("-", "").toLowerCase();
StringBuffer fileName = new StringBuffer(uuid).append(".").append("qiaotong");
//url = OssClientUtil.putObject(is, fileName.toString());
url= OSSUtil.uploadFileInputStream(is);
log.info("生成小程序二维码, 条件参数:{}, url:{}", queryStr, url);
} catch (FileNotFoundException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
} else {
log.error("小程序码获取失败.条件参数:{}", queryStr);
}
return url;
}
}