萌新第一次写文章如有不对地方多多指教。
思路:
1.根据官方文档先获取ACESS_TOKEN
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET"
用相应AppID和Secret替换其中内容组装成完整的接口链接。
2.然后再根据官方接口获取图片二维码
https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN(此接口为为官方接口2,其他同理)
用相应ACCESS_TOKEN替换其中内容组装成完整的接口链接。再添加post传参内容
具体步骤:
步骤一:获取token
public JSONObject getAccessToken() throws ClientProtocolException, IOException {
String appid = config.appid;
String secret = config.secret;
//替换获取token链接中AppID和Secret
String requestUrl = URL_TOKEN.replace("$APPID", appid).replace("$APPSECRET", secret);
//创建http连接客户端
CloseableHttpClient client = HttpClients.createDefault();
//使用HTTPGet方法访问获取token链接url
HttpGet method = new HttpGet(requestUrl);
//执行HttpGet方法
HttpResponse response = client.execute(method);
//返回对象最后处理成jsonObject
logger.info("微信获取微信小程序token 向微信服务器发起get请求:" + requestUrl);
HttpEntity httpEntity = response.getEntity();
if (null == httpEntity) {
logger.error("微信获取微信token 和微信通信返回值为null");
throw new BizException("服务器异常");
}
String jsonString = "";
try {
jsonString = EntityUtils.toString(httpEntity);
} catch (IOException e) {
logger.error("微信获取微信小程序token 返回值转换字符串是不", e);
throw new BizException("服务器异常");
}
JSONObject result = JSONObject.parseObject(jsonString);
if (null == result) {
logger.error("微信获取微信小程序token 返回值不是json字符串");
throw new BizException("服务器异常");
}
if (null != result.get("errcode") && result.getInteger("errcode") > 0) {
logger.error("微信获取微信小程序token 微信服务器返回错误:" + jsonString);
throw new BizException("服务器异常");
}
logger.info("微信获取微信小程序token " + result);
return result;
}
步骤二:组装获取二维码的POST请求
/**
url:传入带token的获取二维码url链接
map:获取post参数
*/
public byte[] doImgPost(String url,Map
byte[] result = null;
//使用HTTPPost方法访问获取二维码链接url
HttpPost httpPost = new HttpPost(url);
//创建http连接客户端
CloseableHttpClient client = HttpClients.createDefault();
//设置头响应类型
httpPost.addHeader("Content-Type", "application/json");
try {
// 设置请求的参数
JSONObject postData = new JSONObject();
for (Map.Entry
postData.put(entry.getKey(), entry.getValue());
}
httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
logger.info("微信获取微信二维码post数据 " + postData.toString());
//返回的post请求结果
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toByteArray(entity);
} catch (ConnectionPoolTimeoutException e) {
logger.error("http get throw ConnectionPoolTimeoutException(wait time out)", e);
} catch (ConnectTimeoutException e) {
logger.error("http get throw ConnectTimeoutException", e);
} catch (SocketTimeoutException e) {
logger.error("http get throw SocketTimeoutException", e);
} catch (Exception e) {
logger.error("http get throw Exception", e);
} finally {
httpPost.releaseConnection();
}
//最后转成2进制图片流
return result;
}
步骤3.编写controller层实习功能
@RequestMapping(value = "/smallProgramCode")
public void smallProgramCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
//设置响应类型
response.setContentType("image/png");
//获取userid
String userId = request.getParameter("user_id");
//获取AccessToken
String accessToken = authService.getAccessToken().getString("access_token");
System.out.println(accessToken);
//组装url
String url = SappCodeAuthService.URL_QRCODE.replace("$ACCESS_TOKEN", accessToken) ;
System.out.println("获取二维码链接"+ url);
//组装参数
Map
XpUser user = userService.getUserByUserId(Integer.parseInt(userId));
String isStr="";
Integer id = 0;
if (user.getIsStore().equals(0)) {
isStr ="ownInviteId=";
id = user.getOwnInviteId();
}else {
isStr ="inviteId=";
id = user.getInviteId();
}
//二维码携带参数 不超过32位
paraMap.put("scene", isStr+id );
//二维码跳转页面
paraMap.put("path", "pages/index");
paraMap.put("width", "250");
// paraMap.put("auto_color", false);
// paraMap.put("line_color", "{\"r\":\"0\",\"g\":\"0\",\"b\":\"0\"}");
//执行post 获取数据流
byte[] result = authService.doImgPost(url, paraMap);
//输出图片到页面
PrintWriter out = response.getWriter();
InputStream is = new ByteArrayInputStream(result);
int a = is.read();
while (a != -1) {
out.print((char) a);
a = is.read();
}
out.flush();
out.close();
}
步骤四:测试
本地访问localhost:自己定义端口/../smallProgramCode?user_id=1138(参数可以自己随意更改)