puzhibing
2023-02-26 8883d654f52171657b62aaec85027f29ef0a4dd0
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package com.supersavedriving.user.modular.system.util.weChat;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.supersavedriving.user.core.util.ToolUtil;
import com.supersavedriving.user.modular.system.util.RedisUtil;
import com.supersavedriving.user.modular.system.util.UUIDUtil;
import com.supersavedriving.user.modular.system.util.httpClinet.HttpClientUtil;
import com.supersavedriving.user.modular.system.util.httpClinet.HttpResult;
import com.supersavedriving.user.modular.system.util.weChat.model.Code2Session;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
 
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
 
/**
 * 微信工具类
 */
@Component
public class WeChatUtil {
 
    private static Logger logger = LoggerFactory.getLogger(WeChatUtil.class);
 
    @Value("${wx.appletsAppid}")
    private String wxAppletsAppid;
 
    @Value("${wx.appletsAppSecret}")
    private String wxAppletsAppSecret;
 
    @Value("${wx.officialAccountAppid}")
    private String officialAccountAppid;
 
    @Value("{wx.officialAccountAppSecret}")
    private String officialAccountAppSecret;
 
    @Value("${wx.appid}")
    private String webAppId;
 
    @Value("${wx.appSecret}")
    private String webAppSecret;
 
    @Autowired
    private RestTemplate restTemplate;
 
