java向微信公众号---发送模板和图文消息

微信公众号初次开发

      • 其他操作
  • 项目搭建
    • maven
    • application.yml
    • yml参数配置
    • 微信客户端配置
  • 搭建完成 实现业务
    • 模板消息推送
      • 准备工作
        • 模板消息填写要求
        • 图文消息填写要求
      • 推送模板消息
        • 推送模板消息结果——效果
      • 推送图文消息
        • 问题和结果
    • 获取关注的用户openId
      • 既然有了openId集合和要发送的消息怎么群发

其他操作

书接上文:微信测试号申请步骤和调试.
书接下文:后台获取授权用户的openId.

项目搭建

maven

<dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.13</version>
        </dependency>
        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
            <version>1.6.0</version>
        </dependency>

        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.9</version>
        </dependency>

    </dependencies>

application.yml

###################  项目启动端口  ###################
server:
  port: 80

# 微信公众号配置
wx:
  #微信公众号APPID
  appid: 123
  #微信公众号SECRET
  secret: 123
  #微信公众号模板ID
  templateId: 123

yml参数配置


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 微信参数
 **/
@Data
@Component
@ConfigurationProperties(prefix = "wx")
public class WxMpProperties {
     

    /**
     * 公众号appId
     */
    private String appId;

    /**
     * 公众号appSecret
     */
    private String secret;

    /**
     * 公众号模板ID
     */
    private String templateId;
}

微信客户端配置


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

/**
 * 微信配置
 **/
@Configuration
public class WxConfig {
     

    @Autowired
    WxMpProperties wxMpProperties;

    /**
     * 构造注入
     *
     * @param wxMpProperties
     */
    WxConfig(WxMpProperties wxMpProperties) {
     
        this.wxMpProperties = wxMpProperties;
    }

    /**
     * 微信客户端配置存储
     *
     * @return
     */
    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
     
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        // 公众号appId
        configStorage.setAppId(wxMpProperties.getAppId());
        // 公众号appSecret
        configStorage.setSecret(wxMpProperties.getSecret());
        // 公众号Token
        configStorage.setToken(wxMpProperties.getToken());
        // 公众号EncodingAESKey
        configStorage.setAesKey(wxMpProperties.getAesKey());
        return configStorage;
    }

    /**
     * 声明实例
     *
     * @return
     */
    @Bean
    public WxMpService wxMpService() {
     
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }
}

搭建完成 实现业务

模板消息推送

准备工作

在这里插入图片描述
链接: 申请测试模板.

模板消息填写要求

first.DATA 跟上.DATA说明是数据

人员:{
     {
     first.DATA}} 
地址:{
     {
     keyword1.DATA}} 
区域:{
     {
     keyword2.DATA}} 
告警类型:{
     {
     remark1.DATA}} 
时间:{
     {
     remark2.DATA}}

图文消息填写要求

<xml> 
<Articles> 
	<item> 
		<Title><![CDATA[title1]]></Title> 
		<Description><![CDATA[description1]]></Description> 
		<PicUrl><![CDATA[picurl]]></PicUrl> 
		<Url><![CDATA[url]]></Url>
	</item>
	<item>
		<Title><![CDATA[title]]></Title>
		<Description><![CDATA[description]]></Description>
		<PicUrl><![CDATA[picurl]]></PicUrl> 
		<Url><![CDATA[url]]></Url> 
	</item>
</Articles> 
</xml>

推送模板消息

这里使用微信提供的serviceApi
链接: WxMpService.


import com.shangqu.datapush.buildsite.model.emnus.AlarmType;
import com.shangqu.datapush.buildsite.model.mysqlData.AlarmInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpAiOpenService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
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.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 微信消息推送
 *
 **/
@Slf4j
@Component
@CrossOrigin
public class WxMsgPush {
     

    /**
     * 微信公众号API的Service
     */
    private final WxMpService wxMpService;

    /**
     * 构造注入
     */
    WxMsgPush(WxMpService wxMpService) {
     
        this.wxMpService = wxMpService;
    }


    /**
     * 发送微信模板信息
     *
     * @param openId 接受者openId
     * @return 是否推送成功
     */
    public Boolean SendWxMsg(String openId,String templateId) {
     

        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId(templateId)
                // 模板跳转链接
                .url("www.baidu.com")
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", "null告警""#000000"))
                .addData(new WxMpTemplateData("keyword1", "","#000000"))
                .addData(new WxMpTemplateData("keyword2","", "#000000"))
                .addData(new WxMpTemplateData("keyword3", "", "#000000"))
                .addData(new WxMpTemplateData("keyword4", "", "#000000"));
        String msgId = null;
        try {
     
            // 发送模板消息
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);

        } catch (WxErrorException e) {
     
            e.printStackTrace();
        }
        log.warn("·==++--·推送微信模板信息:{}·--++==·", msgId != null ? "成功" : "失败");
        return msgId != null;
    }

}

推送模板消息结果——效果

java向微信公众号---发送模板和图文消息_第1张图片
点击详情会进入百度

推送图文消息

    /**
     * 获取token
     * @return
     */
    public String getAccessToken() throws WxErrorException {
     
        String accessToken = wxMpService.getAccessToken();
        return accessToken;
    }


	@ApiOperation(value = "", notes = "")
    @ResponseBody
    @RequestMapping(value = "/findwx", method = RequestMethod.POST)
    public void SendQYMessageimg(@RequestParam("id") String id) throws WxErrorException {
     
        String Url = "http://www.baidu.com";
        String mp = getAccessToken();
        String strurl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + mp;

        try {
     

			//图片地址
            String PicUrl = "https://img-blog.csdn.net/20160907155302548";

            String responeJsonStr = "{";
            //用户openId
            responeJsonStr += "\"touser\": \"" + "用户openId" + "\",";
            responeJsonStr += "\"msgtype\": \"news\",";
            responeJsonStr += "\"agentid\": \"wxd4aff8****\",";
            responeJsonStr += "\"news\": {";
            responeJsonStr += "\"articles\": [{";
            responeJsonStr += "  \"title\": \"" + "震惊外国一小伙竟然做出... ..." + "\",";
            responeJsonStr += "  \"description\": \" " + "今日一美国男子在家中,竟然做出... ..." + "\",";
            responeJsonStr += "  \"url\": \"" + Url + "\",";
            responeJsonStr += "  \"picurl\": \"" + PicUrl + "\"";
            responeJsonStr += "}]";
            responeJsonStr += "},";
            responeJsonStr += "\"safe\":\"0\"";
            responeJsonStr += "}";
            xstream.connectWeiXinInterface(strurl, responeJsonStr);

        } catch (Exception e) {
     
            e.printStackTrace();
        }

    }

问题和结果

要用户先发送一条消息给公众号,你才能发送成功
java向微信公众号---发送模板和图文消息_第2张图片
点击消息会进入百度

获取关注的用户openId

    /**
     * 获得关注公众号所有openid
     * @return
     * @throws WxErrorException
     */
    @Override
    public List<String> getUserList() throws WxErrorException {
     
        WxMpUserList wxMpUserList = wxMpService.getUserService().userList(null);
        List<String> openids = wxMpUserList.getOpenids();
        return openids;
    }

既然有了openId集合和要发送的消息怎么群发

微信并没有提供群发接口–就在自己代码中迭代openId集合去循环发送

你可能感兴趣的:(微信,java,小程序,经验分享)