一个通过分享微信小程序码邀请注册的需求。
该需求需要的小程序码数量不少,所以实现的是带参数生成无限个数小程序码接口。
接口地址:https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN,当然这个接口还要需要先实现获得access_token的接口。把接口返回字节流保存到oss上,然后把oss的返回值URL和我们的用户绑定就可以了。
private InputStream getCode(Integer userId ) throws Exception{
RestTemplate rest = new RestTemplate();
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxService.getToken();
Map<String, Object> param = new HashMap<>();
param.put("page","pages/home/home");
param.put("width", 430);
param.put("auto_color", false);
param.put("scene", userId );
Map<String, Object> line_color = new HashMap<>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
log.info("调用生成微信URL接口传参:" + param);
org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
byte[] results = entity.getBody();
InputStream inputStream = new ByteArrayInputStream(results);
return inputStream;
}
以下为该接口POST的参数说明
参数 |
类型 |
默认值 |
说明 |
scene |
String |
最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式) |
|
page |
String |
必须是已经发布的小程序页面,例如 “pages/index/index” ,如果不填写这个字段,默认跳主页面 |
|
width |
Int |
430 |
二维码的宽度 |
auto_color |
Bool |
false |
自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调 |
line_color |
Object |
{“r”:”0”,”g”:”0”,”b”:”0”} |
auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {“r”:”xxx”,”g”:”xxx”,”b”:”xxx”} |
用户扫描码进入小程序后,开发者需在对应page页面获取码中的scene值,再做处理,scene在传值过程中需要严格参照上表格里的说明。另外page参数不能携带任何参数,参数只能在sene中配置。
前端接收时代码:
Page({ onLoad: function(options) { // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene var scene = decodeURIComponent(options.scene) }})
通过该接口生成的小程序码,数量无限制,永久有效。POST参数需要转成json字符串,不支持form提交。不知道平台官方文档,参考的是第三方平台,想深入研究的自己去找吧。