java获取微信小程序二维码
近期正好遇到了,随手记录下
首先获取微信小程序二维码需要小程序的appid 以及secret
然后根据appid和secret去获取小程序的token 即 access_token
获取token发送给微信的路径"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
//获取微信token
private String getAccessToken() throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
//SysUtil是自己封装的HttpUtils工具类方法
JSONObject get = SysUtil.getCmHttpReqRes(url, "GET", null, null);
if (get.getString("access_token") == null) ExceptionUtil.throwException("获取AccessToken失败:" + get.getString("errmsg"));
return get.getString("access_token");
}
然后根据token 获取二维码图片
获取二维码的方式和获取token大同小异 路径都是写死的"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token
int width = 430;
Boolean auto_color = false;
Map<String,Object> lineColor = new HashMap<>();
lineColor.put("r",0);
lineColor.put("g",0);
lineColor.put("b",0);
Boolean is_hyaline = false;
Map<String,Object> data = new HashMap<>();
data.put("scene",scene);//这里是写入二维码的参数,扫描二维码能获取到的
data.put("page",page);//扫二维码进入的小程序路径 不给默认进入首页
data.put("width",width); //二维码的宽度
data.put("auto_color",auto_color); //auth_color 为 false 时生效,使用 rgb 设置颜色
//例如 {"r":"xxx","g":"xxx","b":"xxx"},十进制表示
data.put("is_hyaline",is_hyaline); //二维码是否需要透明底色, is_hyaline 为true时,生成透明底色的小程序码
//路径也是固定的"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
//这里有个坑,需要用HttpResponse获取,不然会有问题
HttpResponse httpResponse = HttpUtils.doPost(url, new JSONObject(data));
//拿到httpResponse后,在获取里面的图片
InputStream content = httpResponse.getEntity().getContent();
//二维码的图片处理见 Java图片处理笔记
HttpUtils工具类需要自取
public class HttpUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
public static HttpResponse doPost(String url, JSONObject jsonData) {
// 指定Post请求
HttpPost httpPost = new HttpPost(url);
// 创建httpclient
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
HttpResponse httpResponse;
// 返回的json
JSONObject jsonObject = null;
// 封装post请求数据
StringEntity entity = new StringEntity(jsonData.toString(), "utf-8");
httpPost.setEntity(entity);
try {
// 发送请求
httpResponse = httpClient.execute(httpPost);
// 判断请求是否成功
if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
// 得到请求响应信息
// String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
// 返回json
// jsonObject = new JSONObject(Boolean.parseBoolean(str));
return httpResponse;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}