一、controller
@GetMapping(value="/getUnlimited")
@ApiOperation(value = "获取小程序码")
public String getUnlimited() {
try {
String filePath = "D:\\code\\";
//获取accessToken
String accessToken = miniProgramService.getAccessToken();
//生成图片
WxQrCode.getminiqrQr(accessToken,filePath);
return "hello world" ;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
二、service (获取token并生成图片) postHeadersT方法参考resttemplate那篇文章
try {
//获取token
JSONObject accessToken = wxServiceExt.getAccessToken();
String token = accessToken.get(CommonConstant.ACCESS_TOKEN).toString();
if(StringUtils.isBlank(token)){
throw new UnsupportedOperationException("获取accessToken失败!");
}
return token;
} catch (Exception e) {
log.info("获取accessToken失败,原因是"+e.getMessage());
return "";
}
/**
*
* 获取accessToken
* @return
*/
public JSONObject getAccessToken() {
String AccessToken_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;//小程序id
String resultData = postHeadersT(AccessToken_URL, getHeaders(CommonConstant.DATA_INT_1), null, HttpMethod.GET);
JSONObject parseObject = JSONObject.parseObject(resultData);
return parseObject;
}
三、生成小程序二维码(主要代码)
@Autowired
WXServiceExt wxServiceExt;
/**
* 生成不限个数的小程序码(建议使用)
*
* @param accessToken
* @param filePath
* @return
*/
public static void getminiqrQr(String accessToken, String filePath) {
String WxCode_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";//小程序密钥
String fileName = "code1.png";
try {
String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN", accessToken);
URL url = new URL(wxCodeURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
JSONObject paramJson = new JSONObject();
// 注意小程序页面如果不存在,则注释掉page参数
//paramJson.put("page", "pages/index/index");
paramJson.put("scene", "1234567890");
paramJson.put("width", 430);
paramJson.put("is_hyaline", true);
paramJson.put("auto_color", true);
printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File(filePath + fileName));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
os.flush();
}
os.close();
} catch (Exception e) {
log.error("===> error : ", e);
}
}