获取access_token
public static String getAccessToken(String appId, String appSecret) {
String urlStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String result = HttpUtil.sendHttpRequestGet(urlStr);
System.out.println(result);
JSONObject jsonObject = JSONObject.parseObject(result);
System.out.println(jsonObject.getString("access_token"));
return jsonObject.getString("access_token");
}
调用微信的接口获取小程序码
@ResponseBody
@RequestMapping("/getWXACode")
public ResponseData getWXACode(Long userId) {
RestTemplate rest = new RestTemplate();
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + WxContactUtil.getAccessToken(WxUtil.APP_ID_MAP.get("audition"), WxUtil.APP_SECRET_MAP.get("audition"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("scene", userId.toString());
jsonObject.put("width", 300);
jsonObject.put("auto_color", true);
jsonObject.put("is_hyaline", true);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(jsonObject, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
byte[] result = entity.getBody();
Base64.encodeBase64String(result); //进行base64格式转换
return new ResponseData(result);
}
前端js
wx.request({
url: "http://192.168.3.11:8089/api/activity/getWXACode",
data:{
userId:"1111111"
},
success:function(res){
console.log(res);
var imgUrl = res.data.data;
// wx.arrayBufferToBase64(res.data);
that.setData({
imgUrl:imgUrl
})
console.log(that.data.imgUrl)
}
})
wxml显示
<image src="https://img-blog.csdnimg.cn/2022010622154012129.png"></image>
小程序接口调用成功返回的数据是二进制格式,需要进行以下base64转化,本文只是留作备份,供以后使用参考