Home > Java > javaTutorial > How to generate sun code for WeChat applet in Java

How to generate sun code for WeChat applet in Java

WBOY
Release: 2023-04-28 09:49:06
forward
2657 people have browsed it

    Implementation plan

    We can achieve the mini program sun code generation through the following method.

    How to generate sun code for WeChat applet in Java

    Generate restricted sun code

    Implementation steps

    • Get the access_token of the mini program

    • Set path and with related parameters

    • Call the getwxacodeunlimit interface and store the returned image locally

    Get the small Program access_token
    public static String getAccessToken(String appid, String appsecret)
        {
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret+"";
            String accessToken = null;
            try
            {
                String response = HttpClientUtil.getInstance().sendHttpsGet(
                        requestUrl, null);
                JSONObject json = JSONObject.parseObject(response);
                accessToken = String.valueOf(json.get("access_token"));
            }
            catch (Exception e)
            {
                logger.error("getAccessToken error", e);
            }
    
            return accessToken;
        }
    Copy after login

    Description: Just call the WeChat API interface and pass in the appid and appsecret parameters of the mini program.

    Call WeChat api to generate mini program sun code
     public static String generatLimitSunCode(WxScanCodeParam param) throws Exception 
        {
           String token =param.getAccessToken();
           Map<String, String> params = new HashMap<>();
           params.put("path", param.getPath());
           params.put("width", "430");
           CloseableHttpClient httpClient = HttpClientBuilder.create().build();
           HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacode?access_token="+token);
           httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
           String body = JSON.toJSONString(params);
           StringEntity entity = new StringEntity(body);
           entity.setContentType("image/jpg");
           httpPost.setEntity(entity);
           HttpResponse response = httpClient.execute(httpPost);
           int statusCode = response.getStatusLine().getStatusCode();
           if (statusCode == HttpStatus.SC_OK) 
           {
               HttpEntity entity2 = response.getEntity();
               if(!entity2.getContentType().getValue().equals("image/jpeg"))
               {
                   String result = EntityUtils.toString(entity2, "UTF-8");
                   logger.error("generate sun code error,http execute result:" + result);
                   return null;
               }
           }
           else
           {
               logger.error("generate sun code error,http execute result:" + statusCode);
           }
           
           InputStream inputStream = response.getEntity().getContent();
            // 保存图片到本地     
           int flag = saveImg(inputStream, param.getFilePath(), name);
           if (flag == 0)
           {
               throw new SysException("保存图片[" + name + "]失败");
           }
           else
           {
               logger.info("太阳码[{}]生成成功", name);
           }
           return param.getFilePath() + File.separatorChar + name;
       }
    Copy after login
    Description
    Parameter description
    • path: Scan the QR code to enter the mini program Page path, maximum length 128 bytes, cannot be empty; for example: pages/index/index

    • access_token: Mini program authorization token

    Note

    Special attention needs to be paid. The total number of mini-program sun codes and QR codes generated by this solution cannot exceed 100,000. WeChat does not provide the corresponding API interface to query the usage quantity. Once the quantity is exceeded, This will cause the mini program to become invalid, and WeChat currently cannot reset the number of queries, which is suitable for scenarios where the number of generated is small.

    Generate unlimited sun code

    Get the access_token of the mini program

    Same as the first solution

    Call WeChat api to generate the mini program sun code
    /**
         * 生成无限制的小程序码
         * @param param
         * @return
         * @throws Exception
         */
        public static String generatUnlimitSunCode(WxScanCodeParam param) throws Exception 
        {
           String token =param.getAccessToken();
           Map<String, String> params = new HashMap<>();
           params.put("scene", param.getScene());
           params.put("page", param.getPath());
           params.put("width", "430");
           CloseableHttpClient httpClient = HttpClientBuilder.create().build();
           HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
           httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
           String body = JSON.toJSONString(params);
           StringEntity entity = new StringEntity(body);
           entity.setContentType("image/jpg");
           httpPost.setEntity(entity);
           HttpResponse response = httpClient.execute(httpPost);
           int statusCode = response.getStatusLine().getStatusCode();
           if (statusCode == HttpStatus.SC_OK) 
           {
               HttpEntity entity2 = response.getEntity();
               if(!entity2.getContentType().getValue().equals("image/jpeg"))
               {
                   String result = EntityUtils.toString(entity2, "UTF-8");
                   logger.error("generate sun code error,http execute result:" + result);
                   return null;
               }
           }
           else
           {
               logger.error("generate sun code error,http execute result:" + statusCode);
           }
           
           InputStream inputStream = response.getEntity().getContent();
           
           //太阳码写标题
           String content=param.getWriteContent();
           if(StringUtil.isNotEmpty(content) && param.isWrite())
           {
              inputStream = ImageUtil.addImageTitle(param.getWriteContent(), inputStream, 450, 450);
           }
          
           String name = param.getFileName()+".jpg";//文件名加后缀,跟上面对应
           
    
           int flag = saveImg(inputStream, param.getFilePath(), name);// 保存图片
           if (flag == 0)
           {
               throw new SysException("保存图片[" + name + "]失败");
           }
           else
           {
               logger.info("太阳码[{}]生成成功", name);
           }
           return param.getFilePath() + File.separatorChar + name;
       }
    Copy after login
    Description
    Parameter description
    • scene: up to 32 visible characters, the parameter format can be defined by yourself a&b or a=1&b=2

    • access_token: Mini program authorization token

    The problem of too long parameters

    Since the length of the scene parameter only supports 32 characters, if The parameters exceed 32 bits, how will we handle them?

    Solution

    The solution to the problem is: design a small program parameter table, store the generated parameters in the table, and generate the small program by setting the scene parameter as the primary key of this table. , after the mini program scans the code, it first requests the background to obtain the specific parameters of the mini program through the scene parameter.

    Example below:

    How to generate sun code for WeChat applet in Java##

    The above is the detailed content of How to generate sun code for WeChat applet in Java. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template