背景
在uniapp微信小程序开发过程中, 经常需要生成小程序码。
用于海报,签到等功能。这篇文章主要记录这个业务场景如何完成。
后端代码
首先就是后端boot生成微信小程序码。
public String generateQrCode(String page, String certNumber) {
String fileDir = "play/min-code/" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + ".png";
return WxUtil.downloadMiniCode(fileDir, page, certNumber, appId, appSecret);
}
- WxUtil工具类
public class WxUtil {
public static String GET_MINICODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
public static String getAccessTokenAsUrl(String appId, String appSecret) {
String tokenStr = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret + "");
log.info(tokenStr);
JSONObject jsonObject = JSONObject.parseObject(tokenStr);
return "?access_token=" + jsonObject.getString("access_token");
}
/**
* 下载带参数的小程序二维码
*
* @param path 保存图片的的path(该路径一定要线上发布之后的,否则会生成失败)
* @param certNumber 带过去小程序的参数,一般为你的业务参数,建议是id或者number,scene可以多个参数=分隔符 :"1_2_3_4"
*/
public static String downloadMiniCode(String path, String page, String certNumber, String appId, String appSecret) {
Map<String, Object> paramMap = new HashMap<>(12);
paramMap.put("page", page);
paramMap.put("scene", certNumber);
paramMap.put("is_hyaline", true);
try {
String buildUrl = GET_MINICODE_URL + getAccessTokenAsUrl(appId, appSecret);
URL url = new URL(buildUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 提交模式
httpURLConnection.setRequestMethod("POST");
//连接超时 单位毫秒
httpURLConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpURLConnection.setReadTimeout(10000);
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
printWriter.write(JSON.toJSONString(paramMap));
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
String qrCodeUrl = OssBootUtil.upload(httpURLConnection.getInputStream(), path);
return qrCodeUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
以上代码便可以生成微信小程序码。
uniapp
接下来主要就是前端在扫描之后如何解析小程序码携带的参数,以便在业务中使用。
- 生成小程序码的参数
{"path":"pages/index/index","params":"id=1"}
- uniapp页面获取参数的方式
//在onLoad生命周期函数中获取参数值
onLoad: function(options) {
const scene = decodeURIComponent(options.scene)
console.log("--scene--"+ scene);
}
//控台输出结果: --scene--id=34