Files
minispringboot/src/main/java/com/example/mini_program/controller/WxController.java
T
ws d80f64268e feat: 实现微信小程序码生成后端接口
- 新增 WxController 提供 /api/wx-mini/wxacode 接口
- 新增 WxService 实现 access_token 缓存和小程序码生成
- 新增 HttpUtil.postJsonBytes() 方法处理二进制响应
- 配置 application.yml 支持 env 环境参数

主要功能:
1. access_token 自动缓存,5分钟过期缓冲避免频繁调用
2. 支持生成任意页面小程序码,最大宽度 430px
3. 支持环境版本参数(release/trial/develop)
4. 返回 Base64 图片数据,避免服务器文件存储
5. 使用 Jackson ObjectMapper 处理 JSON 序列化

技术细节:
- HttpURLConnection 请求微信 API
- Base64 编码图片数据
- 场景参数限制 32 字符
- 错误处理和异常捕获
2026-04-27 18:36:40 +08:00

62 lines
1.8 KiB
Java

package com.example.mini_program.controller;
import com.example.mini_program.common.Result;
import com.example.mini_program.service.WxService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/wx-mini")
@RequiredArgsConstructor
public class WxController {
private final WxService wxService;
/**
* 生成小程序码
*/
@PostMapping("/wxacode")
public Result<String> getWxacode(@RequestBody Map<String, String> request) {
String scene = request.get("scene");
String page = request.get("page");
String envVersion = request.get("envVersion");
if (scene == null || scene.trim().isEmpty()) {
return Result.error("scene不能为空");
}
page = (page != null && !page.trim().isEmpty()) ? page : "pages/scan/result/index";
Integer width = parseWidth(request.get("width"));
if (envVersion == null || envVersion.trim().isEmpty()) {
envVersion = wxService.getDefaultEnvVersion();
}
try {
String base64Image = wxService.getUnlimitedWxacode(scene, page, width, envVersion);
return Result.success(base64Image);
} catch (Exception e) {
log.error("生成小程序码失败", e);
return Result.error("生成小程序码失败: " + e.getMessage());
}
}
private Integer parseWidth(String widthStr) {
if (widthStr == null || widthStr.trim().isEmpty()) {
return 430;
}
try {
int width = Integer.parseInt(widthStr);
return width > 0 ? width : 430;
} catch (NumberFormatException e) {
log.warn("width参数格式错误: {}", widthStr);
return 430;
}
}
}