微信官方地址: 获取小程序码 | 微信开放文档
这里使用接口B: /getUnlimitedQRCode
- 适用于需要的码数量极多的业务场景
- 生成小程序码,可接受页面参数较短,生成个数不受限。
直接按步骤上代码:
1.小程序参数准备,一般放在yml配置文件中
wx:
//小程序认证参数
xcx:
appid: xxx
secret: xxx
//获取AccessToken地址
wechatQrcodeAccessTokenUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
//获取小程序码地址
wechatQrcodeUrl: https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=
@Data
@ConfigurationProperties(prefix = "wx")
@Component
public class WxProperties {
private WxConfig xcx;
private String wechatQrcodeAccessTokenUrl;
private String wechatQrcodeUrl;
@Data
public static class WxConfig {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
}
}
2.获取 AccessToken
@Resource
private WxProperties wxProperties;
@Resource
private RestTemplate restTemplate;
public String getQrtAccessToken() {
String appid = wxProperties.getXcx().getAppid();
String secret = wxProperties.getXcx().getSecret();
String url = wxProperties.getWechatQrcodeAccessTokenUrl().replace("APPID", appid)
.replace("APPSECRET", secret);
Map<String, String> responseBody = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {}).getBody();
if (responseBody == null || responseBody.get("errcode") != null) {
// 获取失败
log.error("获取小程序码geQrtAccessToken失败:{}", responseBody == null ? "null" : responseBody.toString());
return null;
}
log.info("获取小程序码getQrtAccessToken成功:{}", responseBody.toString());
return responseBody.get("access_token");
}
3.获取 小程序码
使用okhttp3发送请求,首先引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
发送请求代码
public AjaxResult getWechatQrCode() {
String qrtAccessToken = wxConfiguration.getQrtAccessToken();
String wechatQrcodeUrl = wxConfiguration.xcxWechatQrcodeUrl() + qrtAccessToken;
JSONObject jsonBody = new JSONObject();
jsonBody.put("scene", "你要携带的参数");
String url = null;
try {
byte[] bytes = getWechatQrcodeByOkhttp3(wechatQrcodeUrl, jsonBody);
if (bytes == null) {
hrow new RuntimeException("【小程序码】Failed to retrieve QR code.");
}
//可以返回Base64
String imageBase64 = Base64.getEncoder().encodeToString(bytes);
log.info("【小程序码】,bytes:{}, base64:{}", bytes.length, imageBase64);
//也可以上传服务器或资源管理oss等,返回图片链接url
MultipartFile multipartFile = new ByteArrayMultipartFile(bytes, "file", "qrcode.png", "image/png");
String filePath = RuoYiConfig.getUploadPath();
url = FileUploadUtils.upload(filePath, multipartFile);
} catch (Exception e) {
log.error("【小程序码】请求失败,engineerId:{}", engineerId, e);
return AjaxResult.error("请求小程序码失败");
}
return AjaxResult.success("成功", url);
}
public byte[] getWechatQrcodeByOkhttp3(String url, JSONObject jsonBody) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonBody.toString());
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
return response.body().bytes();
} else {
log.error("【小程序码】Failed response, status code: {}", response.code());
}
} catch (IOException e) {
log.error("【小程序码】Request failed", e);
}
return null;
}
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ByteArrayMultipartFile implements MultipartFile {
private final byte[] bytes;
private final String name;
private final String originalFilename;
private final String contentType;
public ByteArrayMultipartFile(byte[] bytes, String name, String originalFilename, String contentType) {
this.bytes = bytes;
this.name = name;
this.originalFilename = originalFilename;
this.contentType = contentType;
}
@Override
public String getName() {
return name;
}
@Override
public String getOriginalFilename() {
return originalFilename;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return bytes.length == 0;
}
@Override
public long getSize() {
return bytes.length;
}
@Override
public byte[] getBytes() throws IOException {
return bytes;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(bytes);
}
@Override
public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
java.nio.file.Files.write(dest.toPath(), bytes);
}
}