/**
* 获取小程序二维码
**/
@Anonymous
@GetMapping("/coco")
public void getWXCode(HttpServletResponse response, String deptId, String processId) throws Exception {
String appId = ""; //自己小程序的appid
String secret = ""; //自己小程序的密钥
try {
//url是微信提供的接口
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + getWxAcesstoken(appId, secret);
Map<String, String> param = new HashMap<>();
String company = deptId + "," + processId;
//下面的page 可以指定扫码后跳转的页面。具体可以参考微信开发平台的文章
String page ="service/page/index/index";
param.put("page", page);
//scene 为可以携带的参数,我这里携带了两个id,具体可以按照你自己的需求
param.put("scene", company);
String json = JSON.toJSONString(param);
sendPost(url, json, response);
log.error("二维码生成成功");
} catch (Exception e) {
log.error("获取二维码异常");
throw new Exception(e.getMessage());
}
}
public static void sendPost(String URL, String json, HttpServletResponse httpServletResponse) {
InputStream inputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost 发送post请求
HttpPost httppost = new HttpPost(URL);
//头文件
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 获取相应实体
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
ServletOutputStream outStream = httpServletResponse.getOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inputStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 生成tk
*
* @param wxappid
* @param wxappkey
* @return
* @throws Exception
*/
public static String getWxAcesstoken(String wxappid, String wxappkey) throws Exception {
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxappid + "&secret=" + wxappkey;
try {
String jsonstr = HttpUtil.get(tokenUrl);
JSONObject jsonObject = JSON.parseObject(jsonstr);
if (jsonObject.containsKey("access_token")) {
String accesstoken = jsonObject.getString("access_token");
return accesstoken;
} else {
log.error("未获取到token");
throw new Exception("未获取到token");
}
} catch (Exception e) {
log.error("未获取到token");
throw new Exception(e.getMessage());
}
}