微信公众号初次开发
- 其他操作
- 项目搭建
- maven
- application.yml
- yml参数配置
- 微信客户端配置
- 搭建完成 实现业务
- 模板消息推送
- 准备工作
- 模板消息填写要求
- 图文消息填写要求
- 推送模板消息
- 推送模板消息结果——效果
- 推送图文消息
- 推送图文消息工具类
- 问题和结果
- 获取关注的用户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;
}
}
推送模板消息结果——效果
点击详情会进入百度
推送图文消息
/**
* 获取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 = "";
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();
}
}
推送图文消息工具类
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class xstream {
public static void connectWeiXinInterface(String action,String json){
URL url;
try {
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 传入参数
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("请求返回结果:"+result);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
问题和结果
要用户先发送一条消息给公众号,你才能发送成功
获取关注的用户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集合去循环发送