xuekang
2024-05-11 bac0878349a1db23e7b420ea164e22fb9db73a99
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
package com.nuvole.util;
 
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.nuvole.common.domain.dto.AppDTO;
import com.nuvole.common.domain.wx.PushMsg;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.HtmlUtils;
 
import java.util.*;
 
/**
 * 小程序工具类
 *
 * @author liujun
 * @Date 2019/5/27 16:40
 */
@Slf4j
public class WxUtil {
 
    /**
     * 获取临时登录凭证code
     *
     * @param appid  AppID(小程序ID)
     * @param secret AppSecret(小程序密钥)
     * @param jsCode 登录时获取的Code
     * @return
     */
    public static String getOpenidSessionKey(String appid, String secret, String jsCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("js_code", jsCode);
        paramMap.put("grant_type", "authorization_code");
        return HttpUtil.get(url, paramMap);
    }
 
    /**
     * 获取AccessToken
     *
     * @param appid  AppID(小程序ID)
     * @param secret AppSecret(小程序密钥)
     * @return
     */
    public static String getAccessToken(String appid, String secret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("grant_type", "client_credential");
        String s = HttpUtil.get(url, paramMap);
        log.info("获取AccessToken 参数= 》appid:{},secret:{}", appid, secret);
        log.info("获取AccessToken = 》{}", s);
        return s;
    }
 
    /**
     * 获取AccessToken
     *
     * @param accessToken getAccessToken方法获取的access_token
     * @return
     */
    public static String getJsapTicket(String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("type", "jsapi");
        paramMap.put("access_token", accessToken);
        return HttpUtil.get(url, paramMap);
    }
 
    /**
     * Createed by PKZ Date 2019/6/18 17:11 Description:微信公众号获取access_token
     **/
    public static String getWechatAccessToken(String appid, String secret, String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("code", code);
        paramMap.put("grant_type", "authorization_code");
        return HttpUtil.get(url, paramMap);
    }
 
    /**
     * Createed by PKZ Date 2019/6/18 17:13 Description:微信公众号获取用户信息
     **/
    public static String getWechatUserInfo(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("access_token", access_token);
        paramMap.put("openid", openid);
        paramMap.put("lang", "zh_CN");
        return HttpUtil.get(url, paramMap);
    }
 
    /**
     * 该接口用于将 code 换取用户手机号
     *
     * @param access_token
     * @param code
     * @return
     */
    public static String getUserPhoneNumber(String access_token, String code) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("code", code);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        log.info("getUserPhoneNumber=>{}", result);
        JSONObject resultInfo = JSONObject.parseObject(result);
        if (resultInfo.getIntValue("errcode") == 0) {
            return resultInfo.getJSONObject("phone_info").getString("purePhoneNumber");
        }
        return null;
    }
 
    /**
     * 获取 URL Link
     *
     * @param access_token
     * @return
     */
    public static String generateUrllink(String access_token) {
        String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + access_token;
        Map<String, Object> paramMap = new HashMap<>(1);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        log.info("generateUrllink=>{}", result);
        JSONObject resultInfo = JSONObject.parseObject(result);
        if (resultInfo.getIntValue("errcode") == 0) {
            return resultInfo.getString("url_link");
        }
        return null;
    }
 
 
    /*
     * @Author : liu.q [916000612@qq.com]
     *
     * @Date : 2019-06-27 09:49
     *
     * @Description :获取小程序码(前提是已发布)
     *
     * @secne 参数
     *
     * @width 码宽
     *
     * @page 码跳转路径
     */
    public static byte[] getQRcode(String access_token, String scene, int width, String page) {
        RestTemplate rest = new RestTemplate();
        byte[] result = null;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", scene);
//            param.put("access_token", access_token); //access_token接在url后
            param.put("page", page);
            param.put("width", width);
            param.put("auto_color", true);
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 54);
            line_color.put("g", 56);
            line_color.put("b", 115);
            param.put("line_color", line_color);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            AppDTO sto = new AppDTO();
            AppDTO s = new AppDTO();
            sto.setMap(param);
            sto.setPro(url);
            BeanUtils.copyProperties(sto, s);
//            String result22 = HttpUtil.post(url, JSONUtil.toJsonStr(param));
//            log.info("getUserPhoneNumber=>{}",result22);
            HttpEntity requestEntity = new HttpEntity(s.getMap(), headers);
            ResponseEntity<byte[]> entity = rest.exchange(s.getPro(), HttpMethod.POST, requestEntity, byte[].class,
                    new Object[0]);
            result = entity.getBody();
            if (entity.getHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_JSON)) {
                log.error(new String(result));
                return null;
            }
            System.out.println(entity.toString());
 
            String imageStr = Base64.getEncoder().encodeToString(result);
            imageStr = HtmlUtils.htmlEscape(imageStr);
            result = Base64.getDecoder().decode(imageStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用小程序生成微信永久小程序码URL接口异常", e);
        }
        return result;
    }
 
    /**
     * 推送消息
     *
     * @param appId
     * @param secret
     * @param openId
     * @param formId
     * @param templateId
     * @param page
     * @param items
     */
    public static void push(String appId, String secret, String openId, String formId, String templateId, String page,
                            List<String> items) {
        // 1,配置小程序信息
        WxMaInMemoryConfig wxConfig = new WxMaInMemoryConfig();
        // 小程序appid
        wxConfig.setAppid(appId);
        // 小程序AppSecret
        wxConfig.setSecret(secret);
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxConfig);
        // 2,设置模版信息(keyword1:类型,keyword2:内容)
        List<WxMaTemplateData> templateDataList = new ArrayList<>(items.size());
        for (int i = 0; i < items.size(); i++) {
            WxMaTemplateData data = new WxMaTemplateData("keyword" + (i + 1), items.get(i));
            templateDataList.add(data);
        }
        // 3,设置推送消息
        WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder().toUser(openId).formId(formId)
                .templateId(templateId).data(templateDataList).page(page).build();
        // 4,发起推送
        try {
            wxMaService.getMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.info("任务失败:" + e.getMessage());
        }
    }
 
    /* *
     * 小程序-订阅消息-推送消息
     *
     * @author lc
     * @date 2019/12/30 9:52
     */
    public static String pushSend(PushMsg pushMsg, String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        try {
            System.out.println("is :" + JSONUtil.toJsonStr(pushMsg));
            String result = HttpUtil.post(url, JSONUtil.toJsonStr(pushMsg));
            log.info("is push result:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /* *
     * 公众号-模板消息
     *
     */
    public static String h5PubpushSend(PushMsg pushMsg, String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        try {
            System.out.println("is :" + JSONUtil.toJsonStr(pushMsg));
            String result = HttpUtil.post(url, JSONUtil.toJsonStr(pushMsg));
            log.info("is push result:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
 
}