java 生成小程序二维码

根据小程序的appId和秘钥换取授权accessToken 信息:
String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="//生成二维码url
String url = "https://api.weixin.qq.com/cgi-bin/token?appid="+appId+"&secret="+appSecret+"&grant_type=client_credential"
RestTemplate restTemplate = new RestTemplate()
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class)
logger.info("responseEntity授权获取accessToken:"+responseEntity)
 if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {

        String sessionData = responseEntity.getBody()
        logger.info("sessionData = " + sessionData)
        JSONObject jsonObj = JSON.parseObject(sessionData)
        String accessToken = jsonObj.getString("access_token")

        URL url_Code= new URL(codeUrl+accessToken)
        HttpURLConnection httpURLConnection = (HttpURLConnection) url_Code.openConnection()
        httpURLConnection.setRequestMethod("POST")//提交模式
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true)
        httpURLConnection.setDoInput(true)
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream())
        // 发送请求参数
        JSONObject paramJson = new JSONObject()
        paramJson.put("scene",orderCodeReq.scene)
        paramJson.put("page", orderCodeReq.page)
        paramJson.put("width", orderCodeReq.width)//二维码的宽度,默认为 430px,最小 280px,最大 1280px
        paramJson.put("auto_color", orderCodeReq.autoColor)
        Map line_color = new HashMap<>()
        line_color.put("r", 0)
        line_color.put("g", 0)
        line_color.put("b", 0)
        paramJson.put("line_color", line_color)
        printWriter.write(paramJson.toString())
        // flush输出流的缓冲
        printWriter.flush()
        //开始获取数据
        String uploadBasePath = 上传文件的路径//
        String accessPath= 访问路径//
        String imei = RandomUtil.getCharAndNum(10) //随机生成文件的名称
        String name = imei+".png"
        String towPath=  上传文件的路径     

        if(uploadBasePath.charAt(uploadBasePath.length()-1) != '/') uploadBasePath=uploadBasePath+"/"
          String basePath=uploadBasePath+towPath
          File fileDir=new File(basePath)
          if(!fileDir.isDirectory()) fileDir.mkdirs()
          fileName = accessPath+"/"+towPath+"/"+name

          BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream())
          OutputStream os = new FileOutputStream(new File(basePath+"/"+name))
          int len
          byte[] arr = new byte[1024]
          while ((len = bis.read(arr)) != -1)
           {
               os.write(arr, 0, len)
               os.flush()
           }
          os.close()
        
  }
返回前端的是一个可以在浏览器上面访问的地址

你可能感兴趣的:(java 生成小程序二维码)