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中实现微信小程序码的生成。具体参数调整请参考微信官方文档。

相关推荐
FYKJ_20102 小时前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
考虑考虑2 小时前
JDK27中的结构化并发
java·后端·java ee
修己xj2 小时前
设备数据采集中的 XPS 文件:它是什么,以及如何正确打开
后端
LucianaiB3 小时前
PGuard 实测与流式改造:我写了一套跨平台护栏网关,顺手拿 789 个标注点把三款安全头测了一遍
后端
程序员cxuan4 小时前
绝了,WorkBuddy 可以打通微信了
人工智能·后端·程序员
程序员cxuan4 小时前
再见了反重力,Google 又来搞事了
人工智能·后端·程序员
狗头大军之江苏分军5 小时前
《潮水漫过十七岁》 加一个蛋,顺便说一下我解放了
前端·后端
Captaincc5 小时前
掘金AI用量迎来重大更新!全新AI用量
前端·后端
AAA修煤气灶刘哥6 小时前
排查一次 CI 失败,Cloudflare 怎么把六次大模型调用减到一次?
人工智能·后端·llm
vx-程序开发7 小时前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业