java实现生成微信小程序码

接口文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
效果图:


 

流程:

1、导入依赖
2、在properties文件中配置appId、secret参数
3、获取配置文件中的参数到实例类
4、配置相关参数至WxMaService中
5、书写Service,逻辑代码编写
6、书写Controller,并完成测试

//代码演示
1、导入依赖

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

2、在properties文件中配置appId、secret参数

/*微信小程序相关参数*/
miniapp.appid=
miniapp.secret=

3、获取配置文件中的参数到实体类

package com.mine.luotj.config.wechat.ma;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 微信相关配置信息
 * @author: create by luotj
 * date: 2020-03-23 16:46
 **/
@ConfigurationProperties(prefix = "miniapp")
@Data
public class WxMaProperties {

    /*微信小程序app_id*/
    private String appid;

    /*微信小程序app_secret*/
    private String secret;


}


4、配置相关参数至WxMaService中

package com.mine.luotj.config.wechat.ma;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信小程序配置文件
 * @author: create by luotj
 * date: 2020-03-23 16:42
 **/
@Configuration
@ConditionalOnClass(WxMaService.class)
@EnableConfigurationProperties(WxMaProperties.class)
public class WeChatMaConfig {

    /*注入小程序相关配置*/
    @Autowired
    private WxMaProperties properties;

    /**
     * 配置默认参数
     */
    @Bean
    @ConditionalOnMissingBean
    public WxMaConfig wxMaConfig(){
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        //设置默认参数-appid,secret
        wxMaDefaultConfig.setAppid(this.properties.getAppid());
        wxMaDefaultConfig.setSecret(this.properties.getSecret());
        return wxMaDefaultConfig;
    }

    /**
     * 配置WxMaService
     */
    @Bean
    @ConditionalOnMissingBean
    public WxMaService wxMaService(WxMaConfig wxMaConfig){
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxMaConfig);
        return wxMaService;
    }


}


5、书写Service,逻辑代码编写

package com.mine.luotj.Service.wechat;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @author: create by luotj
 * date: 2020-03-23 16:34
 **/
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private WxMaService wxMaService;

    /**
     * 该实例获取的是不限制次数的小程序码
     *
     * @param response
     */
    @Override
    public void queryWeChatCode(HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            /* 获取二维码字节数组 */
            byte[] bytes = wxMaQrcodeService.createWxaCodeUnlimitBytes
                    ("hello,test", "", 100, true, new WxMaCodeLineColor("0", "0", "0"), false);
            /* 设置返回文件类型,不设置前端识别不了 */
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception ex) {
            log.info("生成小程序码失败,message:{}", ex.getMessage());
        } finally {
            try {
                outputStream.close();
            } catch (Exception ex) {
                log.error("关闭IO流失败,msg:{}", ex.getMessage());
            }
        }
    }
}


6、书写Controller,并完成测试

package com.mine.luotj.ui.controller.api.wechat.ma;

import com.mine.luotj.Service.wechat.WeChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 微信小程序相关接口测试
 * @author: create by luotj
 * date: 2020-03-23 16:27
 **/

@RestController
@RequestMapping("/api/wechat")
@Api(tags = "03. 微信相关接口")
public class WeChatController {

    @Autowired
    private WeChatService wechatService;

    @ApiOperation("获取微信小程序码")
    @GetMapping("/code")
    @ResponseBody
    public void queryWeChatCode(HttpServletResponse response){
        wechatService.queryWeChatCode(response);
    }
}


 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 要用Java获取微信小程序,首先需要使用微信提供的API接口来实现。以下是一种实现方法: 1. 首先,需要引入相关的依赖包和类库,例如使用HttpClient库来发送HTTP请求,使用JSON库来处理返回的JSON数据。 2. 在代中构建请求URL,将appid和appsecret等参数拼接到URL中,例如: String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=YOUR_APPID&secret=YOUR_SECRET"; 3. 使用HttpClient库发送GET请求,并获取返回的JSON数据,例如: HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); int statusCode = httpClient.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { String response = getMethod.getResponseBodyAsString(); JSONObject json = new JSONObject(response); String accessToken = json.optString("access_token"); // 这里获取到的accessToken是后续获取小程序时需要用到的凭证 } 4. 构建获取小程序的请求URL,将需要的参数拼接到URL中,例如: String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"; JSONObject requestData = new JSONObject(); requestData.put("scene", "YOUR_SCENE"); requestData.put("page", "YOUR_PAGE"); // 这里的YOUR_SCENE和YOUR_PAGE是你自定义的场景值和小程序页面路径值 5. 使用HttpClient库发送POST请求,并将requestData转换为JSON字符串作为请求的内容,获取小程序的二进制数据,例如: HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(codeUrl); postMethod.setRequestEntity(new StringRequestEntity(requestData.toString(), "application/json", "UTF-8")); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { // 获取小程序的二进制数据 byte[] responseBody = postMethod.getResponseBody(); // 这里可以将responseBody保存为图片或其他适合的格式 } 以上是使用Java获取微信小程序的一个简单示例,具体操作还可能受微信官方接口的限制,因此在实际应用中还需要根据接口文档进行适当的调整和处理。 ### 回答2: 要通过Java获取微信小程序,需要使用微信官方提供的开发工具包和API接口。 首先,你需要在微信开放平台上注册一个小程序并获得小程序的唯一标识AppID。 然后,在Java项目中引入相关的开发工具包,例如微信官方提供的Java SDK或第三方封装的SDK。 接下来,通过SDK提供的接口调用微信的API来获取小程序。你可以使用微信官方提供的CreateWXAQRCode接口,该接口可以生成小程序的图片或base64编,并保存在指定的路径。 具体的步骤如下: 1. 创建一个HttpClient对象,并通过HttpPost请求访问微信的API接口。 2. 设置请求的URL为微信的API地址,例如https://api.weixin.qq.com/wxa/getwxacodeunlimit。 3. 设置请求的参数,包括小程序的AppID、Access Token(获取方法见微信开放平台文档)、参数scene(小程序的参数,根据不同的需求进行设置)等。 4. 设置请求的Header信息,包括Content-Type等。 5. 发送请求并获取响应结果。 6. 解析响应结果,判断请求是否成功,如果成功,则从响应结果中提取出小程序的图片或base64编,并保存或处理。 需要注意的是,微信小程序生成是有一定限制的,例如小程序的有效期等,你需要根据需要在代中进行相应的处理。 总结起来,通过上述步骤,你就可以使用Java来获取微信小程序了。当然,具体的实现细节还需要参考微信开放平台的开发文档和SDK的使用说明。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值