生活随笔
收集整理的這篇文章主要介紹了
微信小程序二维码带参数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼目的:
- 掃碼進(jìn)入小程序特定界面;
- 把自己的業(yè)務(wù)參數(shù)放入二維碼當(dāng)中;
步驟:
1、獲取微信連接token:
- 在生成二維碼之前,要先獲取到api的授權(quán)接口;
- 地址為:“https://api.weixin.qq.com/cgi-bin/token”;
- token的有效時(shí)間為2小時(shí);
// 網(wǎng)頁(yè)授權(quán)接口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、發(fā)起請(qǐng)求,生成二維碼:
- 獲取二維碼地址:https://api.weixin.qq.com/wxa/getwxacodeunlimit
/*** 獲取二維碼* @param token 授權(quán)令牌* @param scene 業(yè)務(wù)參數(shù)值,不得超過(guò)32個(gè)字符* @return*/public File createQRCode(String token, String scene){//調(diào)用上面方法獲取token,建議accessToken進(jìn)行緩存Map<String, Object> params = new HashMap<>();params.put("scene", scene);params.put("path", "/pages/goods-detall/index"); //掃碼后進(jìn)入小程序的頁(yè)面位置params.put("width", 280);//不是必須,需要的寬度,默認(rèn)430x430,最小280最大1280CloseableHttpClient 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模式的 postStringEntity 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();//文件起個(gè)名字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;}
總結(jié)
以上是生活随笔為你收集整理的微信小程序二维码带参数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。