    @Autowired
    private RedisUtil redisUtil;
 
 
 
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(30000);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                String wxAppletsAccessToken = getWxAppletsAccessToken();
                                if(ToolUtil.isEmpty(wxAppletsAccessToken)){
                                    System.err.println("获取微信小程序access_token失败");
                                    return;
                                }
                                redisUtil.setStrValue("wxAppletsAccessToken", wxAppletsAccessToken, 7000);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }, 0, 7000000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
 
    }
 
 
    /**
     * 小程序使用jscode获取openid
     * @param jscode
     * @return
     */
    public Code2Session code2Session(String jscode) throws Exception{
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret
                + "&js_code=" + jscode + "&grant_type=authorization_code";
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(null == httpResult || httpResult.getCode() != 200){
            return null;
        }
        Code2Session code2Session = JSON.parseObject(httpResult.getData(), Code2Session.class);
        return code2Session;
    }
 
 
    /**
     * 获取微信小程序token
     * @return
     */
    public String getWxAppletsAccessToken() throws Exception{
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret;
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(httpResult.getCode() != 200){
            return "";
        }
        JSONObject jsonObject = JSON.parseObject(httpResult.getData());
        return jsonObject.getString("access_token");
    }
 
 
    /***
     * 获取jsapiTicket(小程序)
     * 来源 www.vxzsk.com
     * @return
     */
    public String getWxAppletsJSApiTicket() throws Exception{
        String wxAppletsAccessToken = redisUtil.getValue("wxAppletsAccessToken");
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + wxAppletsAccessToken + "&type=jsapi";
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", urlStr, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        logger.debug(httpResult.getData());
        String ticket = JSONObject.parseObject(httpResult.getData()).getString("ticket");
        return  ticket;
    }
 
    /**
     * 通过config接口注入权限验证配置(小程序)
     * 附录1-JS-SDK使用权限签名算法,
     * @return
     */
    public Map<String,Object> getWxAppletsSignatureConfig(String url) throws Exception{
        //获取token
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String ticket = getWxAppletsJSApiTicket();
        String noncestr = UUIDUtil.getRandomCode();
        Long timestamp = System.currentTimeMillis();
        String content = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        String signature = DigestUtils.sha1Hex(content);
        Map<String,Object> map=new HashMap<>();
        map.put("appId", wxAppletsAppid);
        map.put("timestamp", timestamp);
        map.put("nonceStr", noncestr);
        map.put("signature", signature);
        return  map;
    }
 
 
 
    /**
     * 网站应用登录
     * @param code
     * @return
     */
    public Map<String, String> webAccessToken(String code) throws Exception{
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + webAppId + "&secret=" + webAppSecret + "&code=" + code + "&grant_type=authorization_code";
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(httpResult.getData());
        int errcode = jsonObject.getIntValue("errcode");
        Map<String, String> map = new HashMap<>();
        if(errcode == 0){//成功
            map.put("access_token", jsonObject.getString("access_token"));
            map.put("openid", jsonObject.getString("openid"));
            map.put("refresh_token", jsonObject.getString("refresh_token"));
            map.put("unionid", jsonObject.getString("unionid"));
            return map;
        }
        if(errcode == -1){//系统繁忙,此时请开发者稍候再试
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 40029){//code 无效
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 45011){//频率限制,每个用户每分钟100次
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        return map;
    }
 
 
    /**
     * 获取微信个人信息
     * @param access_token
     * @param openid
     * @return
     */
    public Map<String, Object> getUserInfo(String access_token, String openid) throws Exception{
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(httpResult.getData());
        int errcode = jsonObject.getIntValue("errcode");
        Map<String, Object> map = new HashMap<>();
        if(errcode == 0){//成功
            map.put("nickname", jsonObject.getString("nickname"));
            map.put("openid", jsonObject.getString("openid"));
            map.put("sex", jsonObject.getString("sex"));
            map.put("headimgurl", jsonObject.getString("headimgurl"));
            return map;
        }
        if(errcode == -1){//系统繁忙,此时请开发者稍候再试
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 40029){//code 无效
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 45011){//频率限制,每个用户每分钟100次
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        return map;
    }
 
 
    /**
     * 公众号获取openid
     * @param code
     * @return
     */
    public Map<String,Object> getOpenId(String code) throws Exception{
        if (code == null || code.length() == 0) {
            return null;
        }
        String grantType = "authorization_code";
        String params = "appid=" + officialAccountAppid + "&secret=" + officialAccountAppSecret + "&code=" + code + "&grant_type=" + grantType;
        logger.debug("sssss"+params);
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", "https://api.weixin.qq.com/sns/oauth2/access_token?" + params, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        JSONObject json = JSON.parseObject(httpResult.getData());
        logger.debug(json.toJSONString());
        String openId = json.get("openid").toString();
        String accessToken = json.get("access_token").toString();
        Integer expiresIn = json.getInteger("expires_in");
        String refresh_token = json.getString("refresh_token");
        String unionid = json.getString("unionid");
        Map<String,Object> map=new HashMap<>();
        map.put("openId",openId);
        map.put("accessToken",accessToken);
        map.put("expiresIn", expiresIn);
        map.put("refreshToken", refresh_token);
        map.put("unionid", unionid);
        return map;
    }
 
 
    /***
     * 获取acess_token (公众号)
     * 来源www.vxzsk.com
     * @return
     */
    public String getAccessToken() throws Exception{
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + officialAccountAppid
                + "&secret=" + officialAccountAppSecret;
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        String accessToken = JSONObject.parseObject(httpResult.getData()).getString("access_token");
        return accessToken;
    }
 
    /***
     * 获取jsapiTicket(公众号)
     * 来源 www.vxzsk.com
     * @return
     */
    public String getJSApiTicket() throws Exception{
        //获取token
        String acess_token = redisUtil.getValue("acess_token");
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acess_token + "&type=jsapi";
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", urlStr, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        logger.debug(httpResult.getData());
        String ticket = JSONObject.parseObject(httpResult.getData()).getString("ticket");
        return  ticket;
    }
 
    /**
     * 通过config接口注入权限验证配置(公众号)
     * 附录1-JS-SDK使用权限签名算法,
     * @return
     */
    public Map<String,Object> getSignatureConfig(String url) throws Exception{
        //获取token
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String ticket = getJSApiTicket();
        String noncestr = UUIDUtil.getRandomCode();
        Long timestamp = System.currentTimeMillis();
        String content = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        String signature = DigestUtils.sha1Hex(content);
        Map<String,Object> map=new HashMap<>();
        map.put("appId", officialAccountAppid);
        map.put("timestamp", timestamp);
        map.put("nonceStr", noncestr);
        map.put("signature", signature);
        return  map;
    }
 
 
    /**
     * 公众号获取用户个人信息
     * @param access_token
     * @param openid
     * @return
     */
    public Map<String, Object> queryUserInfo(String access_token, String openid) throws Exception{
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
        HttpResult httpResult = HttpClientUtil.pushHttpRequset("GET", url, null, null, "form");
        if(httpResult.getCode() != 200){
            return null;
        }
        logger.debug(httpResult.getData());
        JSONObject j = JSON.parseObject(httpResult.getData());
        Map<String, Object> map = new HashMap<>();
        map.put("nickname", j.getString("nickname"));
        map.put("sex", j.getInteger("sex"));
        map.put("headimgurl", j.getString("headimgurl"));
        map.put("unionid", j.getString("unionid"));
        return map;
    }
 
 
    /**
     * 获取小程序二维码
     * @param page      跳转页 例如 pages/index/index
     * @param scene     参数 a=1&b=2
     */
    public InputStream getwxacodeunlimit(String page, String scene, String envVersion) throws Exception{
        try {
            String wxAppletsAccessToken = redisUtil.getValue("wxAppletsAccessToken");
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxAppletsAccessToken;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", scene);
            param.put("page", page);
            param.put("env_version", envVersion);
            HttpHeaders httpHeaders = new HttpHeaders();
            MediaType type=MediaType.parseMediaType("application/json;charset=UTF-8");
            httpHeaders.setContentType(type);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(param, httpHeaders);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, new Object[0]);
            String body1 = exchange.getBody();
//            System.err.println(body1);
            ResponseEntity<byte[]> entity  = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            byte[] body = entity.getBody();
//            System.err.println(Base64.encodeBase64String(body));
            return new ByteArrayInputStream(body);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * 获取小程序urlscheme码
     * @return
     */
    public String getUrlscheme(String path) throws Exception{
        String wxAppletsAccessToken = redisUtil.getValue("wxAppletsAccessToken");
        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + wxAppletsAccessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("is_expire", true);
        param.put("expire_type", 1);
        param.put("expire_interval", 180);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("path", path);
        map1.put("query", "");
        map1.put("env_version", "release");
        param.put("jump_wxa", map1);
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type=MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(param, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String body1 = exchange.getBody();
        return body1;
    }
}