Helius
2020-12-15 2914588a65371a3ce43f678cde0a26cd8da26611
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.matrix.component.tools;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.system.common.constance.AppConstance;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
 
import java.io.*;
import java.util.HashMap;
import java.util.Map;
 
public class WxacodeUtil {
    /**
     * 小程序秘钥
     */
    private static final String XCX_SECRET = "xcx_secret";
    /**
     * 小程序appid
     */
    private static final String XCX_APPID = "xcx_appid";
    /**
     * token获取地址
     */
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
    
    /**
     * token获取地址
     */
    private static final String GET_WXACODE ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
    
    public static String getWxacode(String scene,String page,String fileName) throws Exception {
        LogUtil.debug("scene={},page={},fileName={}",scene,page,fileName);
        //获取token
        String appid = PropertiesUtil.getString(XCX_APPID);
        String secret = PropertiesUtil.getString(XCX_SECRET);
         String result1 = get(TOKEN_URL.replace("APPID", appid).replace("SECRET", secret));
         String access_token = JSONObject.parseObject(result1).getString("access_token");
        if(StringUtils.isNotBlank(access_token)) {
            Map<String, Object> params = new HashMap<>();
            params.put("scene", scene);
            params.put("page", page);
            params.put("width", 430);
            params.put("is_hyaline", true);
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(GET_WXACODE+access_token);
 
            String body = JSON.toJSONString(params);
            StringEntity entity;
            entity = new StringEntity(body);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            /*Object inputObj= response.getEntity().getContent();
            if(inputObj instanceof InputStream){
                String strError = streamToString(inputStream,"GBK");
                LogUtil.info("-------------二维码生成------"+strError);
                return "error:" + strError;
            }*/
 
            // 图片保存目录路径
            String baseSavePath = PropertiesUtil.getString(AppConstance.FILES_TORAGE_PATH);
            File targetFile = new File(baseSavePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
 
            /*String inputstreamtofile = inputstreamtofile(inputStream, targetFile);
            if(null != inputstreamtofile){
                return inputstreamtofile;
            }*/
 
            // 创建图片文件夹
            baseSavePath += "wxacode" + File.separatorChar;
            File saveDirFile = new File(baseSavePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            String qrcodePath = baseSavePath + fileName + ".png";
            FileOutputStream out = new FileOutputStream(qrcodePath);
            LogUtil.debug("qrcodePath:{}",qrcodePath);
            //本地调试创建(不用删)
            /*String filePath = "e:/test.png";
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
            FileOutputStream outs = new FileOutputStream(file);*/
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, bytesRead);
                //outs.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
            //outs.flush();
            //outs.close();
 
            return qrcodePath;
        } else {
             return null;
        }
    }
 
    public static String inputstreamtofile(InputStream ins,File file){
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
 
        }catch (Exception e) {
            String strError = streamToString(ins,"GBK");
            LogUtil.info("-------------二维码生成------"+strError);
            return "error:" + strError;
        }
        return null;
    }
 
    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String get(String url) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(url, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return responseEntity.getBody();
    }
 
 
    public static String streamToString(InputStream in, String encoding){
        // 将流转换为字符串
        ByteArrayOutputStream bos = null;
        try {
            // 1.创建内存输出流,将读到的数据写到内存输出流中
            bos = new ByteArrayOutputStream();
            // 2.创建字节数组
            byte[] arr = new byte[1024];
            int len;
            while(-1 != (len = in.read(arr))) {
                bos.write(arr, 0, len);
            }
            // 3.将内存输出流的数据全部转换为字符串
            return bos.toString(encoding);
        }  catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("提取 requestBody 异常", e);
        } finally {
            if(null != bos) {
                try {
                    // 其实这个内存输出流可关可不关,因为它的close方法里面没做任何操作。
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
}