1,首先,必须根据小程序的appid和appSecret获取到accessToken 2,然后再根据accessToken去获取指定页面的小程序二维码
public String getAccessToken(){
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);
String accessToken = "";
if (String.valueOf(jsonObject.get("expires_in")).equals("7200")){
accessToken = String.valueOf(jsonObject.get("access_token"));
redisService.set(RedisConstants.WX_ACCESS_TOKEN, accessToken, 7200);
}
return accessToken;
}
public String getActivityQrCodeByAccessToken(String accessToken, LyCreateActivityQrCodeDto lyCreateActivityQrCodeDto) throws Exception {
Map<String, Object> paraMap = new HashMap<>();
paraMap.put("scene", lyCreateActivityQrCodeDto.getScene());
paraMap.put("page", lyCreateActivityQrCodeDto.getPage());
paraMap.put("width", 450);
paraMap.put("auto_color", false);
paraMap.put("is_hyaline", false);
paraMap.put("env_version", "trial");
paraMap.put("check_path", false);
byte[] result = WxUtil.getQrCodeByParam("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken, paraMap);
return QrCodeUtils.getQrCodeUrlByByteStream(result);
}
package com.sport.sportadminserver.common.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.net.SocketTimeoutException;
import java.util.Map;
public class WxUtil {
public static byte[] getQrCodeByParam(String url, Map<String, Object> paraMap) {
byte[] result = null;
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
try {
JSONObject postData = new JSONObject();
for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
postData.put(entry.getKey(), entry.getValue());
}
httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toByteArray(entity);
} catch (ConnectionPoolTimeoutException e) {
e.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return result;
}
}
结果
|