小程序生成二维码(使用binarywang封装的微信工具包)

时间:2024-02-19 20:38:12

一、引包(微信开发工具包)

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>3.5.0</version>
</dependency>

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-common</artifactId>
    <version>3.5.0</version>
</dependency>

工具包代码详细链接:https://github.com/binarywang

二、代码

这边是直接返回base64图片形式。如果有需要其他请自行处理。

    @ApiOperation("生成二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name="codeType",value = "类型",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name="parameterValue",value = "参数值",dataType = "String",required = true,paramType = "query")
    })
    @GetMapping(value = "/createQrCode")
    public  String createQrCode(@RequestParam("codeType") String codeType,
                                @RequestParam("parameterValue") String parameterValue) throws HttpProcessException, IOException {
	//调用工具包的服务
        WxMaService wxMaService = new WxMaServiceImpl();
        WxMaDefaultConfigImpl wxMaDefaultConfigImpl = new WxMaDefaultConfigImpl();
        wxMaDefaultConfigImpl.setAppid(WxConfig.appid);		//小程序appId
        wxMaDefaultConfigImpl.setSecret(WxConfig.secret);	//小程序secret
        wxMaService.setWxMaConfig(wxMaDefaultConfigImpl);

        // 设置小程序二维码线条颜色为黑色
        WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
        byte[] qrCodeBytes = null;
        try {
	    //其中codeType以及parameterValue为前端页面所需要接收的参数。
            qrCodeBytes = wxMaService.getQrcodeService().createWxaCodeBytes("pages/index/index?codeType=" + codeType + "&parameterValue=" + parameterValue, 30, false, lineColor, false);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
       String qrCodeStr= Base64.encodeBase64String(qrCodeBytes);
       return qrCodeStr;
    }