通过接口生成小程序二维码,以及获取二维码中携带的参数(scene值)
生活随笔
收集整理的這篇文章主要介紹了
通过接口生成小程序二维码,以及获取二维码中携带的参数(scene值)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1:獲取二維碼流程
微信官方接口https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html所需要的參數
1.1 獲取access_token
微信官方接口 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html public static void main(String[] args) {String s=sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="+小程序唯一憑證+"&secret="+小程序唯一憑證密鑰+"");JSONObject resultJson = new JSONObject(s);String token = (String) resultJson.get("access_token");}/*** 向指定URL發送GET方法的請求* * @param url* 發送請求的URL* @param param* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。* @return URL 所代表遠程資源的響應結果*/public static String sendGet(String url, String param) {String result = "";BufferedReader in = null;try {String urlNameString = url + "?" + param;URL realUrl = new URL(urlNameString);// 打開和URL之間的連接URLConnection connection = realUrl.openConnection();// 設置通用的請求屬性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建立實際的連接connection.connect();// 獲取所有響應頭字段Map<String, List<String>> map = connection.getHeaderFields();// 遍歷所有的響應頭字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定義 BufferedReader輸入流來讀取URL的響應in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("發送GET請求出現異常!" + e);e.printStackTrace();}// 使用finally塊來關閉輸入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}1.2 調用接口生成二維碼
import net.sf.json.JSONException; import sun.misc.BASE64Decoder;import java.io.FileOutputStream; import java.io.OutputStream; import sun.misc.BASE64Encoder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset;import org.apache.commons.collections.Buffer; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; 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.HttpClients;public static Object pullCouponByToken1() throws IOException {String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=獲取的token"; Map map = Maps.newHashMap();map.put("scene", "yihe");//二維碼攜帶的參數(最大32個可見字符,只支持數字,大小寫英文以及部分特殊字符:)String jsonString = JSON.toJSONString(map);byte[] data = post(url, jsonString);//返回byte64圖片編碼,使用post請求調用(方法在下面↓↓↓)// 將數組轉為字符串BASE64Encoder encoder = new BASE64Encoder();String str = encoder.encode(data).trim();BASE64Decoder decoder = new BASE64Decoder();byte[] imgbyte = decoder.decodeBuffer(str);OutputStream os = new FileOutputStream("D:/a.jpg");//把圖片生成到D盤os.write(imgbyte, 0, imgbyte.length);os.flush();os.close();System.out.println(data.toString());return null;}/* 發送 post請求 用HTTPclient 發送請求*/public byte[] post(String URL, String json) {String obj = null;InputStream inputStream = null;Buffer reader = null;byte[] data = null;// 創建默認的httpClient實例.CloseableHttpClient httpclient = HttpClients.createDefault();// 創建httppostHttpPost httppost = new HttpPost(URL);httppost.addHeader("Content-type", "application/json; charset=utf-8");httppost.setHeader("Accept", "application/json");try {StringEntity s = new StringEntity(json, Charset.forName("UTF-8")); s.setContentEncoding("UTF-8");httppost.setEntity(s);CloseableHttpResponse response = httpclient.execute(httppost);try {// 獲取相應實體HttpEntity entity = response.getEntity();if (entity != null) {inputStream = entity.getContent();data = readInputStream(inputStream);}return data;} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {// 關閉連接,釋放資源try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}return data;}/** 將流 保存為數據數組* @param inStream* @return* @throws Exception*/public static byte[] readInputStream(InputStream inStream) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream();// 創建一個Buffer字符串byte[] buffer = new byte[1024];// 每次讀取的字符串長度,如果為-1,代表全部讀取完畢int len = 0;// 使用一個輸入流從buffer里把數據讀取出來while ((len = inStream.read(buffer)) != -1) {// 用輸出流往buffer里寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度outStream.write(buffer, 0, len);}// 關閉輸入流inStream.close();// 把outStream里的數據寫入內存return outStream.toByteArray();}2 獲取二維碼中攜帶的參數(scene值)
微信官方文檔說明:https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html#%E4%BA%8C%E7%BB%B4%E7%A0%81%E8%B7%B3%E8%BD%AC%E8%A7%84%E5%88%99從onLoad事件提取參數,再decodeURIComponent解碼,就可獲取二維碼中的scene值
2.1 首先打開微信開發者工具
選擇二維碼編譯
然后在(D盤)選擇剛生成的二維碼進行編譯
打印options,結果是一串被編碼后的字符串,到這一步則是最后一步了
根據小程序官方的步驟來解碼,decodeURIComponent會將%3D解碼成=就可以獲取值:
onLoad(options) {
這也是我第一次搞這二維碼也是在官方網站的文章中總結出來的,如果還有啥不懂的歡迎留言評論
總結
以上是生活随笔為你收集整理的通过接口生成小程序二维码,以及获取二维码中携带的参数(scene值)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DDD官方示例
- 下一篇: 机载雷达导论(附录)