在Spring Boot中对接微信小程序生成小程序码的详细步骤如下:
一、前期准备
-
小程序账号配置
- 登录微信公众平台,进入小程序后台。
- 获取以下关键信息:
appid
:小程序的AppID。appsecret
:小程序的AppSecret。
- 配置服务器域名(开发设置 → 服务器域名):
- 确保后端API域名已添加到微信白名单。
-
Spring Boot项目依赖 在
pom.xml
中添加HTTP客户端和JSON处理依赖(如果未添加):xml<!-- HTTP客户端(推荐使用OkHttp或RestTemplate) --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency> <!-- JSON处理 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>
二、获取Access Token
微信API调用需使用access_token
,需定时刷新(有效期2小时)。
在application.yml
中配置小程序参数:
yaml
wechat:
mini-program:
appid: your_appid
secret: your_appsecret
access-token-url: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}
创建配置类:
java
@Configuration
@ConfigurationProperties(prefix = "wechat.mini-program")
@Data
public class WeChatMiniProgramConfig {
private String appid;
private String secret;
private String accessTokenUrl;
}
实现Access Token获取工具:
java
@Service
public class WeChatService {
@Autowired
private WeChatMiniProgramConfig config;
// 缓存Access Token(推荐使用Redis)
private String accessToken;
private long expiresTime;
public String getAccessToken() {
if (accessToken == null || System.currentTimeMillis() > expiresTime) {
refreshAccessToken();
}
return accessToken;
}
private void refreshAccessToken() {
String url = MessageFormat.format(config.getAccessTokenUrl(), config.getAppid(), config.getSecret());
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
String json = response.body().string();
JsonNode node = new ObjectMapper().readTree(json);
accessToken = node.get("access_token").asText();
expiresTime = System.currentTimeMillis() + (node.get("expires_in").asLong() - 300) * 1000; // 提前5分钟刷新
} catch (Exception e) {
throw new RuntimeException("获取Access Token失败", e);
}
}
}
三、生成小程序码
微信提供两种生成方式:
- wxacode.get:生成数量有限(适用于短期活动)。
- wxacode.getUnlimited:无数量限制(推荐长期使用)。
示例:调用wxacode.getUnlimited
创建请求参数类:
java
@Data
public class WxCodeRequest {
private String scene; // 场景参数(如:id=123)
private String page; // 小程序页面路径(如:pages/index/index)
private Integer width = 430; // 二维码宽度(默认430px)
private Boolean autoColor = false;
private Map<String, Integer> lineColor = Map.of("r", 0, "g", 0, "b", 0); // 默认黑色
private Boolean isHyaline = false; // 是否透明
}
实现生成接口:
java
@RestController
@RequestMapping("/wechat/qrcode")
public class WxCodeController {
@Autowired
private WeChatService weChatService;
@PostMapping("/unlimited")
public void generateUnlimitedQrCode(@RequestBody WxCodeRequest request, HttpServletResponse response) {
String accessToken = weChatService.getAccessToken();
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
// 构建请求体
Map<String, Object> body = new HashMap<>();
body.put("scene", request.getScene());
body.put("page", request.getPage());
body.put("width", request.getWidth());
body.put("auto_color", request.getAutoColor());
body.put("line_color", request.getLineColor());
body.put("is_hyaline", request.getIsHyaline());
// 发送POST请求
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(
new ObjectMapper().writeValueAsString(body),
MediaType.parse("application/json")
);
Request httpRequest = new Request.Builder().url(url).post(requestBody).build();
try (Response httpResponse = client.newCall(httpRequest).execute()) {
// 检查响应类型:成功返回图片,失败返回JSON
if ("image/jpeg".equals(httpResponse.header("Content-Type"))) {
response.setContentType("image/jpeg");
response.getOutputStream().write(httpResponse.body().bytes());
} else {
String errorJson = httpResponse.body().string();
throw new RuntimeException("生成二维码失败:" + errorJson);
}
} catch (Exception e) {
throw new RuntimeException("请求微信API失败", e);
}
}
}
四、前端调用示例
前端通过接口获取二维码图片:
javascript
// 调用后端API
axios.post('/wechat/qrcode/unlimited', {
scene: 'product_id=123',
page: 'pages/product/detail',
width: 300
}, { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const img = document.createElement('img');
img.src = url;
document.body.appendChild(img);
});
五、注意事项
-
参数限制:
scene
参数最大长度32字符(wxacode.getUnlimited)。page
路径需以pages/
开头,且必须在小程序已发布版本中存在。
-
错误码处理:
- 常见错误码:
40001
(access_token无效)、41030
(page路径不存在)。 - 需捕获并处理微信API返回的错误信息。
- 常见错误码:
-
性能优化:
- 缓存生成的二维码图片,避免重复调用微信API。
- 使用Redis缓存Access Token,避免频繁刷新。
-
安全建议:
- 不要在前端暴露AppSecret。
- 对生成二维码的接口做权限验证(如JWT校验)。
通过以上步骤,即可在Spring Boot中实现微信小程序码的生成。具体参数调整请参考微信官方文档。