微信小程序 Springboot 后台生成二维码

以官方接口方案B:wxacode.getUnlimited为例
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html

后台请求地址是:
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

所以在请求之前需要先获得后台调用凭证。

	public String getAccessToken() {//获取微信小程序后台API调用凭证
		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=";
		url = url+appid+"&secret="+appsecret;//appid和appsecret分别是你的小程序id和小程序密钥
	    RestTemplate restTemplate = new RestTemplate();
	    String res = restTemplate.getForObject(url, String.class);
		return res;
		
	}

然后就可以愉快地调用图片API了。值得注意的是文档里提到了POST接收的参数必须以JSON格式呈现,因此在使用restTemplate的时候需要添加一个HttpEntity,并设置HttpHeader的参数格式为JSON,然后再以HashMap的格式添加键值对。
值得一提的是返回的Buffer为byte数组格式,在接收时需要判断其长度。微信在返回数据的时候有两种情况,若正常生成图片,则返回buffer,其长度应该在100000数量级。若产生了错误信息,byte数组的长度就很小了。在这里直接将错误信息转为String返回,大家可以对其自行处理。

	@Override
	public String getQRCode(String accessToken) {
		String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
		RestTemplate restTemplate = new RestTemplate();
		if(accessToken==null) {
			return null;
		}
		
		//设置头部
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.setContentType(MediaType.APPLICATION_JSON);
		
		//设置body
		//对应请求参数见微信开放文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
		Map<String, String> requestBody = new HashMap<String,String>();
		requestBody.put("scene", "subid=3");
		
		HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
		byte[] res=restTemplate.postForObject(url, requestEntity, byte[].class);
		
		//将获取到的buffer流存储到本地图片
		String path = "../webapps/TempQRCode/";
		String name = "test2.jpg";
		File f = new File(path+"test2.jpg");
		
		try {
			if(res.length<=500) {//如果byte字节流小于500,说明返回的是err错误码而非buffer
				return new String(res);
			}else {
		        BufferedOutputStream out = new BufferedOutputStream(    
		                new FileOutputStream(f));
		        out.write(res);
		        out.flush();
		        out.close();				
			}
		}catch(Exception e) {
			e.printStackTrace();
			return "IO Error";
		}
		
		return name;
	}

然后在Controller层调用就行了(CutJSON是我自行实现的一个函数,从对应json中提取出对应键的值)

   @RequestMapping(value="/qrcode/getcodetest")
   public String getQRCodeTest() {
	   String res1 = service.getAccessToken();
	   String accessToken = service.CutJSON(res1, "access_token");
	   if(accessToken!=null) {
		   return service.getQRCode(accessToken);
	   }
	   return "fail to produce picture";
   }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值