前言:
需求场景,用户通过扫描小程序码,到指定的页码,希望能帮到大家,切记,要等到小程序发版测能测试。
1、微信官网
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html 官网中给出了几个接口:
我们用接口b,wxacode.getUnlimited
看到官网说明:page会跳用到某一个界面,如果页面有参数,放在scene里,这里有一掉我们要注意,小程序必须要发版,才能进行测试。
2、代码
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@Value("${wx.miniapp.url.getTokenUrl}")
private String GET_TOKEN_URL;
@Value("${wx.miniapp.configs[2].appid}")
private String appId;
@Value("${wx.miniapp.configs[2].secret}")
private String secret;
@Value("${wx.miniapp.url.getQrCodeUrl}")
private String GET_QR_CODE_URL;
@Value("${tmp.save.url}")
private String SAVE_IMG_URL;
/**
* 获得小程序accessToken
*
* @return
*/
public String getAccessToken() {
String fullUrl = String.format(GET_TOKEN_URL, appId, secret);
String result = HttpUtil.get(fullUrl);
if (StringUtils.isBlank(result)) {
log.info(QR_CODE_APPID_SECRET_FAIL.getMessage());
throw new ServiceException(MbUserResultEnum.QR_CODE_APPID_SECRET_FAIL);
}
log.info("getAccessToken(),result:{}", result);
JSONObject jsonObject = JSON.parseObject(result);
String accessToken = (String) jsonObject.get("access_token");
if (StringUtils.isBlank(accessToken)) {
log.info(QR_CODE_APPID_SECRET_FAIL.getMessage());
throw new ServiceException(MbUserResultEnum.QR_CODE_APPID_SECRET_FAIL);
}
return accessToken;
}
/**
* 从小程序获得二维码图片
*
* @param req
* @return
*/
private byte[] getImgByWX(QrCodeMappingReq req) {
String accessToken = getAccessToken();
String fullUrl = String.format(GET_QR_CODE_URL, accessToken);
JsonObject scene = new JsonObject();
scene.addProperty("scene", req.getQrCode());
if(null != req.getPage()){
scene.addProperty("page",req.getPage());
}
if(null != req.getCheck_path()){
scene.addProperty("check_path",req.getCheck_path());
}
if(null != req.getEnv_version()){
scene.addProperty("env_version",req.getEnv_version());
}
if(null != req.getWidth()){
scene.addProperty("width",req.getWidth());
}
if(null != req.getAuto_color()){
scene.addProperty("auto_color",req.getAuto_color());
}
if(null != req.getLine_color()){
scene.addProperty("line_color",req.getLine_color());
}
if(null != req.getIs_hyaline()){
scene.addProperty("is_hyaline",req.getIs_hyaline());
}
log.info("scene:,{}",scene.toString());
byte[] bytes = HttpRequest.post(fullUrl).body(scene.toString()).execute().bodyBytes();
if (null == bytes) {
log.info(MbUserResultEnum.WX_CREATR_IMG_FAIL.getMessage());
throw new ServiceException(MbUserResultEnum.WX_CREATR_IMG_FAIL);
}
return bytes;
}
调用getImgByWX方法:生成二维码:
然后微信扫二维码生成 page下配置的页面: