采用的是wxacode.createQRCode获取二维码,此二维码有调用次数限制(100000次)
1.第一步获取accessToken
public static String getAccessToken() throws Exception {
String apiKey = "你的小程序apiKey";
String secretKey = "你的小程序secretKey";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + apiKey + "&secret=" + secretKey;
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
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 in = null;
if (requestUrl.contains("nlp")) {
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
} else {
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
}
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
JSONObject jsonObject = JSON.parseObject(result);
String accesstoken = jsonObject.getString("access_token");
return accesstoken;
}
2.获取小程序二维码到本地
public static Map<String, Object> getMiniqrQrToLocal(String machineNo, String accessToken) {
Map<String, Object> retMap = null;
try {
URL url = new URL("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
JSONObject paramJson = new JSONObject();
paramJson.put("path", "pages/index/index?machineNo="+machineNo);
paramJson.put("width", 430);
printWriter.write(paramJson.toString());
printWriter.flush();
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File("/Desktop/image/wechatImage.jpg"));
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) {
e.printStackTrace();
}
return retMap;
}
3.测试使用
public static void main(String[] args) throws Exception {
String accessToken = accessToken();
System.out.println("获取的accessToken:" + accessToken);
getMiniqrQrToLocal("123",accessToken);
}
4.小程序端接收参数
在page/index/index.js页面中的onload函数接收即可
onLoad: function(e) {
console.log("接收的机器参数为:"+e.machineNo);
}