hejianhao
2026-09-01 540ef65220e05b75c183cd3554aaeb554927600a
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
package com.tcm.training.admin.app.auth.service;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcm.training.admin.app.auth.config.AppWechatAuthProperties;
import com.tcm.training.admin.app.auth.dto.AppWechatLoginRequest;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
 
/**
 * 微信登录接口客户端,负责换取授权信息并拉取微信头像昵称。
 */
@Service
public class AppWechatAuthClient {
 
    private static final Logger log = LoggerFactory.getLogger(AppWechatAuthClient.class);
 
    private final AppWechatAuthProperties properties;
    private final ObjectMapper objectMapper;
    private final RestOperations restOperations;
 
    /**
     * 使用默认 HTTP 客户端构造微信认证客户端。
     */
    @Autowired
    public AppWechatAuthClient(AppWechatAuthProperties properties, ObjectMapper objectMapper) {
        this(properties, objectMapper, createUtf8RestTemplate());
    }
 
    /**
     * 注入微信配置、JSON 解析器与 HTTP 客户端。
     * 存在多个构造器时,这个扩展构造器仅供测试或内部定制使用,避免 Spring 误判默认注入入口。
     */
    AppWechatAuthClient(AppWechatAuthProperties properties,
                        ObjectMapper objectMapper,
                        RestOperations restOperations) {
        this.properties = properties;
        this.objectMapper = objectMapper;
        this.restOperations = restOperations;
    }
 
    /**
     * 按当前请求中的授权信息换取微信用户资料。
     */
    public AppWechatUserProfile resolveUserProfile(AppWechatLoginRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("微信授权信息不完整");
        }
        String accessToken = trimToNull(request.getAccessToken());
        String openid = trimToNull(request.getOpenid());
        String unionid = trimToNull(request.getUnionid());
 
        if (accessToken != null && openid != null) {
            AppWechatUserProfile profile = fetchUserInfo(accessToken, openid);
            if (profile.getUnionid() == null) {
                profile.setUnionid(unionid);
            }
            return profile;
        }
 
        String code = trimToNull(request.getCode());
        if (code == null) {
            throw new IllegalArgumentException("微信授权信息不完整");
        }
        if (!properties.isServerAuthConfigured()) {
            throw new IllegalArgumentException("微信登录暂未配置,请稍后重试");
        }
 
