微信小程序> 二维码和小程序码有啥区别-微信小程序:java开发获取小程序码和二维码-小程序二维码

二维码和小程序码有啥区别-微信小程序:java开发获取小程序码和二维码-小程序二维码

浏览量:1902 时间: 来源:收一伞烟雨_

1.java开发获取批量小程序二维码微信小程序API文档:链接

2.通过查看api,小程序可以获取三种二维码,三种二维码有不同的适用场景,大家可以依据自己的业务场景选择,现在只针对一种进行代码演示:

3.注意:我编写的是第二种二维码:适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制。

4.接口地址:

5.https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

参数类型默认值说明access_tokenString微信的权限token,详细见下面的代码sceneString最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&’()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用urlencode处理,请使用其他编码方式)pageString必须是已经发布的小程序存在的页面(否则报错),例如pages/index/index,根路径前不要填加/,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面widthnumber430二维码的宽度,默认为430px,最小280px,最大1280pxauto_colorbooleanfalse自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认falseline_colorObject0auto_color为false时生效,使用rgb设置颜色例如{“r”:“xxx”,“g”:“xxx”,“b”:“xxx”}十进制表示,默认全0is_hyalinebooleanfalse是否需要透明底色,为true时,生成透明底色的小程序码,默认false

6.**第一步:**获取accesstoken

