微信小程序二維碼如何帶參數
代碼目的:
- 掃碼進入小程序特定界面;
- 把自己的業務參數放入二維碼當中;
步驟:
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群一起交流學習
本站vip會員 請加入無憂模板網 VIP群(50604020) PS:加入時備注用戶名或昵稱
普通注冊會員或訪客 請加入無憂模板網 技術交流群(50604130)
客服微信號:15898888535
聲明:本站所有文章資源內容,如無特殊說明或標注,均為采集網絡資源。如若內容侵犯了原著者的合法權益,可聯系站長刪除。