创建微信小程序二维码有两个接口需要
一个是获取tocken的接口
一个是生成二维码的接口
获取tocken接口
//**********填写你的小程序appid 和 secret
public static String getAccessToken() throws IOException {//获取tokcen接口String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=*********&secret=*********";url.trim();//创建http请求CloseableHttpClient aDefault = HttpClients.createDefault();HttpGet httpGet=new HttpGet(url);CloseableHttpResponse execute = aDefault.execute(httpGet);String toString = EntityUtils.toString(execute.getEntity());System.out.println(toString);Map map = JSONObject.parseObject(toString, Map.class);System.out.println(map);//只获取tocken返回return map.get("access_token").toString();}
接下来就是获取二维码接口
微信小程序提供了三种
其余两种是数量或时间有限制我们使用第三种数量和时间没有限制的接口
//这里使用HttpServletResponse response吧接收到的二维码发送给前端@GetMapping("/WXEwm")@ResponseBodypublic String WXEwm(HttpServletRequest request , HttpServletResponse response) {try{//获取tockenString accessToken = GetOpenIdUtil.getAccessToken();//生成二维码接口:吧tocken添加在地址后URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);//创建http请求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();//将所有要添加的数据放到scene参数中并做URLDecoder(前端接收数据要从scene中获取)String decode = URLDecoder.decode("a=132;b=132;", "UTF-8");paramJson.put("scene", decode);//转发地址扫描二维码要跳转到那里只获取路径前面去掉/后面不加参数也去掉/paramJson.put("page", "packtwo/pages/details/index");paramJson.put("width", 430);paramJson.put("auto_color", true);printWriter.write(paramJson.toString());// flush输出流的缓冲printWriter.flush();//开始获取数据将数据放到流中BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());Date date = new Date();Timestamp timestamp = new Timestamp(System.currentTimeMillis());long time = timestamp.getTime();response.addHeader("Content-Disposition", "inline;filename=\"" + new String("aaa".getBytes("gb2312"), "ISO8859-1")+"\"");//将获取到的流返回到response中//如果要保存到本地 BufferedOutputStream os = new BufferedOutputStream("D:加上你的路径");BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());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 "ok";}
测试postman
swagger