finalstaticorg.slf4j.LoggerLOGGER=LoggerFactory.getLogger(UserController.class);@Value("${my.appid}")privateStringappid;@Value("${my.secret}")privateStringsecret;/***获取二维码**@param*@returnurl*/@RequestMapping("/getPic/{id}")@ResponseBodypublicStringgetaccess_tokenurl(HttpServletRequestrequest){HttpSessionsession=request.getSession();//因为access_token过期时间为7200秒,暂时放在session中,如果过期了重新去取Stringaccess_token="";if(session.getAttribute("userInfo")!=null){access_token=JsonTools.getJsonValue((String)session.getAttribute("userInfo"),"access_token");}else{Stringgetaccess_tokenurl="https://api.weixin.qq.com/cgi-bin/token?"+"grant_type=client_credential"+"&appid="+appid+"&secret="+secret;RestTemplaterestTemplate1=newRestTemplate();Stringresponse1=restTemplate1.getForObject(getaccess_tokenurl,String.class);session.setAttribute("userInfo",response1);access_token=JsonTools.getJsonValue(response1,"access_token");//文章最下面会贴出工具类}}

7.**第二步:**获取小程序二维码

8.注意:未发布的小程序也可以生成二维码,只是二维码扫码后显示未发布

9.我的业务需求是生成的二维码图片需要下载:

publicResponseEntitybyte[]getminiqrQr(StringaccessToken){RestTemplaterest=newRestTemplate();InputStreaminputStream=null;OutputStreamoutputStream=null;try{Stringurl="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;MapString,Objectparam=newHashMap();param.put("path","pages/index/index");param.put("width",430);param.put("auto_color",true);LOGGER.info("调用生成微信URL接口传参:"+param);MultiValueMapString,Stringheaders=newLinkedMultiValueMap();HttpEntityrequestEntity=newHttpEntity(param,headers);ResponseEntitybyte[]entity=rest.exchange(url,HttpMethod.POST,requestEntity,byte[].class,newObject[0]);LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:"+entity.getBody());byte[]result=entity.getBody();inputStream=newByteArrayInputStream(result);Filefile=newFile("../test.png");outputStream=newFileOutputStream(file);intlen=0;byte[]buf=newbyte[1024];while((len=inputStream.read(buf,0,1024))!=-1){outputStream.write(buf,0,len);}outputStream.flush();HttpHeadersheaders_1=newHttpHeaders();//通知浏览器以attachment方式打开图片headers_1.setContentDispositionFormData("attachment","下载.png");//application/octet-stream:二进制流数据(最常见的文件下载方式)headers_1.setContentType(MediaType.APPLICATION_OCTET_STREAM);returnnewResponseEntitybyte[](org.apache.commons.io.FileUtils.readFileToByteArray(file),headers_1,HttpStatus.CREATED);}catch(Exceptione){LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);}finally{if(inputStream!=null){try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}}if(outputStream!=null){try{outputStream.close();}catch(IOExceptione){e.printStackTrace();}}}returnnull;}

10.这样子就会成功生成二维码并可以下载。

11.**注意!!!:**如果生成的图片不能打开,请改掉图片后缀,用txt打开,可以看到错误码,因为只有错误信息时才打不开,然而我们把它保存png的形式,导致看不到错误码,有了错误码后就可以快速定位错误的地方。

12.完整代码:(如果哪里不对,可以留言)

@Controller@RequestMapping("/m")publicclassWxController{finalstaticorg.slf4j.LoggerLOGGER=LoggerFactory.getLogger(UserController.class);@Value("${my.appid}")privateStringappid;@Value("${my.secret}")privateStringsecret;@AutowiredprivateShopMappershopMapper;/***获取二维码**@param*@returnurl*/@RequestMapping("/getPic/{id}")@ResponseBodypublicResponseEntitybyte[]getaccess_tokenurl(@PathVariable("id")StringshopId,HttpServletRequestrequest){if(ChkTools.isNull(shopId)){returnnull;}HttpSessionsession=request.getSession();Stringaccess_token="";if(session.getAttribute("userInfo")!=null){access_token=JsonTools.getJsonValue((String)session.getAttribute("userInfo"),"access_token");}else{Stringgetaccess_tokenurl="https://api.weixin.qq.com/cgi-bin/token?"+"grant_type=client_credential"+"&appid="+appid+"&secret="+secret;RestTemplaterestTemplate1=newRestTemplate();Stringresponse1=restTemplate1.getForObject(getaccess_tokenurl,String.class);session.setAttribute("userInfo",response1);access_token=JsonTools.getJsonValue(response1,"access_token");}returngetminiqrQr(access_token,shopId);}publicstaticvoidmain(String[]args)throwsIOException{Stringaccess_token="13_nOfh7Bdr5Z6kS2PtiVd5PIYIZSxbx1uQtSD4Uu1o_4YDIGzrvZBEd_T9C3EprG3OE_BsXNfsVeNmlTsmGut05QECC_yA9kWyl26g5886eQXYFT225d-jtZ3A36lZOatzTYxDiNcY2UeQMJhPZCCfAAALOO";//Stringurl2="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;//ResponseEntitybyte[]aa=getminiqrQr(access_token,"1");//System.out.println(aa);}publicResponseEntitybyte[]getminiqrQr(StringaccessToken,StringshopId){RestTemplaterest=newRestTemplate();InputStreaminputStream=null;OutputStreamoutputStream=null;try{Stringurl="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;MapString,Objectparam=newHashMap();param.put("path","pages/index/index");param.put("width",430);param.put("scene",shopId);param.put("auto_color",true);LOGGER.info("调用生成微信URL接口传参:"+param);MultiValueMapString,Stringheaders=newLinkedMultiValueMap();HttpEntityrequestEntity=newHttpEntity(param,headers);ResponseEntitybyte[]entity=rest.exchange(url,HttpMethod.POST,requestEntity,byte[].class,newObject[0]);LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:"+entity.getBody());byte[]result=entity.getBody();inputStream=newByteArrayInputStream(result);Filefile=newFile("../test.png");outputStream=newFileOutputStream(file);intlen=0;byte[]buf=newbyte[1024];while((len=inputStream.read(buf,0,1024))!=-1){outputStream.write(buf,0,len);}outputStream.flush();HttpHeadersheaders_1=newHttpHeaders();//下载显示的文件名,解决中文名称乱码Shopshop=shopMapper.selectByPrimaryKey(Integer.valueOf(shopId));StringdownLoadFileName=newString(shop.getShopName().getBytes("UTF-8"),"iso-8859-1");//通知浏览器以attachment方式打开图片headers_1.setContentDispositionFormData("attachment",downLoadFileName+".png");//application/octet-stream:二进制流数据(最常见的文件下载方式)headers_1.setContentType(MediaType.APPLICATION_OCTET_STREAM);returnnewResponseEntitybyte[](org.apache.commons.io.FileUtils.readFileToByteArray(file),headers_1,HttpStatus.CREATED);}catch(Exceptione){LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);}finally{if(inputStream!=null){try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}}if(outputStream!=null){try{outputStream.close();}catch(IOExceptione){e.printStackTrace();}}}returnnull;}}

13.贴出JsonTools工具类:

publicclassJsonTools{/***该方法是传入string并转化为json,再根据传入的key获取相关值*@paramrescontent字符串*@paramkey字符串中的json关键字*@return*/publicstaticStringgetJsonValue(Stringrescontent,Stringkey){org.json.JSONObjectjsonObject;Stringv=null;try{jsonObject=neworg.json.JSONObject(rescontent);v=jsonObject.getString(key);}catch(Exceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}returnv;}//publicstaticJSONObjectMapStrString(MapString,Objectmap){JSONObjecta;returna=newJSONObject(map);}/***该方法是传入string并转化为json*@paramrescontent*@return*/publicstaticorg.json.JSONObjectStringStrJson(Stringrescontent){org.json.JSONObjectjsonObject=null;Stringv=null;try{jsonObject=neworg.json.JSONObject(rescontent);}catch(Exceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}returnjsonObject;}/***json字符串转Map**@paramjson*@return*/publicstaticMapString,ObjectjsonStrToMap(Stringjson){MapString,Objectmap=newHashMapString,Object();if(ChkTools.isNull(json)){returnmap;}JSONObjectjsonObject=JSON.parseObject(json);SetStringkeys=jsonObject.keySet();for(Stringkey:keys){map.put(key,jsonObject.get(key));}returnmap;}/***json字符串转javaObject**@paramjson*@return*/publicstaticObjectjsonStrToJsonObject(Stringjson,Class?clazz){if(clazz==String.class){if(json.length()2){//去掉首尾的引号json=json.substring(1,json.length()-1);}returnjson;}else{JSONObjectparse=JSON.parseObject(json);returnJSON.toJavaObject(parse,clazz);}}/***对象--json**@paramobj*@return*/publicstaticStringtoJson(Objectobj){returnJSON.toJSONString(obj);}publicstaticMapString,ObjectobjToMap(Objectobj){Stringjson=toJson(obj);MapString,Objectmap=jsonStrToMap(json);returnmap;}publicstaticvoidmain(String[]args){Stringjson="{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}";MapString,Objectmap=jsonStrToMap(json);//Stringjs="{"+"}";System.err.println(map);}}

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