cloudroam
2025-03-28 795fb91c35818cd806b3cf19794736efccd59760
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
package com.mzl.flower.service.system;
 
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.mzl.flower.base.cache.StringCacheClient;
import com.mzl.flower.config.WxMiniappProperties;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.CreateWechatUserDTO;
import com.mzl.flower.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
@Service
@Transactional
@Slf4j
public class WeChatService extends BaseService {
 
    @Autowired
    private StringCacheClient cacheClient;
 
    @Autowired
    private WxMaService maService;
 
    @Autowired
    private WxMpConfigStorage wxMpConfigStorage;
 
    @Autowired
    private WxMiniappProperties wxMiniappProperties;
 
    @Autowired
    private Gson gson;
 
    /**
     * 小程序获取会话信息-花店端
     * @param code
     * @return
     * @throws WxErrorException
     */
    public WxMaJscode2SessionResult getWxMaSessionInfo(String code) throws WxErrorException {
        WxMaJscode2SessionResult result = maService.jsCode2SessionInfo(code);
        return result;
    }
 
    public void getWxMaUserPhone(String code) throws WxErrorException {
        WxMaUserService us = maService.getUserService();
        WxMaJscode2SessionResult session = us.getSessionInfo(code);
        //sessionKey, encryptedData, iv
        us.getPhoneNoInfo(session.getSessionKey(), "", "");
    }
 
    /**
     * 小程序获取openid
     * @param code
     * @return
     * @throws IOException
     */
    public Map<String, Object> getWechatOpenId(String code,String userType) throws IOException {
        if (StringUtils.isEmpty(code)) {
            throw new ValidationException("微信code为空");
        }
        String appId = null;
        String secret = null;
        if(Constants.USER_TYPE.customer.name().equals(userType)){
            WxMiniappProperties.Miniapp customer = wxMiniappProperties.getCustomer();
            appId = customer.getAppid();
            secret = customer.getSecret();
        }else if(Constants.USER_TYPE.partner.name().equals(userType)){
            WxMiniappProperties.Miniapp customer = wxMiniappProperties.getPartner();
            appId = customer.getAppid();
            secret = customer.getSecret();
        }else if(Constants.USER_TYPE.supplier.name().equals(userType)){
            WxMiniappProperties.Miniapp customer = wxMiniappProperties.getSupplier();
            appId = customer.getAppid();
            secret = customer.getSecret();
        }else{
            throw new ValidationException("用户类型不支持");
        }
        String param = "?grant_type=authorization_code&appid=" + appId + "&secret=" + secret + "&js_code=" + code;
        String url = "https://api.weixin.qq.com/sns/jscode2session" + param;
 
        HttpClient http = new HttpClient();
        http.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
 
        GetMethod get = new GetMethod(url);
 
        http.executeMethod(get);
        String json = get.getResponseBodyAsString();
        Map<String, Object> map = parseObject(json, Map.class);
        Object errcode = map.get("errcode");
        if(errcode != null){
            String errmsg = (String)map.get("errmsg");
            throw new ValidationException(errmsg);
        }
 
        return map;
    }
 
    /**
     * 获取公众号accessToken
     * @return
     */
    public String getGZHAccessToken(){
        String appId = wxMpConfigStorage.getAppId();
        String secret = wxMpConfigStorage.getSecret();
 
        return getAccessToken(appId, secret);
    }
 
    public String getAccessToken(String appId, String secret){
        if(StringUtils.isEmpty(appId) || StringUtils.isEmpty(secret)){
            return null;
        }
        String key = "WX_" + appId;
        String token = cacheClient.get(key);
        if(StringUtils.isEmpty(token)){
            Map<String, Object> map = getAccessTokenFromWeiXin(appId, secret);
            token = (String) map.get("access_token");
            Integer expiresIn = (Integer) map.get("expires_in");
            cacheClient.set(key, token, expiresIn - 100);
        }
 
        return token;
    }
 
    private Map<String, Object> getAccessTokenFromWeiXin(String appId, String secret){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        try{
            HttpClient http = new HttpClient();
            GetMethod get = new GetMethod(url);
            http.executeMethod(get);
            String json = get.getResponseBodyAsString();
            Map<String, Object> map = parseObject(json, Map.class);
            Object errcode = map.get("errcode");
            if(errcode != null){
                String errmsg = (String)map.get("errmsg");
                log.error(errcode + ":" + errmsg);
                throw new ValidationException(errmsg);
            }
 
            return map;
        }catch (IOException e){
            log.error(e.getMessage(), e);
            throw new ValidationException(e.getMessage());
        }
    }
    public Map<String,Object> getuserphonenumber(CreateWechatUserDTO dto) {
        if (StringUtils.isEmpty(dto.getCode())) {
            throw new ValidationException("微信code为空");
        }
 
        String accessToken="";
        try {
            accessToken=maService.getAccessToken();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
 
        if(StringUtils.isEmpty(accessToken)){
            accessToken=getAccessToken(
                    wxMiniappProperties.getCustomer().getAppid(),
                    wxMiniappProperties.getCustomer().getSecret());
            if(StringUtils.isEmpty(accessToken)){
                throw new ValidationException("获取微信AccessToken失败");
            }
        }
 
 
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+ accessToken;
        try{
            Map<String,Object> params=new HashMap<String,Object>();
            params.put("code",dto.getCode());
            String result = HttpUtil.post(url, gson.toJson(params));
            System.out.println(result);
            Map<String,Object> resultMap=gson.fromJson(result,Map.class);
            if(!resultMap.get("errmsg").equals("ok")){
                String errmsg = (String)resultMap.get("errmsg");
                log.error(resultMap.get("errcode") + ":" + errmsg);
                throw new ValidationException(errmsg);
            }
            return resultMap;
        }catch (Exception e){
            log.error(e.getMessage(), e);
            throw new ValidationException(e.getMessage());
        }
    }
}