微信公众平台生成带参数的二维码官方文档
分为三个部分: 获取access_token、通过ticket换取二维码、生成带参数的二维码
特别注意:需要有生成二维码的权限。
整个代码带有引入包,能运行。
有个问题
"{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}"
下面这个地方本来想用bean拼接,然后json转。但是怎么都不好用,将官网例子和自己的比较没有任何区别。但是就是报参数类型不正确。所以直接写死了
直接上代码:
1、常量
public class WechartConst {
public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ WechartConst.APPID +"&secret="
+ WechartConst.SECRET;
//生成带参数的二维码
public static final String CREATE_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
//通过ticket换取二维码
public static final String SHOW_QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
public static final String APPID = "xxx";
public static final String SECRET = "xxxx";
public static final String IMG_NAME = "微信二维码";
public static final String SAVE_IMG_ADDR = "C:\Users\admin\Desktop\";
}
2、http请求
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.X509Certificate;
@Slf4j
public class HttpsUtil {
public static JSonObject request(String requestUrl, String requestMethod, String outputStr) {
StringBuffer buffer = new StringBuffer();
JSonObject jsonObject ;
try {
// 创建SSLContext对象,并使用我们制定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
httpUrlConn.disconnect();
log.debug("https buffer:" + buffer.toString());
} catch (ConnectException ce) {
log.error("server connection timed out");
} catch (Exception e) {
log.error( e.getMessage());
}
jsonObject = JSON.parseObject(buffer.toString());
return jsonObject;
}
static class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
3、调用方法
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.his.operation.model.entity.QrCodeParam;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
@Slf4j
public class TemporaryQRcode {
public static String ACCESS_TOKEN = "";
public void getAccessToken() {
JSonObject jsonObject = HttpsUtil.request(WechartConst.GET_TOKEN_URL, "GET", null);
if (null != jsonObject) {
String response = jsonObject.toJSonString();
if (!jsonObject.containsKey("errcode")) {
String accessToken = jsonObject.getString("access_token");
System.out.println("获取access_token成功" + response);
ACCESS_TOKEN = accessToken;
} else {
log.error("临时带参二维码ticket失败:" + response);
}
}
}
public String getTempQrcode(int expireSeconds, int sceneId, String savePath) {
// 需要提交json数据
QrCodeParam qrCodeParam = new QrCodeParam();
QrCodeParam.ActionInfo actionInfo = qrCodeParam.new ActionInfo();
QrCodeParam.ActionInfo.Scene scene = actionInfo.new Scene();
//设置场景值
scene.setSceneId(sceneId);
actionInfo.setScene(scene);
qrCodeParam.setActionInfo(actionInfo);
qrCodeParam.setActionName("QR_SCENE");
qrCodeParam.setExpireSeconds(expireSeconds);
getAccessToken();
String ticket = getTicket(JSON.toJSonString(qrCodeParam));
//是否保存二维码图片,不保存可直接返回qrCodeUrl
//String qrCodeUrl = WechartConst.SHOW_QRCODE_URL.replace("TICKET", ticket);
return getQRcode(ticket, savePath);
}
private String getTicket(String qrCodeParam) {
String ticket = null;
// 拼接请求地址
String requestUrl = WechartConst.CREATE_QRCODE_URL.replace("TOKEN", ACCESS_TOKEN);
// 创建临时带参二维码
JSonObject jsonObject = HttpsUtil.request(requestUrl, "POST", "{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}");
if (null != jsonObject) {
String response = JSON.toJSonString(jsonObject);
if (!jsonObject.containsKey("errcode")) {
ticket = jsonObject.getString("ticket");
System.out.println("临时带参二维码ticket成功" + response);
} else {
log.error("临时带参二维码ticket失败:" + response);
}
}
return ticket;
}
private String getQRcode(String ticket, String savePath) {
String filepath;
String requestUrl = WechartConst.SHOW_QRCODE_URL.replace("TICKET", ticket);
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (!savePath.endsWith("/")) {
savePath += "/";
}
// 将ticket 作为文件名
filepath = savePath + WechartConst.IMG_NAME + ".jpg";
// 将微信服务器返回的输入流写入文件
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(new File(filepath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
conn.disconnect();
System.out.println("根据ticket换取二维码成功");
} catch (Exception e) {
filepath = null;
log.error("根据ticket换取二维码失败" + e.getMessage());
}
return filepath;
}
}
4、miain方法
public static void main(String[] args) {
TemporaryQRcode temporaryQRcode = new TemporaryQRcode();
//前两个参数没用
temporaryQRcode.getTempQrcode(0, 0, WechartConst.SAVE_IMG_ADDR);
}
总结:



