一、生成微信小程序二维码
微信官网API文档
1.下载到本地
@Override
public String getWxRemovalCode() {
String appId = "微信小程序AppID";
String secret = "微信小程序AppSecret";
//获取凭证
String token = weiXinService.getAccessToken(appId, secret);
Map<String, Object> params = new HashMap<>();
//前端页面需要的数据
params.put("scene", value);
//扫码后进入小程序的页面位置
params.put("page", "https://argentian.com.cn/home/home");
//不是必须,需要的宽度,默认430x430,最小280最大1280
params.put("width", 280);
//默认是false,是否需要透明底色,为 true 时,生成透明底色的小程序
params.put("is_hyaline", true);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);//必须是json模式的 post
StringEntity entity = null;
try {
InputStream inputStream = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
inputStream = response.getEntity().getContent();
String path = "D:\\\\picture\\wx";//文件路径
//生成图片文件
File file = new File(path);
//如果文件夹不存在就创建文件夹
if (!file.exists()) {
file.mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(file + "\\文件名");
int len = 0;
byte[] buffer = new byte[8192];
while ((len = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
os.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
return "生成失败";
}
} catch (Exception e) {
e.printStackTrace();
return "生成失败";
}
}
return "生成微信小程序二维码成功";
}
2.存到图片服务器(实例:阿里云图片服务器)
@Override
public String getWxRemovalCode() {
String appId = "微信小程序AppID";
String secret = "微信小程序AppSecret";
//获取凭证
String token = weiXinService.getAccessToken(appId, secret);
Map<String, Object> params = new HashMap<>();
//前端页面需要的数据
params.put("scene", value);
//扫码后进入小程序的页面位置
params.put("page", "https://argentian.com.cn/home/home");
//不是必须,需要的宽度,默认430x430,最小280最大1280
params.put("width", 280);
//默认是false,是否需要透明底色,为 true 时,生成透明底色的小程序
params.put("is_hyaline", true);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);//必须是json模式的 post
StringEntity entity = null;
try {
InputStream inputStream = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
inputStream = response.getEntity().getContent();
Date date = new Date();
Long timestamp = date.getTime();
String fileName = timestamp.toString() + ".png";//文件名
//生成图片文件
File file = new File(fileName );
OutputStream os = null;
try {
os = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[8192];
while ((len = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} finally {
os.close();
inputStream.close();
}
//转成文件格式
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
MediaType.ALL_VALUE, true, file.getName());
try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
IOUtils.copy(input, os);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
//调用阿里云静态方法上传到阿里云服务器并返回图片地址
String url = FileUpload.aliyunUpload(multipartFile);
return url;
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return "操作失败";
}
public static String aliyunUpload(MultipartFile myFile) {
// 上传路径
String dateString = DateUtil.getDate(new Date(), DateUtil.YYYYMMDD);
String oldFileName = myFile.getOriginalFilename();
if(!oldFileName.contains(".")){
oldFileName=myFile.getName();
}
String objectName = dateString + SLASH + UUID.randomUUID().toString().replaceAll("-", "") +
oldFileName.substring(oldFileName.lastIndexOf("."));
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = myFile.getInputStream();
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType("image/jpg");
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream, meta);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//访问图片路径
String urlPrefix = "argentian";//前缀
return urlPrefix + objectName;
}
二、生成支付宝小程序二维码
支付宝官方API文档
@Override
public String getZfbRemovalCode(HttpServletResponse response2) {
String appId = "支付宝小程序appId";
String privateKey = "应用私钥";
String alipayPublicKey = "支付宝公钥";
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
appId, privateKey, "json", "UTF-8", alipayPublicKey, "RSA2");
AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
model.setUrlParam("/pages/home/home");
model.setDescribe("小程序二维码");
//自定义数据 key=value
model.setQueryParam("key=" + value);
request.setBizModel(model);
AlipayOpenAppQrcodeCreateResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
//获取响应数据里面的蓝底圆码链接地址
String url = response.getQrCodeUrlCircleBlue();
//将普通下载到本地指定文件夹下
String imageUrl = downloadWithUrl(url, response2);
//裁剪图片(生成的二维码下放有 “打开支付宝[扫一扫]” 文字描述,将文字描述裁剪掉)
cutOutImage(imageUrl, "裁剪后本地存放路径","裁剪后文件名" , 14, 14, 270, 270);
}
} catch (AlipayApiException e) {
log.error("AlipayApiException:", e);
} catch (Exception e) {
log.error("AdminException:", e);
}
}
return "生成支付宝二维码成功";
}
/**
* 通过URL下载文件
*/
public String downloadWithUrl(String path, HttpServletResponse response) throws IOException {
//设置响应参数
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
//response.setHeader("Content-Disposition", " attachment; filename=" + fileName);//使用此会导致中文变“_”下划线
response.setHeader("Content-Disposition", " attachment; filename=" + new String(fileName.getBytes(), "iso-8859-1"));
InputStream is = null;
OutputStream os = null;;
String filePath = "";//文件路径
//生成图片文件
File file = new File(filePath );
if (!file.exists()) {
file.mkdirs();
}
try {
//创建数据流,执行下载
URL url = new URL(path);
is = url.openStream();
os = new FileOutputStream(file + "\\文件名");
byte[] bytes = IOUtils.toByteArray(is);
os.write(bytes);
return file + "\\文件名";
} finally {
if (null != os)
os.close();
if (null != is)
is.close();
}
}
/**
* 图片裁剪
*
* @param imagePath 图片地址
* @param outputDir 临时目录
* @param name 文件名
* @param startX 裁剪起始x坐标
* @param startY 裁剪起始y坐标
* @param weight 裁剪宽度
* @param height 裁剪高度
* @throws Exception 异常
*/
public static String cutOutImage(
String imagePath,
String outputDir,
String name,
Integer startX,
Integer startY,
Integer weight,
Integer height)
throws Exception {
List<String> paths = Splitter.on(".").splitToList(imagePath);
String ext = paths.get(paths.size() - 1);
if (!Arrays.asList("png", "jpg").contains(ext)) {
throw new Exception("format error");
}
//生成文件名
String resultPath =
Joiner.on(File.separator).join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + ext));
//自定义文件名
String path = outputDir + "\\" + name;
String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
ProcessBuilder builder =
new ProcessBuilder(
ffmpeg,
"-i",
imagePath,
"-vf",
MessageFormat.format(
"crop={0}:{1}:{2}:{3}",
String.valueOf(weight),
String.valueOf(height),
String.valueOf(startX),
String.valueOf(startY)),
"-y",
path//生成文件名or自定义文件名
);
builder.inheritIO().start().waitFor();
return path;
}