使用Spring Boot 生成微信小程序二维码进入对应页面携带参数-摘录
来由
最近使用uni-app
开发微信小程序,客户有一个需求就是后台系统能根据后台中的企业信息生成对应的企业微信小程序二维码,提供给企业用户进行扫描注册,从而减少后台系统进行员工信息录入。
个人建议
微信的文档更新速度很快建议先每次开发微信相关的业务最好先看下微信官方的文档再进行百度查询防止编写出问题找不到原因。
微信api
微信二维码有3种类型的具体的可以看微信介绍
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
我使用的这种:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html
还有注意微信要是已经上线的小程序才可以,但本地测试也是可以的只是不能上线体验
进入微信公众平台 ->小程序 ->开发 -> 开发管理 ->开发设置->扫普通链接二维码打开小程序
进行相关配置
因为要Java后端生成所以要使用微信的服务端地址生成二维码
请求地址:
POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
后端开发
查看微信的这个请求参数要求携带 access_token 接口凭证 那获取生成二维码的过程就简单了
1 获取ACCESS_TOKEN -> 2 调用微信二维码生成地址
获取 access_token
微信文档:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
这里微信要求携带
appid 和secret
JAVA 代码如下:
使用到了fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
1,创建微信配置类:
@Component
public class WechatConfig {
public static String wechatMiniAppId;
public static String wechatMiniSecret;
@Value("${wechat.mini.appid:''}")
public void setWechatMiniAppId(String wechatMiniAppId) {
WechatConfig.wechatMiniAppId = wechatMiniAppId;
}
@Value("${wechat.mini.secret:''}")
public void setWechatMiniSecret(String wechatMiniSecret) {
WechatConfig.wechatMiniSecret = wechatMiniSecret;
}
}
2.yml 配置 参数
#微信开发 属性 具体获取查看微信小程序开发
wechat:
mini:
appid : xxxxxx
secret : xxxxxxxxx
3 .获取access_token
创建一个pojo 接收返回结果
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
@Data
public class WeChatAccessResult implements Serializable {
@JSONField(name = "access_token")
private String accessToken;
@JSONField(name ="expires_in")
private String expiresIn;
@JSONField(name ="errcode")
private String errCode;
@JSONField(name ="errmsg")
private String errMsg;
}
这里的HttpUtils 是我公司在公司封装的一个请求类不好公开可以使用HuTool 中的请求HttpUtils
/**
* 微信小程序配置
*
*/
@Component
public class WeChatCommon {
@Value("${wechat.mini.appid}")
private String appId ;
@Value("${wechat.mini.secret}")
private String secret;
/**
* 获取微信access_token
*/
public WeChatAccessResult returnAccessToken() throws IOException {
if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(secret)){
String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
String returnBody = HttpUtils.get(url).body();
WeChatAccessResult weChatAccessResult = JSONObject.parseObject(returnBody, WeChatAccessResult.class);
return weChatAccessResult;
}
return null;
}
}
获取微信二维码
1.封装一个请求 POJO
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html
微信官网说
POST 参数需要转成 JSON 字符串,不支持 form 表单提交 所以我使用pojo 然后使用fastjson 转成json字符串
/**
* 微信请求对象
* https://developers.weixin.qq.com/miniprogram/
* dev/api-backend/open-api/qr-code/wxacode.get.html
*/
@Data
public class WeChatQueryObject implements Serializable {
private String path;
private Integer width;
private boolean auto_color;
// private Object line_color;
private boolean is_hyaline;
}
2.创建生成微信二维码方法
@Component
public class WeChatCommon {
@Value("${wechat.mini.appid}")
private String appId ;
@Value("${wechat.mini.secret}")
private String secret;
/**
* 获取微信access_token
*/
public WeChatAccessResult returnAccessToken() throws IOException {
if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(secret)){
String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
String returnBody = HttpUtils.get(url).body();
WeChatAccessResult weChatAccessResult = JSONObject.parseObject(returnBody, WeChatAccessResult.class);
return weChatAccessResult;
}
return null;
}
/**
* @param weChatQueryObject 查询参数
* @return
* @throws IOException
*/
public BufferedInputStream getWxCode(WeChatQueryObject weChatQueryObject) throws IOException{
WeChatAccessResult weChatAccessResult = returnAccessToken();
if (weChatAccessResult!=null && StringUtils.isNotEmpty(weChatAccessResult.getAccessToken())
&& weChatQueryObject !=null
){
String queryURL ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+weChatAccessResult.getAccessToken();
String wxParams =JSON.toJSONString(weChatQueryObject);
return HttpUtils.post(queryURL,wxParams).bodyStream();
}
return null;
}
}
3.创建生成接口并可以下载这个生成的微信二维码图片
我这里是先让其可以下载二维码 然后保存到后台管理系统中,提供给企业使用
/**
* 微信企业员工注册
* @param companyWxCode 企业信息
* @param response 响应
* @throws Exception
*/
@RequestMapping(value = "wxCompanyCode.do", method = RequestMethod.GET)
@ResponseBody
public void wxCompanyCode(CompanyWxCode companyWxCode, HttpServletResponse response) throws Exception {
Integer companyId = companyWxCode.getCompanyId();
if (companyId!=null){
QMemberTT byId = qMemberTTService.findById(companyId);
String fileName ="wxCode";
if (byId !=null) {
//设置名称 电话号码
fileName =byId.getQyMobile();
}
// TATD 后期添加到yml 中自定义配置
WeChatQueryObject weChatQueryObject = new WeChatQueryObject();
//设置参数
weChatQueryObject.setPath("pages/regist/invitationUser?companyId="+companyId);
weChatQueryObject.setWidth(340);
weChatQueryObject.setAuto_color(true);
//微信二维码封装方法
BufferedInputStream returnWxCode = WeChatCommon.getWxCode(weChatQueryObject);
byte[] buf = new byte[1024];
int len = 0;
// 非常重要
response.reset();
response.setContentType("image/jpeg;");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".jpg");
OutputStream out = response.getOutputStream();
//让其导出
while ((len = returnWxCode.read(buf)) > 0){
out.write(buf, 0, len);
out.flush();
}
returnWxCode.close();
out.close();
}else{
System.out.println("企业信息输入未完全");
}
}
前端
这里使用的是uniapp 可以在微信配置好的页面进行业务开发
//接受到参数 方式一 这个可能是uniapp 的params 自动获取的参数 挺强大的
onLoad(option) {
if (option.companyId) {
option.companyId
console.log(option.companyId)
}
},
//方式二 微信官方提供了这个这个扫码是使用微信那边普通网址链接
onLoad: function(options) {
if (options.q) {
//获取二维码的携带的链接信息
let qrUrl = decodeURIComponent(options.q)
console.log(qrUrl)
}
},
以上就可以完成一个带参数的微信小程序二维码,建议还是多看微信文档,开发这个当时没怎么看文档让坑了不少