微信小程序生成带参二维码

场景:实现微信小程序中的海报功能,海报中有一个通过扫码跳转到自己小程序的二维码,用户保存海报到本地在朋友圈分享后就可以通过扫码进入小程序。

  • 生成二维码工具类代码如下:
 package com.aone.foottalk.action.wx.util;

 import java.io.File;
import java.io.FileOutputStream;
//import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map; //import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.protocol.HTTP; import com.alibaba.fastjson.JSON;
//import com.aone.foottalk.action.back.image.ImgTAction;
//import com.aone.foottalk.common.QiniuUtil; import net.sf.json.JSONObject;
/**
* 二维码工具
* @author 开发
*
*/
public class AUtil { public static String getminiqrQr(String neirong,String tzdz) throws Exception{
String dizhi="";//返回给前端的地址
/*************获取小程序token值*******************/
String access_token ="";
// 小程序(商城)
String appId = "***************";
String secret = "***************";
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
JSONObject json = CommonUtil.httpsRequest(url, "GET", null);
if (null != json) {
access_token=json.getString("access_token");
}
System.out.println("token"+access_token);
/********************************/
Map<String, Object> params = new HashMap<>();
params.put("scene", neirong);
params.put("page", "pages"+"/"+tzdz+"/"+tzdz);
params.put("width", 430); CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);
StringEntity entity;
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity); HttpResponse response;
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
/**===========================上传七牛==================================**/
/*try {
byte[] data = IOUtils.toByteArray(inputStream);
Map<String, String> map = QiniuUtil.upload(data, neirong);
String code = map.get("code");
if ("200".equals(code)) {
System.out.println(map.get("path"));
dizhi=map.get("path");
System.out.println("地址:"+dizhi);
}
} catch (IOException ex) {
System.out.println(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException ignored) { }
}*/
/**============================保存到本地=================================**/
File targetFile = new File("/photo");
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream("/888.png"); byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
return dizhi;
} public static void main(String args[]){
try {
getminiqrQr("333","index");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  • 通用工具类:
 package com.aone.foottalk.action.wx.util;

 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.util.Formatter; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import net.sf.json.JSONObject; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 通用工具类
* @author 开发
*
*/
public class CommonUtil {
private static Logger log = LoggerFactory.getLogger(CommonUtil.class); // 凭证获取(GET)
public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; /**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
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 conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf); conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod); // 当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();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
} /**
* 方法名:byteToHex</br>
* 详述:字符串加密辅助方法 </br>
* 开发人员:souvc </br>
* 创建时间:2016-1-5 </br>
* @param hash
* @return 说明返回值含义
* @throws 说明发生此异常的条件
*/
public static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
}
  1. 目前根据已发布小程序的appId与secret所获取的token可以下载到带参的二维码图片,但是没发布的没法得到小程序二维码图片。
  2. 小程序下载二维码需要https的图片地址,但是七牛目前是http的,图片保存地址需要处理。
上一篇:MySQL for Windows 解压缩版配置安装


下一篇:php微信开发之带参数二维码的使用