springboot对接微信小程序以及生成小程序码

在Spring Boot中对接微信小程序生成小程序码的详细步骤如下:


一、前期准备

  1. 小程序账号配置

    • 登录微信公众平台,进入小程序后台。
    • 获取以下关键信息:
      • appid:小程序的AppID。
      • appsecret:小程序的AppSecret。
    • 配置服务器域名(开发设置 → 服务器域名):
      • 确保后端API域名已添加到微信白名单。
  2. 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);
        }
    }
}

三、生成小程序码

微信提供两种生成方式:

  1. wxacode.get:生成数量有限(适用于短期活动)。
  2. 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);
});

五、注意事项

  1. 参数限制

    • scene参数最大长度32字符(wxacode.getUnlimited)。
    • page路径需以pages/开头,且必须在小程序已发布版本中存在。
  2. 错误码处理

    • 常见错误码:40001(access_token无效)、41030(page路径不存在)。
    • 需捕获并处理微信API返回的错误信息。
  3. 性能优化

    • 缓存生成的二维码图片,避免重复调用微信API。
    • 使用Redis缓存Access Token,避免频繁刷新。
  4. 安全建议

    • 不要在前端暴露AppSecret。
    • 对生成二维码的接口做权限验证(如JWT校验)。

通过以上步骤,即可在Spring Boot中实现微信小程序码的生成。具体参数调整请参考微信官方文档

相关推荐
FG.1 分钟前
GO语言入门
开发语言·后端·golang
转转技术团队1 小时前
加Log就卡?不加Log就瞎?”——这个插件治好了我的精神
java·后端
谦行1 小时前
前端视角 Java Web 入门手册 5.5:真实世界 Web 开发——控制反转与 @Autowired
java·后端
uhakadotcom1 小时前
PyTorch 2.0:最全入门指南,轻松理解新特性和实用案例
后端·面试·github
bnnnnnnnn1 小时前
前端实现多服务器文件 自动同步宝塔定时任务 + 同步工具 + 企业微信告警(实战详解)
前端·javascript·后端
DataFunTalk1 小时前
乐信集团副总经理周道钰亲述 :乐信“黎曼”异动归因系统的演进之路
前端·后端·算法
DataFunTalk2 小时前
开源一个MCP+数据库新玩法,网友直呼Text 2 SQL“有救了!”
前端·后端·算法
idMiFeng2 小时前
通过GO后端项目实践理解DDD架构
后端
LemonDu2 小时前
Cursor入门教程-JetBrains过度向
人工智能·后端
LTPP2 小时前
掌握Rust Web开发的未来:Hyperlane框架全方位教程 🎓🔧
前端·后端·github