wlzboy
2025-11-22 fd047fa7234dc11643dab8ecbf38e8d7a8ba0854
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
package com.ruoyi.system.service.impl;
 
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WechatConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.IWechatLoginService;
import com.ruoyi.system.service.ISysUserService;
 
/**
 * 微信登录服务实现
 * 
 * @author ruoyi
 */
@Service
public class WechatLoginServiceImpl implements IWechatLoginService
{
    private static final Logger log = LoggerFactory.getLogger(WechatLoginServiceImpl.class);
    
    @Autowired
    private WechatConfig wechatConfig;
    
    @Autowired
    private ISysUserService userService;
    
    /**
     * 微信API - code2Session
     */
    private static final String JSCODE_2_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    
    /**
     * 微信API - 获取手机号
     */
    private static final String GET_PHONE_NUMBER_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
    
    /**
     * 微信API - 获取access_token
     */
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    
    /**
     * 通过微信code获取openid和session_key
     * 
     * @param code 微信登录code
     * @return 包含openid、unionid、session_key的Map
     */
    @Override
    public Map<String, Object> getWechatSession(String code)
    {
        Map<String, Object> result = new HashMap<>();
        
        try
        {
            // 构建请求参数
            String params = "appid=" + wechatConfig.getAppId() +
                          "&secret=" + wechatConfig.getAppSecret() +
                          "&js_code=" + code +
                          "&grant_type=authorization_code";
            
            log.info("调用微信jscode2session接口, code: {}", code);
            
            // 发送请求
            String response = HttpUtils.sendGet(JSCODE_2_SESSION_URL, params);
            
            log.info("微信jscode2session响应: {}", response);
            
            // 解析响应
            JSONObject jsonResponse = JSONObject.parseObject(response);
            
            if (jsonResponse.containsKey("errcode") && jsonResponse.getInteger("errcode") != 0)
            {
                log.error("微信jscode2session失败: {}", response);
                result.put("success", false);
                result.put("message", "获取微信会话失败: " + jsonResponse.getString("errmsg"));
                return result;
            }
            
            result.put("success", true);
            result.put("openid", jsonResponse.getString("openid"));
            result.put("session_key", jsonResponse.getString("session_key"));
            
            // unionid可能为空(需要小程序绑定微信开放平台)
            if (jsonResponse.containsKey("unionid"))
            {
                result.put("unionid", jsonResponse.getString("unionid"));
            }
            
            return result;
        }
        catch (Exception e)
        {
            log.error("调用微信jscode2session接口异常", e);
            result.put("success", false);
            result.put("message", "获取微信会话异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 获取微信access_token
     */
    private String getAccessToken()
    {
        try
        {
            String params = "grant_type=client_credential" +
                          "&appid=" + wechatConfig.getAppId() +
                          "&secret=" + wechatConfig.getAppSecret();
            
            String response = HttpUtils.sendGet(GET_ACCESS_TOKEN_URL, params);
            JSONObject jsonResponse = JSONObject.parseObject(response);
            
            if (jsonResponse.containsKey("errcode"))
            {
                log.error("获取access_token失败: {}", response);
                return null;
            }
            
            return jsonResponse.getString("access_token");
        }
        catch (Exception e)
        {
            log.error("获取access_token异常", e);
            return null;
        }
    }
    
    /**
     * 获取微信用户手机号
     * 
     * @param code 手机号授权code
     * @return 包含手机号信息的Map
     */
    @Override
    public Map<String, Object> getPhoneNumber(String code)
    {
        Map<String, Object> result = new HashMap<>();
        
        try
        {
            // 获取access_token
            String accessToken = getAccessToken();
            if (StringUtils.isEmpty(accessToken))
            {
                result.put("success", false);
                result.put("message", "获取access_token失败");
                return result;
            }
            
            // 构建请求URL
            String url = GET_PHONE_NUMBER_URL + "?access_token=" + accessToken;
            
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("code", code);
            
            log.info("调用微信getPhoneNumber接口, code: {}", code);
            
            // 发送POST请求
            String response = HttpUtils.sendPost(url, requestBody.toJSONString());
            
            log.info("微信getPhoneNumber响应: {}", response);
            
            // 解析响应
            JSONObject jsonResponse = JSONObject.parseObject(response);
            
            if (jsonResponse.getInteger("errcode") != 0)
            {
                log.error("微信getPhoneNumber失败: {}", response);
                result.put("success", false);
                result.put("message", "获取手机号失败: " + jsonResponse.getString("errmsg"));
                return result;
            }
            
            // 获取手机号信息
            JSONObject phoneInfo = jsonResponse.getJSONObject("phone_info");
            
            result.put("success", true);
            result.put("phoneNumber", phoneInfo.getString("phoneNumber"));
            result.put("purePhoneNumber", phoneInfo.getString("purePhoneNumber"));
            result.put("countryCode", phoneInfo.getString("countryCode"));
            
            return result;
        }
        catch (Exception e)
        {
            log.error("调用微信getPhoneNumber接口异常", e);
            result.put("success", false);
            result.put("message", "获取手机号异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 微信手机号登录
     * 
     * @param loginCode 微信登录code
     * @param phoneCode 手机号授权code
     * @return 登录结果
     */
    @Override
    public Map<String, Object> loginByWechatPhone(String loginCode, String phoneCode)
    {
        Map<String, Object> result = new HashMap<>();
        
        try
        {
            // 1. 获取微信session(openid、unionid)
            Map<String, Object> sessionResult = getWechatSession(loginCode);
            if (!(Boolean)sessionResult.get("success"))
            {
                return sessionResult;
            }
            
            String openId = (String) sessionResult.get("openid");
            String unionId = (String) sessionResult.get("unionid");
            
            log.info("获取到openid: {}, unionid: {}", openId, unionId);
            
            // 2. 获取手机号
            Map<String, Object> phoneResult = getPhoneNumber(phoneCode);
            if (!(Boolean)phoneResult.get("success"))
            {
                return phoneResult;
            }
            
            String phoneNumber = (String) phoneResult.get("purePhoneNumber");
            
            log.info("获取到手机号: {}", phoneNumber);
            
            // 3. 根据手机号查找用户
            SysUser user = userService.selectUserByPhonenumber(phoneNumber);
            
            if (user == null)
            {
                result.put("success", false);
                result.put("message", "该手机号尚未注册,请先注册账号");
                return result;
            }
            
            // 4. 检查用户状态
            if ("1".equals(user.getStatus()))
            {
                result.put("success", false);
                result.put("message", "用户已被停用,请联系管理员");
                return result;
            }
            
            if ("1".equals(user.getDelFlag()))
            {
                result.put("success", false);
                result.put("message", "用户已被删除,请联系管理员");
                return result;
            }
            
            // 5. 更新用户的微信信息
            SysUser updateUser = new SysUser();
            updateUser.setUserId(user.getUserId());
            updateUser.setOpenId(openId);
            if (StringUtils.isNotEmpty(unionId))
            {
                updateUser.setUnionId(unionId);
            }
            userService.updateUser(updateUser);
            
            log.info("用户{}微信信息更新成功", user.getUserName());
            
            // 6. 返回成功结果
            result.put("success", true);
            result.put("user", user);
            result.put("openId", openId);
            result.put("unionId", unionId);
            
            return result;
        }
        catch (Exception e)
        {
            log.error("微信手机号登录异常", e);
            result.put("success", false);
            result.put("message", "登录异常: " + e.getMessage());
            return result;
        }
    }
}