首先是微信接口信息:获取不限制的小程序码 | 微信开放文档
接下来是代码
/**
* 获取微信token
*
* @return String
* @author xyl
* @date 2023/1/7 9:46
*/
public String getAccessToken() throws IOException {
Object o = redisUtil.get(RedisKey.ACCESS_TOKEN);
if (o != null) {
return o.toString();
}
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + smallSecret;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(accessTokenUrl);
CloseableHttpResponse execute;
execute = client.execute(httpGet);
int i = execute.getStatusLine().getStatusCode();
if (i != 200) {
log.warn("获取微信AccessToken失败");
return null;
}
HttpEntity entity = execute.getEntity();
String string = EntityUtils.toString(entity);
JSONObject jsonObject = JSONObject.parseObject(string);
Object token = jsonObject.get("access_token");
redisUtil.set(RedisKey.ACCESS_TOKEN, token.toString(), 7100);
return token.toString();
}
/**
* 获取小程序二维码 带参数
*
* @return 二维码字符串
*/
public String getQRCode(String unionid) throws IOException {
//获取微信token
String accessToken = getAccessToken();
if (accessToken != null) {
String postUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
JSONObject jsonObject = new JSONObject();
//可以用作传参,必填,内容随意
jsonObject.put("scene", "id=" + unionid + "");
//默认是主页,页面 page,例如 pages/index/index,根路径前不要填加 /,不能携带参数(参数请放在 scene 字段里),如果不填写这个字段,默认跳主页面。
jsonObject.put("page", "pages/personal/personal");
//默认是true,检查page 是否存在,为 true 时 page 必须是已经发布的小程序存在的页面(否则报错);为 false 时允许小程序未发布或者 page 不存在, 但page 有数量上限(60000个)请勿滥用。
jsonObject.put("check_path", false);
//要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
jsonObject.put("env_version", "develop");
try {
URL url = new URL(postUrl);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
// 提交模式
httpUrlConnection.setRequestMethod("POST");
//连接超时 单位毫秒
httpUrlConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpUrlConnection.setReadTimeout(10000);
// 发送POST请求必须设置如下两行
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpUrlConnection.getOutputStream());
printWriter.write(jsonObject.toJSONString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpUrlConnection.getInputStream());
//调取上传oss接口
return ossUtil.upload(bis, UUID.randomUUID() + ".png");
} catch (Exception e) {
log.warn("获取用户二维码出现异常,错误信息:{}", e.getMessage());
}
} else {
log.warn("获取用户二维码出现异常,错误信息:获取不到accessToken");
}
return null;
}