SpringBoot 对接微信公众号模板消息通知

效果图见测试结果,有问题评论@

模板消息

开通模板消息功能

登录微信公众平台开通模板消息功能 (未开通时)

在这里插入图片描述

添加模板消息

  1. 审核通过后,登录微信公众平台,点击 广告与服务 --> 模板消息
  2. 公众号如果未设置服务类目,则需要先设置服务类目。
  3. 然后在模板库中挑选合适的模板消息即可,如下图。

在这里插入图片描述

对接开发

模板消息官方文档(建议看完,少走弯路)

引入依赖

参考:https://github.com/Wechat-Group/weixin-java-tools

<!-- 微信框架 -->
<dependency>
	<groupId>com.github.binarywang</groupId>
	<artifactId>weixin-java-mp</artifactId>
	<version>3.6.0</version>
</dependency>

添加模板消息工具类

在业务类中注入工具类即可
commonSendTemplateMsg公共消息通知发送 模板相同的消息
sendTemplateMsg 发送不同的模板消息,需要在业务类中构建消息内容。

/**
 * 微信公众号消息通知工具类
 */
@Slf4j
@Component
public class WeChatTemplateMsgUtils{

    @Autowired
    private WxMpService wxMpService;

    //公共消息通知
    public boolean commonSendTemplateMsg(String openId) {
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(TEMPLATE_ID);
        //设置详情跳转链接
        wxMpTemplateMessage.setUrl(WX_TEMPLATE_DETAILS_URL);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        //消息格式自行修改
        List<WxMpTemplateData> listData = new ArrayList<>();
        //WxMpTemplateData:key (time4) 对应 模板消息中的关键词 {{time4.DATA}}
        listData.addAll(Arrays.asList(
                new WxMpTemplateData("time4",DateUtils.parseDateToStr("yyyy-MM-dd hh:mm:ss",sessionInfo.getBiddingStartTime())),
                new WxMpTemplateData("time5",DateUtils.parseDateToStr("yyyy-MM-dd hh:mm:ss",sessionInfo.getBiddingEndTime()))));
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(listData);
        //接收发送模板消息结果,就是msgId
        boolean flag = false;
        try {
            //发送模板
            String json = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            if (StringUtils.isNotEmpty(json)){
                flag = true;
            }
        } catch (WxErrorException e) {
            log.error("发送模板消息异常:{}", e.getMessage());
        }
        return flag;
    }

    /**
     * 设置所属行业
     */
    public boolean setIndustry(WxMpTemplateIndustry wxMpIndustry) throws WxErrorException {
        Boolean flag = wxMpService.getTemplateMsgService().setIndustry(wxMpIndustry);
        return flag;
    }

    /**
     * 获取设置的行业信息
     */
    public WxMpTemplateIndustry getIndustry() throws WxErrorException {
        WxMpTemplateIndustry wxMpTemplateIndustry = wxMpService.getTemplateMsgService().getIndustry();
        return wxMpTemplateIndustry;
    }

    /**
     * 发送模板消息
     */
    public boolean sendTemplateMsg(WxMpTemplateMessage templateMessage) {
        //标识消息是否发送成功,true 成功,false 失败
        boolean flag = false;
        try {
        // result 为消息id
            String result = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            if (StringUtils.isNotEmpty(result)){
                flag = true;
            }
        } catch (WxErrorException e) {
            log.error("发送模板消息异常:{}", e.getMessage());
        }
        return flag;
    }


    /**
     * 获得模板ID
     */
    public String addTemplate(String shortTemplateId) throws WxErrorException {
        String result = wxMpService.getTemplateMsgService().addTemplate(shortTemplateId);
        return result;
    }

    /**
     * 获得模板列表
     */
    List<WxMpTemplate> getAllPrivateTemplate() throws WxErrorException {
        List<WxMpTemplate> templateList = wxMpService.getTemplateMsgService().getAllPrivateTemplate();
        return templateList;
    }

    /**
     * 删除模板
     * templateId: 公众帐号下模板消息ID
     */
    boolean delPrivateTemplate(String templateId) throws WxErrorException {
        Boolean flag = wxMpService.getTemplateMsgService().delPrivateTemplate(templateId);
        return flag;
    }

}

wxMpService 注入为空解决

详情见demo 参考:https://github.com/Wechat-Group/weixin-java-tools
完成下面3步即可。
1、application.yml 添加配置

# 微信公众号配置
wx:
  mp:
    configs:
      - appId: xxx # 公众号appid
        secret: xxx # 公众号密钥

2、添加 WxMpProperties 类

@Data
@ConfigurationProperties(prefix = "wx.mp")
public class WxMpProperties {
    /**
     * 多个公众号配置信息
     */
    private List<MpConfig> configs;

    @Data
    public static class MpConfig {
        /**
         * 设置微信公众号的appid
         */
        private String appId;

        /**
         * 设置微信公众号的app secret
         */
        private String secret;

    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}

3、添加 WxMpConfiguration 类

@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {
    private final WxMpProperties properties;

    @Bean
    public WxMpService wxMpService() {
        final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("添加下相关配置,注意别配错了!");
        }
        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(configs
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();;
                    configStorage.setAppId(a.getAppId());
                    configStorage.setSecret(a.getSecret());
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        return service;
    }
}

测试结果

手机显示结果

在这里插入图片描述

Postman测试结果

access_token可以从微信公众平台接口调试工具中获取,如下图

若获取不成功,需要在公众号平台IP白名单中添加本机IP地址。
设置与开发 ---> 安全中心 ----> IP白名单

在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对接微信公众模板消息接口,需要进行以下步骤: 1. 在微信公众平台上创建模板消息,获取模板 ID 和模板消息中需要填充的关键词。 2. 在 PHP 代码中编写发送模板消息的代码,包括获取 access_token 和发送模板消息。 3. 在用户触发某些事件时,调用 PHP 发送模板消息的代码。 以下是一个简单的 PHP 示例代码: ```php // 获取 access_token function getAccessToken($appID, $appSecret) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appID}&secret={$appSecret}"; $result = file_get_contents($url); $json = json_decode($result, true); if (isset($json['access_token'])) { return $json['access_token']; } else { return false; } } // 发送模板消息 function sendTemplateMessage($accessToken, $openID, $templateID, $data, $url = '') { $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}"; $data = [ 'touser' => $openID, 'template_id' => $templateID, 'url' => $url, 'data' => $data ]; $data = json_encode($data, JSON_UNESCAPED_UNICODE); $result = http_post_data($url, $data); $json = json_decode($result, true); if (isset($json['errcode']) && $json['errcode'] == 0) { return true; } else { return false; } } // 发送 POST 请求 function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); ob_start(); curl_exec($ch); $result = ob_get_contents(); ob_end_clean(); curl_close($ch); return $result; } // 示例代码 $appID = 'your-app-id'; $appSecret = 'your-app-secret'; $accessToken = getAccessToken($appID, $appSecret); $openID = 'your-open-id'; $templateID = 'your-template-id'; $data = [ 'first' => ['value' => 'Hello World!', 'color' => '#173177'], 'keyword1' => ['value' => 'value1', 'color' => '#173177'], 'keyword2' => ['value' => 'value2', 'color' => '#173177'], 'remark' => ['value' => 'This is a remark.', 'color' => '#173177'] ]; $url = 'http://example.com'; $result = sendTemplateMessage($accessToken, $openID, $templateID, $data, $url); if ($result) { echo '发送成功!'; } else { echo '发送失败!'; } ``` 请注意,以上代码仅作为示例,需要根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值