代码目的:
- 扫码进入小程序特定界面;
- 把自己的业务参数放入二维码当中;
步骤:
1、获取微信连接token:
- 在生成二维码之前,要先获取到api的授权接口;
- 地址为:“https://api.weixin.qq.com/cgi-bin/token”;
- token的有效时间为2小时;
// 网页授权接口
private final static String GetAccessTokenUrl =
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
/**
* 获取二维码生成的token
* @param appid 小程序appid
* @param appsecret 小程序密钥
* @return
*/
private static String getAccessToken(String appid, String appsecret) {
String requestUrl = GetAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret);
HttpClient client = null;
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 = JSON.parseObject(response);
accessToken = String.valueOf(OpenidJSONO.get("access_token"));
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return accessToken;
}
2、发起请求,生成二维码:
- 获取二维码地址:https://api.weixin.qq.com/wxa/getwxacodeunlimit
/**
* 获取二维码
* @param token 授权令牌
* @param scene 业务参数值,不得超过32个字符
* @return
*/
public File createQRCode(String token, String scene){
//调用上面方法获取token,建议accessToken进行缓存
Map<String, Object> params = new HashMap<>();
params.put("scene", scene);
params.put("path", "/pages/goods-detall/index"); //扫码后进入小程序的页面位置
params.put("width", 280);//不是必须,需要的宽度,默认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;
String resultPath = null;
try {
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
//文件起个名字
Date date=new Date();
Long timestamp=date.getTime();
String rqName = timestamp.toString()+".jgp";
File rqFile= new File(rqName);
return rqFile;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
版权声明:本文为qq_43584568原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。