1
luofl
2025-03-11 b8dedd4e1962cf4f7984b01d500f950fe5e8fea3
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
package com.ruoyi.auction.util.weChat;
 
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.auction.util.CreateQrCode;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.RemoteFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
 
/**
 * 微信工具类
 */
@Slf4j
@Component
public class WeChatUtil {
 
    private static final String wxAppletsAppid = "wx69e3ac6e13a889b7";
 
    private static final String wxAppletsAppSecret = "1b8bcfcb681524ac553e72054e5271ef";
 
 
//    @Value("${wx.appid}")
    private String webAppId;
 
//    @Value("${wx.appSecret}")
    private String webAppSecret;
    
    @Resource
    private RedisService redisService;
    @Resource
    private RemoteFileService remoteFileService;
    
    
 
 
    /**
     * 小程序使用jscode获取openid
     * @param jscode
     * @return
     */
    public Map<String, Object> code2Session(String jscode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret
                + "&js_code=" + jscode + "&grant_type=authorization_code";
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse response = get.execute();
        int status = response.getStatus();
        if(200 != status){
            throw new RuntimeException(response.body());
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        int errcode = jsonObject.getIntValue("errcode");
        Map<String, Object> map = new HashMap<>();
        map.put("errcode", errcode);
        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;
    }
    
    
    public String getWxAppletsAccessToken(){
        Object wxAppletsAccessToken = redisService.getCacheObject("wxAppletsAccessToken");
        if(null != wxAppletsAccessToken){
            return wxAppletsAccessToken.toString();
        }
        String appletsAccessToken = getAppletsAccessToken();
        redisService.setCacheObject("wxAppletsAccessToken", appletsAccessToken, 7200L, TimeUnit.SECONDS);
        return appletsAccessToken;
    }
    
 
    /**
     * 获取微信小程序token
     * @return
     */
    public String getAppletsAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret;
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse response = get.execute();
        if(response.getStatus() != 200){
            return "";
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        return jsonObject.getString("access_token");
    }
 
 
    /**
     * 网站应用登录
     * @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";
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse response = get.execute();
        if(response.getStatus() != 200){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        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;
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse response = get.execute();
        if(response.getStatus() != 200){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        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;
    }
 
    
 
 
    /**
     * 获取小程序二维码
     * @param page      跳转页 例如 pages/index/index
     * @param scene     参数 a=1&b=2
     */
    public InputStream getwxacodeunlimit(String page, String scene, EnvVersion env_version){
        try {
            String token = getWxAppletsAccessToken();
            if(StringUtils.isEmpty(token)){
                System.err.println("获取接口调用凭证失败");
            }
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", scene);
            param.put("page", page);
            param.put("env_version", env_version.getVersion());
    
            HttpRequest post = HttpUtil.createPost(url);
            post.header(Header.CONTENT_TYPE, "application/json;charset=UTF-8");
            post.body(JSON.toJSONString(param));
            HttpResponse execute = post.execute();
            byte[] bytes = execute.bodyBytes();
            String body1 = execute.body();
            System.err.println(body1);
            System.err.println(Base64.encodeBase64String(bytes));
            return new ByteArrayInputStream(bytes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 获取微信小程序二维码
     * @param page
     * @param scene
     * @param filePath
     * @return
     */
    public String getwxacodeunlimit(String page, String scene, EnvVersion env_version, String filePath){
        InputStream getwxacodeunlimit = getwxacodeunlimit(page, scene, env_version);
        MultipartFile multipartFile = CreateQrCode.getMultipartFile(getwxacodeunlimit, UUID.randomUUID() + ".png");
//        File file = FileUtil.writeFromStream(getwxacodeunlimit, new File(filePath));
//        return file.getPath();
        return remoteFileService.obsUpload(multipartFile).getData();
    }
}