微信公众号模板消息发送

前段时间有幸在工作中用到了微信公众号模板消息推送,在这里把自己在使用过程中的一些心得发一下,如有不明白的大家一起讨论。

前提准备

申请微信公众号–申请开通模板消息(如果主页面没有,请到左下方的那个+号点开;还有一点注意:只有认证的服务号才可以使用模版消息接口,订阅号无法使用这一功能。)

微信公众号基本设置–记住这里的AppID和AppSecret(AppSecret初始是无值的,需要生成),后续需要设置微信配置
在这里插入图片描述

OpenID:每个用户的唯一标识(注意:这里的openId和微信小程序的openId不是同一个)
消息模板ID:需要提前在微信公众后台,从模板库中添加自己需要的模板(当然也可以自己申请)
在这里插入图片描述

注意:在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
准备参数:
1.公众号用户的openId
2.消息模板ID
3.小程序跳转页面 pagePath
4.消息内容WxMpTemplateData

获取用户openId步骤:
参考文档地址:微信开放文档
第一步:用户同意授权,前端获取code
第二步:通过code获取session_key、openId和unionId
请求以下链接获取:
https://api.weixin.qq.com/sns/jscode2session?appid=appid&js_code=code&grant_type=authorization_code

maven包引入

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-mp</artifactId>
    <version>3.7.0</version>
</dependency>

代码示例:

配置类

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WeiXinConfig {
	//我这里是用的SpringBoot项目,在yml配置文件配置了开头提到的AppID和AppSecret
    @Value("${weChatOfficial.appid}")
    private String appid;

    @Value("${weChatOfficial.secret}")
    private String secret;

    @Bean
    public WxMpDefaultConfigImpl wxMpDefaultConfig() {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(appid);
        config.setSecret(secret);
        return config;
    }

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxService = new WxMpServiceImpl();
        wxService.setWxMpConfigStorage(wxMpDefaultConfig());
        return wxService;
    }

}

公众号模板消息发送

import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;

    @GetMapping("/sendTemplateMsg")
    @ResponseBody
    public DataPipe sendTemplateMsg(){
        //pagePath暂时不传,小程序还未发布
        String pagePath="";
        String first = "您有一个新的审核信息需要处理";
        String keyword1="审核申请";
        String keyword2="张三";
        String remark="这是个备注";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String keyword3 = sdf.format(new Date());
        List<WxMpTemplateData> data = new ArrayList<WxMpTemplateData>(){{
            add(new WxMpTemplateData("first", first));
            add(new WxMpTemplateData("keyword1", keyword1));
            add(new WxMpTemplateData("keyword2", keyword2));
            add(new WxMpTemplateData("keyword3", keyword3));
            add(new WxMpTemplateData("remark",  remark));
        }};
        sendTemplateMsgService.sendTemplateMsg("用户公众号openId", templateId, "小程序跳转地址,可填可不填", data);
    }
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/***
 * 发送公众号模板消息
 */
@Service
@Slf4j
public class SendTemplateMsgService {
	
	/***
	* 微信小程序appId
	*/
    private String appid;

    @Resource
    private WxMpService wxMpService;

    /***
     * 发送公众号模板消息
     * @param openId 接收人微信OpenId
     * @param templateId 模板ID
     * @param pagePath 小程序跳转路径
     * @param list 模板内容
     * @return
     */
    public void sendTemplateMsg(String openId, String templateId, String pagePath, List<WxMpTemplateData> list) {
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(appid);
        miniProgram.setPagePath(pagePath);
        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage
                .builder()
                .templateId(templateId)
                .toUser(openId)
                .miniProgram(miniProgram)
                .build();
        wxMpTemplateMessage.setData(list);
        wxMpTemplateMessage.setTemplateId(templateId);
        try {
            String result = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            log.info(result);
        } catch (WxErrorException e) {
//            e.printStackTrace();
            log.error("[微信模板消息发送] 发送失败 , {}",e);
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
发送微信公众号模板消息,你需要先获取到模板消息模板ID和用户的openid。然后按照以下步骤进行操作: 1. 构建消息体 首先,你需要构建一个消息体,指明要发送模板ID、接收者openid消息内容。例如,以下是一个消息体的示例: ``` { "touser":"OPENID", "template_id":"TEMPLATE_ID", "url":"http://weixin.qq.com/download", "data":{ "first": { "value":"恭喜你购买成功!", "color":"#173177" }, "keyword1":{ "value":"巧克力", "color":"#173177" }, "keyword2": { "value":"39.8元", "color":"#173177" }, "keyword3": { "value":"2014年9月22日", "color":"#173177" }, "remark":{ "value":"欢迎再次购买!", "color":"#173177" } } } ``` 其中,touser指明接收者openid,template_id指明模板ID,url是点击模板消息跳转的链接(可选),data是消息内容。 2. 发送请求 构建好消息体后,你需要向微信服务器发送请求,调用发送模板消息的API。具体的API接口为: ``` https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN ``` 其中,ACCESS_TOKEN是你的公众号的access_token。 3. 处理返回结果 发送请求后,微信服务器会返回一个JSON格式的响应。你需要根据返回结果来判断消息是否发送成功。如果发送成功,返回结果中的errcode应该是0。 以上就是发送微信公众号模板消息的主要步骤,你需要根据自己的实际需求来构建消息体和处理返回结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值