微信二维码生成

时间:2022-04-22 13:28:33

@Action(value = "weweb207Init", results = {
@Result(name = "success", location = "/jsp/Weweb207.jsp"),
@Result(name = "error", location = "/jsp/error.jsp") })
public String execute() throws Exception {

appid = getSessionAppID();

if (CommonUtil.getSystemValue(PropertyConstants.WXINFO_APPID).equals(
appid)) {
secret = CommonUtil.getSystemValue(PropertyConstants.WXINFO_APPSECRET);
}

/*********************
* AccessToken获取
*********************/
if (!WechatMsgSendUtil.getWeiXinAccessToken(appid, secret)) {
System.exit(-1);
}else{
access_token = WechatMsgSendUtil.access_token;
}

// 取得UnionId
recommId = getUnionId();
nickname = getNickname();
erweimatupianPath = CommonUtil.getSystemValue(PropertyConstants.QRCODE_TEMP_PATH);
//// 自动创建文件夹
File file = new File(erweimatupianPath);// 定义一个文件流
file.mkdir();
erweimatupian = recommId.concat(".jpg");
erweimatupianPath = erweimatupianPath.concat(erweimatupian);

// 生成永久二维码
String ticket = createPermanentQRCode(access_token,10000).getTicket();
// 生成临时二维码
//String ticket = createTemporaryQRCode(access_token,2592000,10000).getTicket();
getImageQRCode(ticket,erweimatupianPath);

// config设定
WebUtils.gainSign(appid, form.getUrl(), form);
return SUCCESS;
}

/**
*
* 获取微信access_token <功能详细描述>
*
* @return
* @throws IOException
* @throws Exception
* @see [类、类#方法、类#成员]
*/
public static boolean getWeiXinAccessToken(String appidP, String secretP) throws Exception {

if (StringUtils.isBlank(appidP) || StringUtils.isBlank(secretP)) {
return false;
}
String accessToken = "";

// 延选Fresh
if (CommonUtil.getSystemValue(PropertyConstants.WXINFO_APPID).equals(
appidP)) {
accessToken = WebUtils.gainTokenAndPutInCache();

} else { // 延选农场
accessToken = WebUtils.gainTokenAndPutInCache2();
}
System.out.println(accessToken);
access_token = accessToken;
return true;
}

/**
* 二维码生成【永久二维码】
* @param token access_token
* @param sceneId 小参数
* @return 二维码图片生成code
* @throws JSONException 异常
*/
public WeixinQRCode createPermanentQRCode(String token, int sceneId) throws JSONException {
String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN"+"&unionId=UNIONID&nickname=NICKNAME&lang=zh_CN";
requestUrl = requestUrl.replace("TOKEN", token);
requestUrl=requestUrl.replace("UNIONID", recommId);
requestUrl=requestUrl.replace("NICKNAME", nickname);
String jsonMsg = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": %d}}}";
String aaString= httpsRequest(requestUrl, "POST",String.format(jsonMsg, sceneId));
JSONObject json = new JSONObject(aaString);
WeixinQRCode w = null;
if (json != null) {
try {
w = new WeixinQRCode();
w.setTicket(json.getString("ticket"));
w.setUrl(json.getString("url"));
} catch (Exception e) {
int errorCode = json.getInt("errorcode");
String errorMsg = json.getString("errmsg");
System.out.println(errorCode + ":" + errorMsg);
}
}
return w;
}

 

/**
* 二维码生成【临时二维码】
* @param token access_token
* @param expireSeconds 有效时间
* @param sceneId 小参数
* @return 二维码图片生成code
* @throws JSONException 异常
*/
public WeixinQRCode createTemporaryQRCode(String token,int expireSeconds,int sceneId) throws JSONException{
String requestUrl="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN"+"&recommId=UNIONID&nickname=NICKNAME&lang=zh_CN";
requestUrl=requestUrl.replace("TOKEN", token);
requestUrl=requestUrl.replace("UNIONID", recommId);
requestUrl=requestUrl.replace("NICKNAME", nickname);
String jsonMsg="{\"expire_seconds\": %d, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": %d}}}";
String aaString = httpsRequest(requestUrl, "POST", String.format(jsonMsg, expireSeconds,sceneId));
JSONObject json = new JSONObject(aaString);
WeixinQRCode w=null;
if(json!=null){
try{
w=new WeixinQRCode();
w.setExpire_seconds(json.getInt("expire_seconds"));
w.setTicket(json.getString("ticket"));
w.setUrl(json.getString("url"));
}catch(Exception e){
int errorCode=json.getInt("errorcode");
String errorMsg=json.getString("errmsg");
System.out.println(errorCode+":"+errorMsg);
}
}
return w;
}

 

/**
* 通过ticket换取二维码
* @param ticket 二维码生成用ticket
* @param savePath 图片保存路径
* @throws Exception 异常
*/
public void getImageQRCode(String ticket,String savePath)
throws Exception {
String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
requestUrl = requestUrl.replace("TICKET",
URLEncoder.encode(ticket, "UTF-8"));
//ServletOutputStream writer = null;
try {
URL url = new URL(requestUrl);// 二维码路径【可查看二维码】
HttpURLConnection httpUrlConn = (HttpURLConnection) url
.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();

// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
FileOutputStream bos = new FileOutputStream(new File(savePath));
int temp = 0;
while ((temp = bis.read()) != -1) {
bos.write(temp);
}
bos.close();
bis.close();

//response.setContentType("multipart/form-data");
//writer = response.getOutputStream();
//byte[] buf = new byte[1024];
//int len = 0;
//while ((len = inputStream.read(buf)) != -1) {
//writer.write(buf, 0, len); // 写
//}
//writer.flush();

// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();

} catch (Exception e) {
e.printStackTrace();
}
}

 

/**
* 发送请求
* @param requestUrl 详情url
* @param requestMethod 设置请求方式
* @param outputStr 发丝难过的数据流
* @return 请求方式
*/
private String httpsRequest(String requestUrl, String requestMethod,
String outputStr){
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type",
"application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("连接超时:\n" + ce);
} catch (Exception e) {
log.error("https请求异常:\n" + e);
}
return null;
}