        WechatAccessTokenSnapshot tokenSnapshot = exchangeCode(code);
        AppWechatUserProfile profile = fetchUserInfo(tokenSnapshot.getAccessToken(), tokenSnapshot.getOpenid());
        if (profile.getUnionid() == null) {
            profile.setUnionid(tokenSnapshot.getUnionid());
        }
        return profile;
    }
 
    /**
     * 使用临时 code 向微信换取 accessToken 与 openid。
     */
    private WechatAccessTokenSnapshot exchangeCode(String code) {
        String url = UriComponentsBuilder.fromHttpUrl(properties.getAccessTokenUrl())
                .queryParam("appid", properties.getAppId())
                .queryParam("secret", properties.getAppSecret())
                .queryParam("code", code)
                .queryParam("grant_type", "authorization_code")
                .build(true)
                .toUriString();
        JsonNode payload = getWechatPayload(url, "微信登录授权失败");
        ensureWechatSuccess(payload, "微信登录授权失败");
 
        String accessToken = trimToNull(readText(payload, "access_token"));
        String openid = trimToNull(readText(payload, "openid"));
        if (accessToken == null || openid == null) {
            throw new IllegalArgumentException("微信登录授权失败");
        }
 
        WechatAccessTokenSnapshot snapshot = new WechatAccessTokenSnapshot();
        snapshot.setAccessToken(accessToken);
        snapshot.setOpenid(openid);
        snapshot.setUnionid(trimToNull(readText(payload, "unionid")));
        return snapshot;
    }
 
    /**
     * 使用微信 accessToken 与 openid 拉取昵称、头像和性别。
     */
    private AppWechatUserProfile fetchUserInfo(String accessToken, String openid) {
        String url = UriComponentsBuilder.fromHttpUrl(properties.getUserInfoUrl())
                .queryParam("access_token", accessToken)
                .queryParam("openid", openid)
                .queryParam("lang", "zh_CN")
                .build(true)
                .toUriString();
        JsonNode payload = getWechatPayload(url, "获取微信用户信息失败");
        ensureWechatSuccess(payload, "获取微信用户信息失败");
 
        AppWechatUserProfile profile = new AppWechatUserProfile();
        profile.setOpenid(openid);
        profile.setUnionid(trimToNull(readText(payload, "unionid")));
        profile.setNickname(trimToNull(readText(payload, "nickname")));
        profile.setAvatar(trimToNull(readText(payload, "headimgurl")));
        profile.setSex(readInteger(payload, "sex"));
        return profile;
    }
 
    /**
     * 发起微信接口调用并将响应解析为 JSON。
     */
    private JsonNode getWechatPayload(String url, String failureMessage) {
        try {
            String responseBody = restOperations.getForObject(url, String.class);
            if (responseBody == null || responseBody.trim().isEmpty()) {
                throw new IllegalArgumentException(failureMessage);
            }
            return objectMapper.readTree(responseBody);
        } catch (IllegalArgumentException ex) {
            throw ex;
        } catch (Exception ex) {
            log.error("调用微信接口失败: url={}", url, ex);
            throw new IllegalArgumentException(failureMessage);
        }
    }
 
    /**
     * 校验微信接口返回是否为成功态。
     */
    private void ensureWechatSuccess(JsonNode payload, String failureMessage) {
        Integer errcode = readInteger(payload, "errcode");
        if (errcode == null || errcode == 0) {
            return;
        }
        String errmsg = trimToNull(readText(payload, "errmsg"));
        if (errmsg == null) {
            errmsg = failureMessage;
        }
        log.warn("微信接口返回异常: errcode={}, errmsg={}", errcode, errmsg);
        throw new IllegalArgumentException(errmsg);
    }
 
    /**
     * 读取字符串字段。
     */
    private String readText(JsonNode payload, String fieldName) {
        JsonNode valueNode = payload.get(fieldName);
        if (valueNode == null || valueNode.isNull()) {
            return null;
        }
        return valueNode.asText();
    }
 
    /**
     * 读取整数字段。
     */
    private Integer readInteger(JsonNode payload, String fieldName) {
        String value = trimToNull(readText(payload, fieldName));
        if (value == null) {
            return null;
        }
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException ex) {
            return null;
        }
    }
 
    /**
     * 将空白字符串归一化为 null。
     */
    private String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
 
    /**
     * 创建默认按 UTF-8 解码字符串响应的 HTTP 客户端,避免微信中文昵称乱码。
     */
    private static RestTemplate createUtf8RestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().removeIf(StringHttpMessageConverter.class::isInstance);
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
 
    /**
     * 保存微信换票结果,避免在多个私有方法之间散落参数。
     */
    private static class WechatAccessTokenSnapshot {
 
        private String accessToken;
        private String openid;
        private String unionid;
 
        /**
         * 获取 accessToken。
         */
        public String getAccessToken() {
            return accessToken;
        }
 
        /**
         * 设置 accessToken。
         */
        public void setAccessToken(String accessToken) {
            this.accessToken = accessToken;
        }
 
        /**
         * 获取 openid。
         */
        public String getOpenid() {
            return openid;
        }
 
        /**
         * 设置 openid。
         */
        public void setOpenid(String openid) {
            this.openid = openid;
        }
 
        /**
         * 获取 unionid。
         */
        public String getUnionid() {
            return unionid;
        }
 
        /**
         * 设置 unionid。
         */
        public void setUnionid(String unionid) {
            this.unionid = unionid;
        }
    }
}