WechatMod.java 2.55 KB
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 "微信公众号消息推送失败";
    }
}