Java生成微信小程序碼
官網文檔地址:獲取小程序碼
package test;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
/**
* @description:
* @author: Mr.Fang
* @create: 2023-04-03 17:06
**/
public class WxUtils {
/**
* description: 獲取token,返回結果為 JSON 自行轉 map
* create by: Mr.Fang
*
* @return: java.lang.String
* @date: 2023/4/3 17:46
*/
public String getToken() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", "appid");
params.put("secret", "secret");
params.put("grant_type", "client_credential");
String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
/**
* description: 對象轉 字符串
* create by: Mr.Fang
*
* @param obj
* @return: java.lang.String
* @date: 2023/4/3 17:45
*/
public String objToStr(Object obj) {
ObjectMapper objectMapper = new ObjectMapper();
if (Objects.nonNull(obj)) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return null;
}
/**
* description: 字符串 轉 對象轉
* create by: Mr.Fang
*
* @param jsonStr
* @param objClass
* @return: java.lang.String
* @date: 2023/4/3 17:45
*/
public <T> T strToObj(String jsonStr, Class<T> objClass) {
ObjectMapper objectMapper = new ObjectMapper();
try {
T t = objectMapper.readValue(jsonStr, objClass);
return t;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* description: 生成小程序碼
* create by: Mr.Fang
*
* @param scene 攜帶參數
* @param page 頁面路徑
* @param token token
* @param path 保存路徑
* @return: java.lang.String
* @date: 2023/5/11 14:22
*/
public String appletQR(String scene, String page, String token, String path) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("scene", scene);
params.put("page", page); //developer為開發版;trial為體驗版;formal為正式版;默認為正式版
params.put("env_version", "develop"); //要打開的小程序版本。正式版為 "release",體驗版為 "trial",開發版為 "develop"。默認是正式版。
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
httpPost.addHeader("ContentTyp", "application/json");
// 參數轉 JSON 格式
String json = objToStr(params);
StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
stringEntity.setContentEncoding(CharSetType.UTF8.getType());
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 響應結果
byte[] data;
try {
data = readInputStream(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (data.length < 100) { // 異常
String error = new String(data);
return null;
}
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
String filePath = path + File.separator + fileName;
// 創建文件
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(data);
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
// 釋放資源
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
/**
* description: 輸入流轉字節數組
* create by: Mr.Fang
*
* @param inStream 輸入流
* @return: byte[]
* @date: 2023/5/11 11:52
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 創建一個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里的數據寫入內存
return outStream.toByteArray();
}
public static void main(String[] args) throws IOException {
WxUtils wxUtils = new WxUtils();
// 獲取 token
String token = wxUtils.getToken();
// 字符串轉 map 對象
Map map = wxUtils.strToObj(token, Map.class);
// 生成小程序碼
String path = wxUtils.appletQR("2023", "pages/index/index", map.get("access_token").toString(), System.getProperty("user.dir") + File.separator);
System.out.println(path);
}
}
項目根目錄生成小程序碼

哇!又賺了一天人民幣

浙公網安備 33010602011771號