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

相关推荐
IT_陈寒11 分钟前
JavaScript闭包的这个坑,我居然今天才爬出来
前端·人工智能·后端
Thneonl17 分钟前
消息队列选型决策树:RabbitMQ vs Kafka vs Redis Streams
后端·架构
晚安日记wanna19 分钟前
大厂禁 JOIN 的真正原因,拆到第四层才清楚
数据库·后端·面试
dd聊技术29 分钟前
LLM 说"你这篇和已有文章 92% 相似",我去查了——它编的
后端
行百里er1 小时前
Redis 持久化——RDB 快照 vs AOF 日志
redis·后端
Ysx2 小时前
踩了 5 次"本地全绿、生产失效"之后,我把交付流程做成了 SOP
后端·程序员
pippocao2 小时前
王者荣耀日志组件BqLog为什么这么快之2——从环形队列到自适应数据总线
后端
孟健3 小时前
Stripe出海收款架构设计:水星银行与香港账户实测对比与资金流闭环
后端·架构
程序员cxuan3 小时前
DeepSeek Harness 出了桌面端?我把它扒了一遍
人工智能·后端·程序员
j7~3 小时前
【Python】(篇七)《使用Python库》 -- 详解
开发语言·后端·python·编程学习·python标准库·python第三方库·python拓展