1:获取二维码流程
微信官方接口
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
所需要的参数
1.1 获取access_token
微信官方接口
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
public static void main(String[] args) {
String s=sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="+小程序唯一凭证+"&secret="+小程序唯一凭证密钥+"");
JSONObject resultJson = new JSONObject(s);
String token = (String) resultJson.get("access_token");
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
1.2 调用接口生成二维码
import net.sf.json.JSONException;
import sun.misc.BASE64Decoder;
import java.io.FileOutputStream;
import java.io.OutputStream;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.collections.Buffer;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public static Object pullCouponByToken1() throws IOException {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=获取的token";
Map map = Maps.newHashMap();
map.put("scene", "yihe");//二维码携带的参数(最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:)
String jsonString = JSON.toJSONString(map);
byte[] data = post(url, jsonString);//返回byte64图片编码,使用post请求调用(方法在下面↓↓↓)
// 将数组转为字符串
BASE64Encoder encoder = new BASE64Encoder();
String str = encoder.encode(data).trim();
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgbyte = decoder.decodeBuffer(str);
OutputStream os = new FileOutputStream("D:/a.jpg");//把图片生成到D盘
os.write(imgbyte, 0, imgbyte.length);
os.flush();
os.close();
System.out.println(data.toString());
return null;
}
/* 发送 post请求 用HTTPclient 发送请求*/
public byte[] post(String URL, String json) {
String obj = null;
InputStream inputStream = null;
Buffer reader = null;
byte[] data = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取相应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
data = readInputStream(inputStream);
}
return data;
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
/** 将流 保存为数据数组
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
return outStream.toByteArray();
}
2 获取二维码中携带的参数(scene值)
微信官方文档说明:https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html#%E4%BA%8C%E7%BB%B4%E7%A0%81%E8%B7%B3%E8%BD%AC%E8%A7%84%E5%88%99
从onLoad事件提取参数,再decodeURIComponent解码,就可获取二维码中的scene值
2.1 首先打开微信开发者工具
选择二维码编译
然后在(D盘)选择刚生成的二维码进行编译
在小程序项目首页的js中找到
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log(options);//打印初始值,只要中间有值就证明获取到scene值了
},
打印options,结果是一串被编码后的字符串,到这一步则是最后一步了
根据小程序官方的步骤来解码,decodeURIComponent会将%3D解码成=就可以获取值:
onLoad(options) {
const opScene = options.scene;
if(opScene){
const scene = decodeURIComponent(opScene);
let qrCodeScene = {
id: scene.split('=')[1]
};
console.log(scene);
console.log(scene.split('=')[1]);
}
这也是我第一次搞这二维码也是在官方网站的文章中总结出来的,如果还有啥不懂的欢迎留言评论