欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java中生成微信小程序太阳码的实现方案,

来源: javaer 分享于  点击 16546 次 点评:144

Java中生成微信小程序太阳码的实现方案,


目录
  • 背景
  • 实现方案
  • 生成有限制太阳码
    • 实现步骤
      • 获取小程序的access_token
      • 调用微信api生成小程序太阳码
      • 说明
      • 参数说明
      • 注意事项
      • 获取小程序的access_token
      • 调用微信api生成小程序太阳码
      • 说明
      • 参数说明
      • 参数过长问题
      • 解决方案
  • 生成无限制太阳码
    • 扩展功能
      • 总结

        背景

        当前小程序盛行的时代,无论走在那里都会看到各种各样的小程序太阳码,小程序项目中经常也会用到小程序的太阳码,那么我们如何生成小程序的太阳码呢?

        实现方案

        我们可以通过如下的方法实现小程序太阳码生成。

        生成有限制太阳码

        实现步骤

        • 获取小程序的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中生成微信小程序太阳码的实现方案的文章就介绍到这了,更多相关小程序太阳码内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

        您可能感兴趣的文章:
        • 微信小程序生成海报分享朋友圈的实现方法
        • 微信小程序生成二维码的示例代码
        • 微信小程序分享海报生成的实现方法
        • 微信小程序动态生成二维码的实现代码
        相关栏目:

        用户点评