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 params1 = new HashMap();
       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);
	}
	});

你可能感兴趣的:(微信二维码)