1,官网地址:申请测试公众号
地址: 微信公众平台 (qq.com)
文档地址:微信开放文档 (qq.com)
2,注册后可以查看自己的appId 和 appsecret
3,创建模板
我创建的模板
早安!:{{name.DATA}}
天气:{{weather.DATA}}
距离破壳日:{{birthday.DATA}}
发送消息和推送消息都是需要 token 的,所以第一步就可以获取token,再拿获取的token 进行发送消息,每天获取token的是有次数限制的(2000次)
使用微信公众号需要的依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.3.0</version>
</dependency>
我这里把 也添上,等下可以在swagger测试
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- knife4j 依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
controller 层
这里就两个部分,getToken() 方法 是获取token, pushMessage() 是推送消息(这里代码中没有模板id,需要修改成上面自己创建的模板id)
@Api(tags = "各项测试")
@RestController
@RequestMapping("/loginInfo")
public class SendWeChatMessageController {
// /*
// * 功能: 公众号:appid,这里也可以配置到yaml 文件里面
// */
//
// @Value("${wx.appId}")
// private String appId;
//
// /*
// * 功能: 公众号:appsecret
// */
//
// @Value("${wx.appsecret}")
// private String appsecret;
private final Logger logger = LoggerFactory.getLogger(SendWeChatMessageController.class);
@ApiOperation("获取token")
@GetMapping("/getToken")
public Object getToken(@PathParam("grantType") String grantType,@PathParam("appId") String appId,@PathParam("secret") String secret) throws Exception {
String tokenUrl = WeChatUrlEnum.TOKEN.getUrl();
String params = "grant_type=" + grantType + "&appid=" + appId + "&secret=" + secret;
logger.info("请求地址为:" + tokenUrl + params);
String tokenResponse = HttpUtils.sendGet(tokenUrl, params);
JSON parse = JSONUtil.parseObj(tokenResponse);
System.out.println(parse);
return parse;
}
@ApiOperation("发送消息")
@PostMapping("/testPushMessage")
public String pushMessage(@RequestBody PushMessageToUserVo pushMessageToUserVo) {
// 组装要发送的数据
JSONObject body = new JSONObject();
// 要推给谁
body.put("touser", pushMessageToUserVo.getTouser());
// 模板ID
body.put("template_id", "这里填写自己的模板id");
String accessToken = pushMessageToUserVo.getAccessToken();
// 创建消息和内容,这里可以自己定义,对应好模板就行
JSONObject data = new JSONObject();
data.put("name", new JSONObject().put("value", "做一个身体和心灵都勇敢的人,趁着身体未老,心灵还透明。晚安!"));
data.put("weather", new JSONObject().put("value", "阴天 19°c"));
data.put("birthday", new JSONObject().put("value", "53 天"));
body.put("data", data);
logger.info("body---->{}", body.toString());
String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, body.toString());
logger.info("通知到用户--->{}", post);
return body.toString();
}
}
config
这里使用 knife4j,等下好测试接口
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact("xx@qq.com")
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径,自行记得修改!!!!
.apis(RequestHandlerSelectors.basePackage("com.example.springbootwechat.controller"))
.paths(PathSelectors.any())
.build();
}
}
entity
这个是推送消息vo,给那个用户推送消息,并带上token
@Data
@ApiModel(description = "用户推送vo")
public class PushMessageToUserVo {
@ApiModelProperty(value = "用户微信关注号", required = true)
private String touser;
@ApiModelProperty(value = "用户Token", required = true)
private String accessToken;
}
enum
我这里是把地址都变成枚举,因为后面地址会比较多,便于维护,当然也可以配置在yaml ,或者定义在使用处。
public enum WeChatUrlEnum {
/**
* 获取token
*/
TOKEN("获取微信 token的地址","https://api.weixin.qq.com/cgi-bin/token");
private String info;
private String url;
WeChatUrlEnum(String info,String url) {
this.info =info;
this.url = url;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
utils
工具类:发送http get,post 请求
public class HttpUtils {
public static String sendGet(String url, String query) throws Exception {
String fullUrl = url + "?" + query;
HttpURLConnection connection = (HttpURLConnection) new URL(fullUrl).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode()!= 200) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine())!= null) {
sb.append(output);
}
connection.disconnect();
return sb.toString();
}
public static String sendPost(String url, String data) throws Exception {
URL fullUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) fullUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
if (connection.getResponseCode()!= 200) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine())!= null) {
sb.append(output);
}
connection.disconnect();
return sb.toString();
}
}
接口swagger地址:http://127.0.0.1:1955/doc.html 自己注意端口
1,获取token
2,发送消息
手机端:接收到的消息
谢谢看到这!!!有不对地方,可以留言评论讨论哦!!!
希望可以动动小手,点个关注!!!