微信小程序:java开发获取小程序码和二维码

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

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

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

接口地址:

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

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

**第一步:**获取accesstoken

   final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Value("${my.appid}")
    private String appid;

    @Value("${my.secret}")
    private String secret;
        /**
     * 获取二维码
     *
     * @param
     * @returnurl 
     */
    @RequestMapping("/getPic/{id}")
    @ResponseBody
 public String getaccess_tokenurl(HttpServletRequest request) {
    HttpSession session=request.getSession();//因为access_token过期时间为7200秒,暂时放在session中,如果过期了重新去取
        String access_token="";
        if (session.getAttribute("userInfo")!=null){
            access_token= JsonTools.getJsonValue((String) session.getAttribute("userInfo"), "access_token");
        }else {
            String getaccess_tokenurl = "https://api.weixin.qq.com/cgi-bin/token?" +
                    "grant_type=client_credential" +
                    "&appid=" + appid +
                    "&secret=" + secret;
            RestTemplate restTemplate1 = new RestTemplate();
            String response1 = restTemplate1.getForObject(getaccess_tokenurl, String.class);
            session.setAttribute("userInfo",response1);
            access_token = JsonTools.getJsonValue(response1, "access_token");//文章最下面会贴出工具类
        }
    }

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

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

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

 public  ResponseEntity<byte[]> getminiqrQr(String accessToken) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            param.put("path", "pages/index/index");
            param.put("width", 430);
            param.put("auto_color", true);
            LOGGER.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);

            File file = new File("../test.png");
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();

            HttpHeaders headers_1 = new HttpHeaders();
        
            //通知浏览器以attachment方式打开图片
            headers_1.setContentDispositionFormData("attachment","下载.png");
            //application/octet-stream:二进制流数据(最常见的文件下载方式)
            headers_1.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),
                    headers_1, HttpStatus.CREATED);
        } catch (Exception e) {
            LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

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

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

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

@Controller
@RequestMapping("/m")
public class WxController {
    final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Value("${my.appid}")
    private String appid;

    @Value("${my.secret}")
    private String secret;

    @Autowired
    private ShopMapper shopMapper;


    /**
     * 获取二维码
     *
     * @param
     * @returnurl
     */
    @RequestMapping("/getPic/{id}")
    @ResponseBody
    public ResponseEntity<byte[]> getaccess_tokenurl(@PathVariable("id")String shopId, HttpServletRequest request) {
        if (ChkTools.isNull(shopId)){
            return null;
        }
        HttpSession session=request.getSession();
        String access_token="";
        if (session.getAttribute("userInfo")!=null){
            access_token= JsonTools.getJsonValue((String) session.getAttribute("userInfo"), "access_token");
        }else {
            String getaccess_tokenurl = "https://api.weixin.qq.com/cgi-bin/token?" +
                    "grant_type=client_credential" +
                    "&appid=" + appid +
                    "&secret=" + secret;
            RestTemplate restTemplate1 = new RestTemplate();
            String response1 = restTemplate1.getForObject(getaccess_tokenurl, String.class);
            session.setAttribute("userInfo",response1);
            access_token = JsonTools.getJsonValue(response1, "access_token");
        }
        return getminiqrQr(access_token,shopId);
    }

    public static void main(String[] args) throws IOException {
        String access_token = "13_nOfh7Bdr5Z6kS2PtiVd5PIYIZSxbx1uQtSD4Uu1o_4YDIGzrvZBEd_T9C3EprG3OE_BsXNfsVeNmlTsmGut05QECC_yA9kWyl26g5886eQXYFT225d-jtZ3A36lZOatzTYxDiNcY2UeQMJhPZCCfAAALOO";
//        String url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
//        ResponseEntity<byte[]> aa = getminiqrQr(access_token, "1");
//        System.out.println(aa);

    }
    public  ResponseEntity<byte[]> getminiqrQr(String accessToken,String shopId) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            param.put("path", "pages/index/index");
            param.put("width", 430);
            param.put("scene", shopId);
            param.put("auto_color", true);
            LOGGER.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            LOGGER.info("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);

            File file = new File("../test.png");
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();

            HttpHeaders headers_1 = new HttpHeaders();
            //下载显示的文件名,解决中文名称乱码
            Shop shop = shopMapper.selectByPrimaryKey(Integer.valueOf(shopId));
            String downLoadFileName = new String (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);

            return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),
                    headers_1, HttpStatus.CREATED);
        } catch (Exception e) {
            LOGGER.error("调用小程序生成微信永久二维码URL接口异常",e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

贴出JsonTools工具类:

public class JsonTools {
	/**
	 *  该方法是传入string 并转化为json,再根据传入的key获取相关值
	 * @param rescontent 字符串
	 * @param key 字符串中的json关键字
	 * @return
	 */
	public static String getJsonValue(String rescontent, String key) {
		org.json.JSONObject jsonObject;
		String v = null;
		try {
			jsonObject = new org.json.JSONObject(rescontent);
			v = jsonObject.getString(key);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return v;
	}
	//
	public static JSONObject MapStrString(Map<String,Object> map) {
		JSONObject a;
		return a = new JSONObject(map);
	}
	/**
	 * 该方法是传入string 并转化为json
	 * @param rescontent
	 * @return
	 */
	public static org.json.JSONObject StringStrJson(String rescontent) {
		org.json.JSONObject jsonObject = null;
		String v = null;
		try {
			jsonObject = new org.json.JSONObject(rescontent);

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return jsonObject;
	}
	/**
	 * json 字符串 转 Map
	 * 
	 * @param json
	 * @return
	 */
	public static Map<String, Object> jsonStrToMap(String json) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (ChkTools.isNull(json)) {
			return map;
		}
		JSONObject jsonObject = JSON.parseObject(json);
		Set<String> keys = jsonObject.keySet();
		for (String key : keys) {
			map.put(key, jsonObject.get(key));
		}

		return map;
	}

	/**
	 * json 字符串 转 java Object
	 * 
	 * @param json
	 * @return
	 */
	public static Object jsonStrToJsonObject(String json, Class<?> clazz) {
		if (clazz == String.class) {
			if (json.length() > 2) {
				// 去掉首尾的引号
				json = json.substring(1, json.length() - 1);
			}
			return json;
		} else {
			JSONObject parse = JSON.parseObject(json);
			return JSON.toJavaObject(parse, clazz);
		}
	}

	/**
	 * 对象-->json
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj) {
		return JSON.toJSONString(obj);
	}

	public static Map<String, Object> objToMap(Object obj) {
		String json = toJson(obj);
		Map<String, Object> map = jsonStrToMap(json);
		return map;
	}


	public static void main(String[] args) {
		String json = "{ \"firstName\": \"Brett\", \"lastName\":\"McLaughlin\", \"email\": \"aaaa\" }";
		Map<String, Object> map = jsonStrToMap(json);
//		String js = "{\"+\"}";
		System.err.println(map);
	}

}
阅读更多
换一批

没有更多推荐了,返回首页