ny
23 小时以前 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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
package jnpf.message.controller;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.message.entity.AccountConfigEntity;
import jnpf.message.entity.WechatUserEntity;
import jnpf.message.service.AccountConfigService;
import jnpf.message.service.WechatUserService;
import jnpf.permission.SocialsUserApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.SocialsUserEntity;
import jnpf.util.DateUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.XSSEscape;
import jnpf.util.wxutil.mp.WXGZHWebChatUtil;
import jnpf.util.wxutil.mp.aes.WXBizMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
 
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 发送消息模型
 *
 */
@Tag(name = "微信公众号事件接收", description = "WechatOpen")
@Controller
@RequestMapping("/WechatOpen")
@Slf4j
public class WxGZHFunctionController {
 
    @Autowired
    private UserApi userApi;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private SocialsUserApi socialsUserApi;
 
    /**
     * 服务器基本配置链接微信公众号验证
     *
     * @param request 请求对象
     * @param response 响应对象
     * @return
     */
    @Operation(summary = "服务器基本配置链接微信公众号验证")
    @ResponseBody
    @Parameters({
            @Parameter(name = "enCode", description = "微信公众号账号配置编码", required = true)
    })
    @GetMapping("/token/{enCode}")
    public String token(@PathVariable("enCode") String enCode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取微信公众号账号配置
        AccountConfigEntity accountConfigEntity = accountConfigService.getInfoByEnCode(enCode,"7");
        if(ObjectUtil.isEmpty(accountConfigEntity)){
            log.info("未找到与编码相对应的微信公众号配置");
            return "";
        }
        //微信公众号服务器配置token
        String wxToken = accountConfigEntity.getAgentId();
        String signature = request.getParameter("signature");
        String echostr = XSSEscape.escape(request.getParameter("echostr"));
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
 
        String sortStr = WXGZHWebChatUtil.sort(wxToken,timestamp,nonce);
        String MySinStr = WXGZHWebChatUtil.shal(sortStr);
        if(StringUtil.isNotBlank(signature) && MySinStr.equals(signature)){
            return echostr;
        }else {
            log.info("微信公众号链接失败");
            return echostr;
        }
    }
 
 
    /**
     * 微信公众号事件请求
     *
     * @param request 请求对象
     * @param response 响应对象
     * @return
     * @throws Exception
     */
    @Operation(summary = "微信公众号事件请求")
    @ResponseBody
    @PostMapping("/token/{enCode}")
    public String tokenPost(@PathVariable("enCode") String enCode,HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("微信公众号请求事件");
        //获取微信公众号账号配置
        AccountConfigEntity accountConfigEntity = accountConfigService.getInfoByEnCode(enCode,"7");
        if(ObjectUtil.isEmpty(accountConfigEntity)){
            log.info("未找到与编码相对应的微信公众号配置");
            return "";
        }
        //微信公众号服务器配置token
        String wxToken = accountConfigEntity.getAgentId();
        //微信公众号服务器配置EncodingAesKey
        String encodingAesKey = accountConfigEntity.getBearer();
        //微信公众号AppId
        String wxAppId = accountConfigEntity.getAppId();
 
        // 获取系统配置
        String msgSignature  = request.getParameter("msg_signature");
        String encrypt_type = request.getParameter("encrypt_type");
 
        String signature = request.getParameter("signature");
        String echostr = XSSEscape.escape(request.getParameter("echostr"));
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
 
        String sortStr = WXGZHWebChatUtil.sort(wxToken,timestamp,nonce);
        String mySinStr = WXGZHWebChatUtil.shal(sortStr);
        //验签
        if(StringUtil.isNotBlank(signature) && mySinStr.equals(signature)){
            //事件信息
            Map<String ,Object> map = WXGZHWebChatUtil.parseXml(request);
            //事件信息
            String Event = String.valueOf(map.get("Event"));
            String openid = String.valueOf(map.get("FromUserName"));
            //公众号原始id
            String gzhId = String.valueOf(map.get("ToUserName"));
            if("aes".equals(encrypt_type)) {
                WXBizMsgCrypt pc = new WXBizMsgCrypt(wxToken, encodingAesKey, wxAppId);
                String encrypt = String.valueOf(map.get("Encrypt"));
                String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
                String fromXML = String.format(format, encrypt);
                // 获取解密后消息明文
                String result = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);
 
                Map<String, Object> resultMap = WXGZHWebChatUtil.xmlToMap(result);
                // 获取解密后事件信息
                Event = String.valueOf(resultMap.get("Event"));
                openid = String.valueOf(resultMap.get("FromUserName"));
                gzhId = String.valueOf(resultMap.get("ToUserName"));
            }
 
            String appId = accountConfigEntity.getAppId();
            String appsecret = accountConfigEntity.getAppSecret();
            String token = WXGZHWebChatUtil.getAccessToken(appId,appsecret);
            if("subscribe".equals(Event)){
                //用户关注事件
                if(StringUtil.isNotBlank(token)){
                    JSONObject rstObj = WXGZHWebChatUtil.getUsetInfo(token,openid);
                    if(rstObj.containsKey("unionid")){
                        String unionid = rstObj.getString("unionid");
                        SocialsUserEntity socialsUserEntity = socialsUserApi.getInfoBySocialId(unionid,"wechat_open");
//                        SocialsUserInfo socialsUserInfo = socialsUserApi.getUserInfo("wechat_applets",unionid,null);
                        if(socialsUserEntity==null){
                            log.info("微信公众号未绑定系统账号,请登录小程序绑定");
                            return "";
                        }else{
                            WechatUserEntity wechatUserEntity = wechatUserService.getInfoByGzhId(socialsUserEntity.getUserId(),gzhId);
                            if(wechatUserEntity==null){
                                WechatUserEntity entity = new WechatUserEntity();
                                entity.setId(RandomUtil.uuId());
                                 entity.setUserId(socialsUserEntity.getUserId());
                                entity.setGzhId(gzhId);
                                entity.setCloseMark(1);
                                entity.setCreatorTime(DateUtil.getNowDate());
                                entity.setOpenId(openid);
                                wechatUserService.create(entity);
                                return "";
                            }else {
                                if(wechatUserEntity.getCloseMark()==0){
                                    wechatUserEntity.setCloseMark(1);
                                }
                                wechatUserEntity.setOpenId(openid);
                                wechatUserEntity.setLastModifyTime(DateUtil.getNowDate());
                                wechatUserService.update(wechatUserEntity.getId(),wechatUserEntity);
                            }
                            return "";
                        }
                    }else{
                        log.info("微信公众号未绑定系统账号,请登录小程序绑定");
                        return "";
                    }
                }else{
                    log.error("微信公众号token错误,请查看配置");
                    return "";
                }
            }else if("unsubscribe".equals(Event)){
                //用户取消关注事件
                if(StringUtil.isNotBlank(token)){
                    JSONObject rstObj = WXGZHWebChatUtil.getUsetInfo(token,openid);
                    if(rstObj.containsKey("unionid")){
                        String unionid = rstObj.getString("unionid");
                        SocialsUserEntity socialsUserEntity = socialsUserApi.getInfoBySocialId(unionid,"wechat_open");
                        if(socialsUserEntity==null){
                            log.info("微信公众号未绑定系统账号,请登录小程序绑定");
                        }else{
                            WechatUserEntity wechatUserEntity = wechatUserService.getInfoByGzhId(socialsUserEntity.getUserId(),gzhId);
                            if(wechatUserEntity==null){
                                WechatUserEntity entity = new WechatUserEntity();
                                entity.setId(RandomUtil.uuId());
                                entity.setUserId(socialsUserEntity.getUserId());
                                entity.setGzhId(gzhId);
                                entity.setCloseMark(0);
                                entity.setCreatorTime(DateUtil.getNowDate());
                                entity.setOpenId(openid);
                                wechatUserService.create(entity);
                                return "";
                            }else {
                                if(wechatUserEntity.getCloseMark()==1){
                                    wechatUserEntity.setCloseMark(0);
                                }
                                wechatUserEntity.setOpenId(openid);
                                wechatUserEntity.setLastModifyTime(DateUtil.getNowDate());
                                wechatUserService.update(wechatUserEntity.getId(),wechatUserEntity);
                                return "";
                            }
                        }
                    }else{
                        log.info("微信公众号未绑定系统账号,请登录小程序绑定");
                        return "";
                    }
                }else{
                    log.error("微信公众号token错误,请查看配置");
                    return "";
                }
                return "";
            }else {
                return "";
            }
        }else {
            log.info("微信公众号事件请求失败");
            return echostr;
        }
    }
 
}