代码一:
public String generateQRCode(String appId, String appSecret, String pagePath) throws IOException {
String accessToken = getAccessToken(appId, appSecret);
String apiUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
JSONObject requestBody = new JSONObject();
requestBody.put("scene", pagePath); // 指定体验版的路径
requestBody.put("width", 280);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.toString().getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 处理返回的小程序码图片数据
// ...
inputStream.close();
} else {
throw new IOException("HTTP response code: " + responseCode);
}
return null;
}
private String getAccessToken(String appId, String appSecret) throws IOException {
String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 处理返回的 access token 数据
// ...
inputStream.close();
} else {
throw new IOException("HTTP response code: " + responseCode);
}
return null;
}
代码二:
controller部分:
//生成小程序码方式
@PostMapping("/generate/applet")
public ResponseEntity<byte[]> generateQRCode(@RequestBody CodeData codeData, HttpServletResponse response) throws IOException {
// System.out.println(codeData);
String accessToken = weChatApiService.getAccessTokenTwo(codeData.getOpenId(), codeData.getAppSecret());
String page = codeData.getPage();
byte[] imageBytes = qrCodeImg.generateMiniProgramQRCode(accessToken,codeData.getScene(),page);
// 设置响应头部
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(imageBytes.length);
// 返回图片数据
return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
}
获取access_token部分:
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class WeChatApiService {
// @Value("${wechat.appId}")
// private String appId;
//
// @Value("${wechat.appSecret}")
// private String appSecret;
public String getAccessTokenOne(String appId, String appSecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
WebClient client = WebClient.create();
AccessTokenResponse response = client.get()
.uri(url)
.retrieve()
.bodyToMono(AccessTokenResponse.class)
.block();
if (response != null) {
return response.getAccess_token();
} else {
throw new RuntimeException("Failed to get access token.");
}
}
public String getAccessTokenTwo(String appId, String appSecret) {
// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
RestTemplate restTemplate = new RestTemplate();
AccessTokenResponse response = restTemplate.getForObject(url, AccessTokenResponse.class);
if (response != null) {
return response.getAccess_token();
} else {
throw new RuntimeException("Failed to get access token.");
}
}
}
其他功能类:
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Service
public class QRCodeImg {
public byte[] generateMiniProgramQRCode(String accessToken, String scene,String pageEncoded) throws IOException {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
// String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
// 正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
String env_version = "trial";
// 构建请求参数
// String postData = "{\"scene\":\"" + scene + "\", \"path\":\"" + pageEncoded + "\", \"width\":430,\"env_version\":\"trial\"}";
String postData = "{\"scene\":\"" + scene + "\", \"page\":\"" + pageEncoded + "\", \"width\":430,\"env_version\":\""+env_version +"\"}";
// String postData = "{\"scene\":\"" + scene + "\", \"width\":430,\"env_version\":\"trial\"}";
// 发送POST请求
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.getOutputStream().write(postData.getBytes("UTF-8"));
// 读取响应数据
InputStream inputStream = connection.getInputStream();
byte[] buffer = StreamUtils.copyToByteArray(inputStream);
// 解析响应数据,获取小程序码的URL
return buffer;
}
public void saveQRCodeImage(String imageUrl, String filePath) throws IOException {
System.out.println(imageUrl);
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 读取图片数据
InputStream inputStream = connection.getInputStream();
// 保存图片到本地文件
FileOutputStream outputStream = new FileOutputStream(filePath);
StreamUtils.copy(inputStream, outputStream);
// 关闭流
inputStream.close();
outputStream.close();
}
}
import lombok.Data;
@Data
public class CodeData {
private String scene;
private String openId;
private String appSecret;
private String page;
}
三种方式获取小程序码,我用的第三种方式,如下:
获取小程序二维码 | 微信开放文档微信开发者平台文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
获取小程序码 | 微信开放文档微信开发者平台文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html
获取不限制的小程序码 | 微信开放文档微信开发者平台文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html微信小程序前端获取参数:
在App.js获取:
App({
onLaunch(options) {
console.log(options.query); // 获取小程序码的参数
}
})