WechatMod.java
2.55 KB
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
package vion.third;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author HlQ
* @date 2023/11/21
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class WechatMod {
private final WxMpService wxMpService;
/**
* 微信扫码获取用户 openid
*
* @param code 授权码
* @return java.lang.Object
*/
public Object wechatCallback(String code) {
try {
WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
return wxMpUser.getOpenid();
} catch (WxErrorException e) {
log.error("调用微信接口异常!", e);
}
return new ModelAndView("weChatError");
}
/**
* 生成微信网页授权链接
*
* @param taskTempId 预工单 id
* @return java.lang.String
*/
public String genQRCodeUrl(Long taskTempId) {
String url = StrUtil.format("https://yunwei.vionyun.com/yunwei/api/wechat/callback?taskTempId={}", taskTempId);
return wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
}
public String sendMsg(String templateId, String openId, List<WxMpTemplateData> wxMpTemplateDataList, String url) {
try {
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(templateId)
.data(wxMpTemplateDataList)
.url(url)
.build();
String s = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
log.info("微信消息推送成功,msgid:{}", s);
return "微信公众号消息推送成功";
} catch (WxErrorException e) {
log.error("调用微信接口发送模板消息异常!", e);
}
return "微信公众号消息推送失败";
}
}