Pu Zhibing
2024-12-13 73b750200f25df08aa64124da49e7461f9de6653
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
package com.stylefeng.guns.modular.system.util;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 微信工具类
 */
@Component
public class WeChatUtil {
 
    @Value("${wx.appletsAppid}")
    private String wxAppletsAppid;
 
    @Value("${wx.appletsAppSecret}")
    private String wxAppletsAppSecret;
 
    @Autowired
    private RestTemplate restTemplate;
 
 
 
    /**
     * 小程序使用jscode获取openid
     * @param jscode
     * @return
     */
    public Map<String, String> code2Session(String jscode){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret
                + "&js_code=" + jscode + "&grant_type=authorization_code";
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        int errcode = jsonObject.getIntValue("errcode");
        Map<String, String> map = new HashMap<>();
        if(errcode == 0){//成功
            map.put("openid", jsonObject.getString("openid"));
            map.put("sessionKey", jsonObject.getString("session_key"));
            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 null;
    }
 
 
    /**
     * 通过config接口注入权限验证配置(公众号)
     * 附录1-JS-SDK使用权限签名算法,
     * @return
     */
    public Map<String,Object> getSignatureConfig(String url){
        //获取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", "wx0e72f86394831b34");
        map.put("timestamp", timestamp);
        map.put("nonceStr", noncestr);
        map.put("signature", signature);
        return  map;
    }
 
 
 
    /***
     * 获取jsapiTicket(公众号)
     * 来源 www.vxzsk.com
     * @return
     */
    public String getJSApiTicket(){
        //获取token
        String acess_token= this.getAccessToken();
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acess_token + "&type=jsapi";
        String backData = restTemplate.getForObject(urlStr, String.class);
        System.out.println(backData);
        String ticket = JSONObject.parseObject(backData).getString("ticket");
        return  ticket;
    }
 
 
    /***
     * 获取acess_token (公众号)
     * 来源www.vxzsk.com
     * @return
     */
    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc89ecab90d24edd8&secret=bca863174d22736a4a9758a67484947e";
        String backData = restTemplate.getForObject(url, String.class);
        String accessToken = JSONObject.parseObject(backData).getString("access_token");
        return accessToken;
    }
 
    public String getUrlLink(String path, String query) throws Exception{
        String wxAppletsAccessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + wxAppletsAccessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("expire_type", 1);
        param.put("expire_interval", 1);
        param.put("path", path);
        param.put("query", query);
        param.put("env_version", "trial");
        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;
    }
 
    public String getPhone(String code) throws Exception{
        String wxAppletsAccessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + wxAppletsAccessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        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();
//        String body1 ="{\"errcode\":0,\"errmsg\":\"ok\",\"phone_info\":{\"phoneNumber\":\"15708179461\",\"purePhoneNumber\":\"15708179461\",\"countryCode\":\"86\",\"watermark\":{\"timestamp\":1720420413,\"appid\":\"wxc89ecab90d24edd8\"}}}";
 
        JSONObject jsonObject = JSON.parseObject(body1);
        // 从JSON对象中获取phone_info子对象
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        // 从phone_info中获取phoneNumber
        String phoneNumber = phoneInfo.getString("phoneNumber");
        System.out.println("Phone Number: " + phoneNumber);
 
 
        return phoneNumber;
    }
 
    public String rid(String path, Integer driverId) throws Exception{
        // 获取access_token
        String accessToken = getAccessToken();
        // 替换CREATE_CODE_URL
        String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+accessToken;
        // 发送请求
        String stringApiResult = null;
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("path", path+"?driverId="+driverId);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity requestEntity = new HttpEntity(map, headers);
            ResponseEntity<byte[]> rep = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
            byte[] bytes = rep.getBody();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), byteArrayInputStream);
//            ResultUtil resultUtil = userInfoController.uploadImg(file, null, null);
            String s = OssUploadUtil.ossUpload(file,driverId);
            System.err.println("===url"+s);
//            StringBuilder sb = new StringBuilder(stringApiResult);
//            stringApiResult = sb.toString();
            return s;
 
        } catch (Exception e) {
        }
        return stringApiResult;
    }
 
}