1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 微信小程序生成二维码接口调用

微信小程序生成二维码接口调用

时间:2022-10-28 19:23:20

相关推荐

微信小程序生成二维码接口调用

小程序生成二维码这个接口可以在小程序里面做, 也可以在java后台做, 此篇博客记录的是在java后台请求微信的接口生成;

场景:

如果要生成带参数二维码拿出去做裂变推广, 生成的二维码数量多. 此时不可能一个个通过草料或者阿拉丁来做, 只能请求官方的接口生成;

准备工作:

a. 小程序的appId

b.小程序的secret

步骤如下:

1. 获取小程序的access_token, 该值是生成二维码的必要因素, 获取方式如下:

/*** 获取access_token** @return*/public String getAccessToken() {Map<String, String> map = new LinkedHashMap<>();map.put("grant_type", "client_credential");map.put("appid", APP_ID);//改成自己的appidmap.put("secret", SECRET);String res = sendPost(tokenUrl, map);JSONObject parse = JSONObject.parseObject(res);if (parse.getString("access_token") != null || parse.getString("access_token") != "") {return parse.getString("access_token");} else {return null;}}

2. 通过access_token获取小程序的二维码:

public InputStream getminiqrQr(String accessToken, String userId) {InputStream in = null;try {URL url = new URL("https://api./wxa/getwxacodeunlimit?access_token=" + accessToken);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("POST");httpURLConnection.setDoInput(true);httpURLConnection.setDoOutput(true); PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());// 发送请求参数JSONObject paramJson = new JSONObject();paramJson.put("scene", "useId="+userId);paramJson.put("path", "pages/invite/invite");paramJson.put("width", 430);paramJson.put("is_hyaline", false);// 生成二维码颜色为黑色paramJson.put("auto_color", false);JSONObject lineColor = new JSONObject();lineColor.put("r", 0);lineColor.put("g", 0);lineColor.put("b", 0);paramJson.put("line_color", lineColor);printWriter.write(paramJson.toString());// flush输出流的缓冲printWriter.flush();in = httpURLConnection.getInputStream();return in;} catch (Exception e) {e.printStackTrace();}return in;}

拿到二维码的流, 是读到本地还是读到对象存储自己搞完事了, 需要注意的是几个post请求入参:

path: 跳转小程序的页面地址, 前面不要 "/", 如果要带参数不可以在这里, 只能在第二个参数scene里添加

scene: 填放用户需要携带的参数

width: 尺寸

is_hyaline: 背景色要不要

auto_color: 线条颜色是否是自动的颜色, true的时候不需要设置RGB颜色

另外这个接口是不限次数的, 还有两个是限制次数的接口,可以参考官方文档

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。