官方提供生成小程序码的三种方式,官方不推荐使用第三种:createwxaqrcode;
官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
第一种方式:POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
·生成小程序码,可接受 path 参数较长,生成个数受限,数量限制10万个
第二张方式:POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
·生成小程序码,可接受页面参数较短,生成个数不限,5000次/分钟
以上两种方式参数access_token、path为必填
一、生成二维码可分为两步:
第一步:获取ACCESS_TOKEN
// 网页授权接口
public final static String GetAccessTokenUrl =
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
public static Map<String, String> getAccessToken(String appid, String appsecret) {
String requestUrl = GetAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret);
HttpClient client = null;
Map<String, String> result = new HashMap<String, String>();
String accessToken = null;
try {
client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(httpget, responseHandler);
JSONObject OpenidJSONO = JSONObject.fromObject(response);
accessToken = String.valueOf(OpenidJSONO.get("access_token"));
result.put("accessToken", accessToken);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return result;
}
第二步:调用生成小程序码接口带上accessToken
@RequestMapping("/qrCode")
@ResponseBody
public Object cenerateTheQrCode(HttpServletRequest request){
//调用上面方法,获取accessToken,建议对accessToken进行缓存,
//appid:小程序appid,appsecret:小程序密钥
String token = SignUtil.getAccessToken(appid,appsecret).get("accessToken");
Map<String, Object> params = new HashMap<>();
//参数,一个可以直接放入参数例如:1 多个例如:id=1&name=2&...
params.put("scene", "需要的参数");
params.put("path", "pages/index/index"); //扫码后进入小程序的页面位置
params.put("width", Number类型)//不是必须,需要的宽度,默认430x430,最小280最大1280
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 接口
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);//必须是json模式的 post
StringEntity entity = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");//也可以是image/jpg
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
String name = name+".png";//文件名加后缀,跟上面对应
String path = "D:\\";//图片保存路径
SignUtil.saveToImgByInputStream(inputStream,path,name); //保存图片
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
下面是保存图片的方法:
/**
* 将二进制转换成文件保存
* @param instreams 二进制流
* @param imgPath 图片的保存路径
* @param imgName 图片的名称
* @return
* 1:保存正常
* 0:保存失败
*/
public static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName){
int stateInt = 1;
if(instreams != null){
try {
File file = new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
File filePath = new File(imgPath);
if (filePath.exists()) {
if (filePath.isDirectory()) {
System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
System.out.println("dir not exists, create it ...");
filePath.mkdir();
}
FileOutputStream fos=new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
} catch (Exception e) {
stateInt = 0;
e.printStackTrace();
} finally {
}
}
return stateInt;//1 成功,0 失败
}
这样就可以在你保存的文件夹下看到小程序码了。
这里用的是 getwxacodeunlimit 接口,想要使用getwxacode的话只需要替换即可,其他方式不变;
二、后面就是扫码后在小程序获取二维码带的参数
onLoad:function(options){
if(options.scene){
decodeURIComponent(options.scene)//一个参数可以直接这样获取
//1.多个参数处理方式
let scene=decodeURIComponent(options.scene);
//&是我们定义的参数链接方式
let userId=options.scene.split("&")[0];
let recommendId=options.scene.split('&')[1];
//2.多个参数处理方式
if (options.scene) {
console.log("has scene");
var scene = decodeURIComponent(options.scene);
console.log("scene is ", scene);
var arrPara = scene.split("&");
var arr = [];
for (var i in arrPara) {
arr = arrPara[i].split("=");
wx.setStorageSync(arr[0],arr[1]);
console.log("setStorageSync:",arr[0],"=",arr[1]);
}
} else {
console.log("no scene");
}
//第二中处理方式转载
---------------------
作者:brightming
来源:CSDN
原文:https://blog.csdn.net/brightming/article/details/81953571
版权声明:本文为博主原创文章,转载请附上博文链接!
}
}
另外:开发测试的时候,使用开发者工具选择编译模式
需要注意的是开发者工具测试时可以不用解码可直接获取
//配置的启动页面下的js文件
onLoad: function (options) {
console.log('解码:',decodeURIComponent(options.scene))
console.log('直接获取:',options.scene)
},
发布的小程序扫描小程序码获取参数须解码;
希望对大家有帮助;