WechatMod.java 5.25 KB
package vion.third;

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.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import vion.dto.WxDTO;
import vion.event.WxDTOEvent;

import java.util.List;

/**
 * @author vion
 * @date 2023/11/21
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class WechatMod {

    private final WxMpService wxMpService;
    private final ApplicationEventPublisher publisher;

    /**
     * 用于微信公众号内提交单子。
     * 用户已关注公众号,直接获取 openid 即可。
     *
     * @param code 授权码
     * @return java.lang.Object
     */
    public Object getOpenid(String code) {
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            String openid = userInfo.getOpenid();
            String nickname = userInfo.getNickname();
            return MapUtil.<String, String>builder()
                    .put("nickname", nickname)
                    .put("openid", openid).build();
        } catch (WxErrorException e) {
            log.error("调用微信接口异常!", e);
        }
        return new ModelAndView("weChatError");
    }

    /**
     * 生成微信网页授权链接用于 pc 端故障保修、点位设计等页面,绑定openid
     *
     * @param id   生成单子的 id
     * @param flag 1:故障保修 2:点位设计
     * @return java.lang.String
     */
    public String genCallbackQRCode(Long id, Integer flag) {
        String redirectUri = StrUtil.format("https://yunwei.vionyun.com/yunwei/api/getFollowingOpenid?id={}&flag={}", id, flag);
        return wxMpService.getOAuth2Service().buildAuthorizationUrl(redirectUri, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }

    /**
     * 用户提交单子,需要判断用户是否关注公众号。
     * 关注公众号的用户,直接获取 openid,返回前端,前端提交工单(或其他单子)时带上 openid。
     * 未关注公众号的用户,直接返回一个页面,提示用户关注公众号。
     *
     * @param id   提交单子的主键id
     * @param flag 1:故障保修 2:点位设计 3:备件申请 4:设备返修
     * @param code 授权码
     * @return java.lang.Object
     */
    public Object getFollowingOpenid(Long id, Integer flag, String code) {
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            String openid = userInfo.getOpenid();
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openid);
            if (!wxMpUser.getSubscribe()) {
                return new ModelAndView("weChatNeedAttention");
            }
            String nickname = userInfo.getNickname();
            WxDTO wxDTO = WxDTO.builder().nickname(nickname).openid(openid).id(id).flag(flag).build();
            WxDTOEvent wxDTOEvent = new WxDTOEvent(this, wxDTO);
            publisher.publishEvent(wxDTOEvent);

            return new ModelAndView("weChatSuccess");
        } catch (WxErrorException e) {
            log.error("调用微信接口异常!", e);
        }
        return new ModelAndView("weChatError");
    }

    /**
     * 点位设计详情页获取绑定微信二维码
     *
     * @param uuid 点位记录 uuid
     * @return java.lang.String
     */
    public String genBindOpenidQRCode(String uuid) {
        String redirectUri = StrUtil.format("https://yunwei.vionyun.com/yunwei/api/point/getBindOpenid?uuid={}&rid={}", uuid, IdUtil.fastSimpleUUID());
        return wxMpService.getOAuth2Service().buildAuthorizationUrl(redirectUri, 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 "微信公众号消息推送失败";
    }
}