1. 程式人生 > >java後臺獲取微信分享二維碼 並返回給前端

java後臺獲取微信分享二維碼 並返回給前端

最近公司業務需求 微信小程式需要分享 從後臺請求生成二維碼圖片 並顯示

給大家分享一下 經驗 第一步 :獲得 微信token(這個token兩個小時會過期 所以需要token生成相對應的二維碼)

String wxspAppid = "yourAppid";
        //小程式的 app secret (在微信小程式管理後臺獲取)
        String wxspSecret = "yourSecret";
        //授權(必填)
        String grant_type = "client_credential";
        //////////////// 1、向微信伺服器 使用登入憑證 code 獲取 session_key 和 openid ////////////////
        //請求引數
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&grant_type=" + grant_type;
       String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
       
       System.err.println(sr);
     //解析相應內容(轉換成json物件)
       JSONObject json = JSONObject.fromObject(sr);
       //獲取會話金鑰(session_key)
       String access_token = json.get("access_token").toString();
       System.err.println(access_token);
       String imei ="867186032552993";
       String page="pages/index/index";
       String token = access_token;   // 得到token

第二步 通過token獲取二維碼圖片位元組碼

       Map<String, Object> params1 = new HashMap<String,Object>();
       params1.put("scene", "123456");  //引數  這個引數是自己來識別的  可以隨意  但我們寫的程式他是唯一識別
       params1.put("page", "pages/index/index"); //位置
       params1.put("width", 430);

       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(params1);  
       System.err.println(body);//必須是json模式的 post      
       StringEntity entity;
       entity = new StringEntity(body);
       entity.setContentType("image/png");

       httpPost.setEntity(entity);
       HttpResponse response;

       response = httpClient.execute(httpPost);
       InputStream inputStream = response.getEntity().getContent();
       ByteArrayOutputStream bytestream = new ByteArrayOutputStream();  
       int ch;  
       try {
			 while ((ch = inputStream.read()) != -1) {  
			 bytestream.write(ch);  
			}
			} 
       catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
       byte[] program = bytestream.toByteArray(); 

第三步 通過BASE64Encoder 將位元組碼 轉換成二進位制 這裡需要注意的是

  1. 小程式一定要釋出過 否則會返回 40032
  2. 小程式傳入的引數要是json 格式 否則會出現70002
	BASE64Encoder encoder = new BASE64Encoder(); 
	     String  binary = encoder.encodeBuffer(program).trim();
	     System.err.println("binary"+binary);

打印出來的結果應該是這種 注:中間太長 刪了很多

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAGuAa4DASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK V1UBpCq/KpdgWKjgE4HAqSgAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoooo AKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+AP/AILe/wDBsR+2 j+1n/wAFCfiH+1H+x7J8K9e+Hn7Q+qaD4h8Z6b4z8dyeE9Z8AeNY9DsNI8UapewajYXi6r4d1abT E1i1bQ57y+t7m8uLD+yIII7Z5P7Df+CZX7Gdv/wT9/YV/Z0/ZJXVrPxBq3wm8DrZ+Ldf043h0zW/ HOv6nqHijxrqelrf7bpNLufE2tamdNSWK3YWKwFrW2YtCn3fRQAUUUUAfgj/AMHC/wDwSh8ff8FX /wBjvwt8Pfgvq/hfSPjn8HfiRD8R/h2vjPU73R/Dmv2t5ouoaB4q8K3ep2ttfRaddatZXNldaZf3 ljLbQ32lwwT3Fla3VzcD88P+DaT/AIIN/tF/8EyviB8a/wBpL9rqTwPpnxN8f+A9P+F3w/8ABHgz xQ/iubw74Zn1218ReK9V8R6pYwW+hm81a80Xw5badZWc2qPbwWl5LNPavKscn9ftFABRRRQAUUUU AFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/2Q==

第五步 將上述的返回String 在前端解析

$.ajax({
		url: "http://localhost:8888/AppBase/getBase.do?pid=123456",
		type:'post',
	success : function(data) {
		$('#img').attr('src', 'data:image/png;base64,' + data);
	}
	});