liuxiaolong
2019-05-06 f99bc8c6a1d10610373738edd7d0aa0181c81d99
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
package com.cloud.user.service.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.cloud.model.sys.*;
import com.cloud.model.sys.constants.CredentialType;
import com.cloud.user.config.WechatConfig;
import com.cloud.user.dao.UserCredentialsDao;
import com.cloud.user.dao.WechatDao;
import com.cloud.user.service.AppUserService;
import com.cloud.user.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
 
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
 
    @Autowired
    private WechatConfig wechatConfig;
 
    private static final String WECHAT_AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect";
    private static final String STATE_WECHAT = "state_wechat";
 
    private WechatInfo getWechatInfo(String app) {
        WechatInfo wechatInfo = wechatConfig.getInfos().get(app);
        if (wechatInfo == null) {
            throw new IllegalArgumentException("未找到," + app);
        }
 
        return wechatInfo;
    }
 
    @Override
    public String getWechatAuthorizeUrl(String app, HttpServletRequest request, String toUrl)
            throws UnsupportedEncodingException {
        log.info("引导到授权页:{},{}", app, toUrl);
        WechatInfo wechatInfo = getWechatInfo(app);
 
        // 网关域名(外网)加路由到用户系统的规则 https://xxx.xxx.xxx/api-u
        String domain = wechatConfig.getDomain();
        StringBuilder redirectUri = new StringBuilder(domain + "/wechat/" + app + "/back");
        if (StringUtils.isNoneBlank(toUrl)) {
            toUrl = URLEncoder.encode(toUrl, "utf-8");
            redirectUri.append("?toUrl=").append(toUrl);
        }
        String redirect_uri = URLEncoder.encode(redirectUri.toString(), "utf-8");
 
        // 生成一个随机串,微信再跳回来的时候,会原封不动给我们带过来,到时候做一下校验
        String state = UUID.randomUUID().toString();
        request.getSession().setAttribute(STATE_WECHAT, state);
 
        return String.format(WECHAT_AUTHORIZE_URL, wechatInfo.getAppid(), redirect_uri, state);
    }
 
    @Transactional
    @Override
    public WechatUserInfo getWechatUserInfo(String app, HttpServletRequest request, String code, String state) {
        log.info("code:{}, state:{}", code, state);
        checkStateLegal(state, request);
 
        WechatAccess wechatAccess = getWechatAccess(app, code);
        WechatUserInfo wechatUserInfo = wechatDao.findByOpenid(wechatAccess.getOpenid());
 
        if (wechatUserInfo == null) {
            wechatUserInfo = saveWechatUserInfo(app, wechatAccess);
        } else {
            updateWechatUserInfo(wechatAccess, wechatUserInfo);
        }
 
        return wechatUserInfo;
    }
 
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private UserCredentialsDao userCredentialsDao;
 
    private WechatUserInfo saveWechatUserInfo(String app, WechatAccess wechatAccess) {
        WechatUserInfo wechatUserInfo = getWechatUserInfo(wechatAccess);
 
        // 多公众号支持
        String unionid = wechatUserInfo.getUnionid();
        if (StringUtils.isNoneBlank(unionid)) {
            // 根据unionid查询,看是否有同源公众号已绑定用户
            Set<WechatUserInfo> set = wechatDao.findByUniond(unionid);
            if (!CollectionUtils.isEmpty(set)) {
                WechatUserInfo userInfo = set.parallelStream().filter(w -> w.getUserId() != null).findFirst().orElse(null);
                if (userInfo != null) {
                    wechatUserInfo.setUserId(userInfo.getUserId());
                    log.info("具有相同的unionid,视为同一用户:{}", userInfo);
 
                    // 将新公众号的openid也存入登陆凭证表
                    userCredentialsDao.save(new UserCredential(wechatUserInfo.getOpenid(), CredentialType.WECHAT_OPENID.name(), userInfo.getUserId(),null));
                }
            }
        }
 
        wechatUserInfo.setApp(app);
        wechatUserInfo.setCreateTime(new Date());
        wechatUserInfo.setUpdateTime(wechatUserInfo.getCreateTime());
 
        wechatDao.save(wechatUserInfo);
        log.info("保存微信个人用户信息:{}", wechatUserInfo);
 
        return wechatUserInfo;
    }
 
    @Autowired
    private TaskExecutor taskExecutor;
 
    /**
     * 异步更新微信个人用户信息
     *
     * @param wechatAccess
     * @param wechatUserInfo
     */
    private void updateWechatUserInfo(WechatAccess wechatAccess, WechatUserInfo wechatUserInfo) {
        taskExecutor.execute(() -> {
            WechatUserInfo userInfo = getWechatUserInfo(wechatAccess);
            BeanUtils.copyProperties(userInfo, wechatUserInfo, new String[]{"id", "userId"});
            wechatUserInfo.setUpdateTime(new Date());
            wechatDao.update(wechatUserInfo);
 
            log.info("更新微信个人用户信息:{}", wechatUserInfo);
        });
    }
 
    /**
     * 校验state是否合法
     *
     * @param state
     * @param request
     */
    private void checkStateLegal(String state, HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        String sessionState = (String) httpSession.getAttribute(STATE_WECHAT);
        if (sessionState == null) {
            throw new IllegalArgumentException("缺失session state");
        }
 
        if (!state.equals(sessionState)) {
            throw new IllegalArgumentException("非法state");
        }
 
        // 校验通过,将session中的state移除
        httpSession.removeAttribute(STATE_WECHAT);
    }
 
    @Autowired
    private RestTemplate restTemplate;
 
    private static final String WECHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
 
    private WechatAccess getWechatAccess(String app, String code) {
        WechatInfo wechatInfo = getWechatInfo(app);
 
        String accessTokenUrl = String.format(WECHAT_ACCESS_TOKEN_URL, wechatInfo.getAppid(), wechatInfo.getSecret(),
                code);
 
        String string = restTemplate.getForObject(accessTokenUrl, String.class);
        WechatAccess wechatAccess = JSONObject.parseObject(string, WechatAccess.class);
        log.info("wechatAccess:{}", wechatAccess);
 
        return wechatAccess;
    }
 
    private static final String WECHAT_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
 
    /**
     * 获取微信个人用户信息
     *
     * @param wechatAccess
     * @return
     */
    private WechatUserInfo getWechatUserInfo(WechatAccess wechatAccess) {
        String userInfoUrl = String.format(WECHAT_USERINFO_URL, wechatAccess.getAccessToken(),
                wechatAccess.getOpenid());
 
        String string = restTemplate.getForObject(userInfoUrl, String.class);
 
        try {
            string = new String(string.getBytes("ISO-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        WechatUserInfo userInfo = JSONObject.parseObject(string, WechatUserInfo.class);
        log.info("userInfo:{}", userInfo);
 
        return userInfo;
    }
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    @Override
    public String getToUrl(String toUrl, WechatUserInfo wechatUserInfo) {
        StringBuilder builder = new StringBuilder(toUrl);
        if (!toUrl.contains("?")) {
            builder.append("?");
        }
 
        if (wechatUserInfo.getUserId() != null) {
            builder.append("&hasUser=1");
        }
        builder.append("&openid=").append(wechatUserInfo.getOpenid());
 
        String tempCode = cacheWechatUserInfo(wechatUserInfo);
        builder.append("&tempCode=").append(tempCode);
 
        builder.append("&nickname=").append(wechatUserInfo.getNickname());
        builder.append("&headimgurl=").append(wechatUserInfo.getHeadimgurl());
 
        return builder.toString();
    }
 
    private String cacheWechatUserInfo(WechatUserInfo wechatUserInfo) {
        String tempCode = UUID.randomUUID().toString();
        String key = prefixKey(tempCode);
 
        // 用tempCode和微信信息做个临时关系,后续的微信和账号绑定、微信登陆将会校验这个tempCode
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(wechatUserInfo), 4, TimeUnit.HOURS);
        log.info("缓存微信信息:{},{}", tempCode, wechatUserInfo);
 
        return tempCode;
    }
 
    private String prefixKey(String key) {
        return "wechat:temp:" + key;
    }
 
    @Autowired
    private AppUserService appUserService;
 
    @Transactional
    @Override
    public void bindingUser(AppUser appUser, String tempCode, String openid) {
        WechatUserInfo wechatUserInfo = checkAndGetWechatUserInfo(tempCode, openid);
 
        UserCredential userCredential = new UserCredential(openid, CredentialType.WECHAT_OPENID.name(), appUser.getId(),null);
        userCredentialsDao.save(userCredential);
        log.info("保存微信登陆凭证,{}", userCredential);
 
        if (StringUtils.isBlank(appUser.getHeadImgUrl())) {
            appUser.setHeadImgUrl(wechatUserInfo.getHeadimgurl());
            appUserService.updateAppUser(appUser);
        }
 
        wechatUserInfo.setUserId(appUser.getId());
        wechatDao.update(wechatUserInfo);
        log.info("{},绑定微信成功,给微信设置用户id,{}", appUser, wechatUserInfo);
    }
 
    public WechatUserInfo checkAndGetWechatUserInfo(String tempCode, String openid) {
        String key = prefixKey(tempCode);
        String string = stringRedisTemplate.opsForValue().get(key);
        if (string == null) {
            throw new IllegalArgumentException("无效的code");
        }
 
        WechatUserInfo wechatUserInfo = JSONObject.parseObject(string, WechatUserInfo.class);
        if (!wechatUserInfo.getOpenid().equals(openid)) {
            throw new IllegalArgumentException("无效的openid");
        }
 
        // 删除临时tempCode
        stringRedisTemplate.delete(tempCode);
 
        return wechatUserInfo;
    }
 
}