导入相关依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
WX服务类
public class WXService {
private static final Logger log = LoggerFactory.getLogger(WXService.class);
private static RequestConfig requestConfig;
static {
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
}
//微信获取access_token接口
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?" +
"grant_type=client_credential";
//微信获取小程序码接口
private static final String GET_APPLET_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
//小程序appid
private static final String APP_ID = "wx1ada744eeb2b9544";
//小程序秘钥
private static final String APP_SECRET = "6f19f511617cb96685444c3cdd21ca13";
/**
* 获取小程序二维码图片链接
* @param scene 场景值
* @return
*/
public String getAppletCode(String scene) {
try {
// 1.获取access_token
String accessToken = getAccessToken();
// 2.获取图片字节流
String url = GET_APPLET_CODE_URL.concat("?access_token=").concat(accessToken);
JSONObject jsonParam = new JSONObject();
//扫码后进入小程序页面的路径
jsonParam.put("page","pages/order/upload");
jsonParam.put("scene",scene);
byte[] bytes = httpPostReturnByte(url, jsonParam);
if (null != bytes && bytes.length > 0) {
// 3.上传图片服务器,获取图片链接(这部分就看个人实现了)
return "图片链接";
}
} catch (Exception e) {
log.error("获取小程序码失败,scene={}, e={} ", scene, e);
}
return null;
}
/**
* 获取小程序码请求
* @param url
* @param jsonParam
* @return
*/
public static byte[] httpPostReturnByte(String url, JSONObject jsonParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try {
setEncoding(jsonParam, httpPost);
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if ("image/jpeg".equals(result.getEntity().getContentType().getValue())) {
return EntityUtils.toByteArray(result.getEntity());
} else {
String s = EntityUtils.toString(result.getEntity(), "utf-8");
log.debug("post请求提交失败: url= {}, 错误原因={}", url, s);
}
}
} catch (IOException e) {
log.info("获取小程序码,post请求提交失败: url= {}, e={}", url, e);
} finally {
httpPost.releaseConnection();
}
return null;
}
/**
* 解决中文乱码
* @param jsonParam
* @param httpPost
*/
private static void setEncoding(JSONObject jsonParam, HttpPost httpPost) {
if (null != jsonParam) {
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
}
/**
* 获取access_token
* @return
*/
public static String getAccessToken() {
log.info("获取小程序accessToken开始...");
String url = GET_ACCESS_TOKEN_URL.concat("&appid=").
concat(APP_ID).concat("&secret=").concat(APP_SECRET);
JSONObject jsonObject = httpGet(url);
if (null != jsonObject && null != jsonObject.get("access_token")) {
String accessToken = jsonObject.getString("access_token");
log.info("获取小程序accessToken结束,accessToken={}",accessToken);
return accessToken;
} else {
log.error("获取小程序accessToken失败,返回信息:{}", jsonObject.toString());
return "";
}
}
/**
* 发送get请求
* @param url 路径
* @return
*/
private static JSONObject httpGet(String url) {
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
log.info("请求响应结果statusCode={}", response.getStatusLine().getStatusCode());
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
} else {
log.warn("get请求提交失败:url={}", url);
}
} catch (IOException e) {
log.warn("get请求提交失败:url={},e={}", url, e);
} finally {
request.releaseConnection();
}
return jsonResult;
}
}