首頁  >  文章  >  Java  >  Java中如何產生微信小程式太陽碼

Java中如何產生微信小程式太陽碼

WBOY
WBOY轉載
2023-04-28 09:49:062603瀏覽

    實作方案

    我們可以透過以下的方法實作小程式太陽碼生成。

    Java中如何產生微信小程式太陽碼

    產生有限制太陽碼

    實作步驟

    • 取得小程式的access_token

    • 設定path、with相關參數

    • 呼叫getwxacodeunlimit介面,並將回傳圖片儲存到本地

    取得小程式的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;
        }

    說明:呼叫微信API介面傳入小程式的appid和appsecret參數即可。

    呼叫微信api產生小程式太陽碼
     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;
       }
    說明
    #參數說明
    • path:掃碼進入的小程序頁面路徑,最大長度128 位元組,不能為空;例如:pages/index/index

    • #access_token:小程式授權token

    注意事項

    需要特殊注意,本方案產生的小程式太陽碼與二維碼的總數不能超過10萬個,微信沒有提供對應的Api介面查詢的使用的數量,一旦超過了數量,將會導緻小程式失效,且微信目前無法重置查詢次數,適合於產生數量少的場景。

    產生無限制太陽碼

    取得小程式的access_token

    #如同第一種的方案

    呼叫微信api產生小程式太陽碼
    /**
         * 生成无限制的小程序码
         * @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;
       }
    說明
    參數說明
    • scene:最大32個可見字元,參數格式可以自行定義a&b或a=1&b=2都行

    • access_token:小程式授權token

    #參數過長問題

    由於scene參數的長度只支援32位元字符,如果參數超過了32位,我們將如何合處理?

    解決方案

    改變問題的解決方案為:設計一張小程式參數表,將產生的參數儲存到表中,產生小程式是scene參數設定此表表的主鍵,小程式掃碼後,先請求後台透過scene參數取得小程式的具體參數。

    如下範例:

    Java中如何產生微信小程式太陽碼

    以上是Java中如何產生微信小程式太陽碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除