微信生成临时带参数二维码实战
相信大家在进行公众号开发的时候会遇到扫描二维码需要在二维码里面添加一些特定的参数的需求,通过扫描对应的二维码来处理相关的业务需求,今天我就来整理下之前实现的微信二维码生成临时带参二维码的具体实现。
第一步:首先确定自己需要嵌入二维码的参数
这里我门就拿格式为:type+,+uid+,+id来举例,需要将这种格式参数嵌入到二维码中。
第二步:配置相关的二维码配置
具体的见下方的代码,详情见对应的代码注释
package com.eone.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class HttpTool {
private static Logger logger = LoggerFactory.getLogger(HttpTool.class);
/**
* POST请求,字符串形式数据
* @param url 请求地址
* @param param 请求数据
* @param charset 编码方式
*/
public static String sendPostUrl(String url, String param, String charset) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
package com.eone.biz.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.boycai.api.annotation.AuthCheck;
import com.boycai.base.Utils;
import com.boycai.base.bean.DataMap;
import com.boycai.base.bean.ResultMap;
import com.boycai.base.util.JsonUtils;
import com.eone.common.base.web.BaseController;
import com.eone.common.util.HttpTool;
import com.eone.wx.util.MpUtils;
import com.google.gson.Gson;
/**
* 生成带参数二维码
*/
@AuthCheck(value = false, log = true)
@Controller
@RequestMapping("/qrCode")
public class QrCodeController extends BaseController {
private final static String QR_SCENE = "QR_STR_SCENE";// 临时二维码
private String CREATE_TICKET_PATH = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";// 创建二维码
private String SHOW_QRCODE_PATH = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";// 通过ticket换取二维码
private Integer EXPIRE_SECONDS = 1800;// 过期时间:30分钟
private static final String DEFAULT_URL_ENCODING = "UTF-8";//格式编码设置
/**
* 创建临时带参数二维码
*
* @param articleId
* @return
* @throws UnsupportedEncodingException
*/
@ResponseBody
@RequestMapping("/createTicket")
public ResultMap createTicket() {
try {
//格式:type+,+uid+,+id; 如:"1," + uid + "," + id
String sceneStr = getStrValid("sceneStr");
String accessToken = MpUtils.getToken();//通过appid访问接口获取到accessToken凭证
if (Utils.notBlankStr(accessToken)) {
Map<String, String> intMap = new HashMap<String, String>();
intMap.put("scene_str", sceneStr);//前台传参二维码带参格式
Map<String, Map<String, String>> mapMap = new HashMap<String, Map<String, String>>();
mapMap.put("scene", intMap);
Map<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("expire_seconds", EXPIRE_SECONDS);// 过期时间:30分钟
paramsMap.put("action_name", QR_SCENE);// 临时二维码
paramsMap.put("action_info", mapMap);
String data = new Gson().toJson(paramsMap);//格式转换
String res = HttpTool.sendPostUrl(CREATE_TICKET_PATH.replace("ACCESS_TOKEN", accessToken), data,
"UTF-8");//通过accessToken获取请求结果
DataMap dataMap = JsonUtils.parseData(res);//得到结果
String ticket = dataMap.getStr("ticket");//得到ticket信息
ticket = URLEncoder.encode(ticket, DEFAULT_URL_ENCODING);//设置编码格式
return ResultMap.init().put("expireSeconds", EXPIRE_SECONDS).put("path",
SHOW_QRCODE_PATH.replace("TICKET", ticket));//替换TICKET获取临时二维码路径赋值到前台
}
} catch (Exception e) {
}
return ResultMap.error();
}
}
相关的注释代码已经给大家备注清楚,结果就是将生成的path返回到前台进行二维码赋值,这样带参数的二维码就这样生成了。