这篇文章给大家介绍如何使用Java开发微信公众号,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
个人微信公众号相关的接口权限有限,不过用于个人学习体验一下足够了,如图:
然后进入微信公众后台,点击基本配置,按照如下操作(点击启用,相当于设置请求url为自己后台的):
设置服务器URL、令牌、消息加解密密钥(这个可以使用自动生成的):
服务器URL至关重要,我在这里设置为我自己的域名http://www.youcongtech.com/wx-api。
这个wx-api就是后面对应的接口(比如我发送某个关键字,返回对应的信息)。
token可以设置复杂点。
package com.blog.springboot.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.blog.springboot.wx.service.WxService;
import com.blog.springboot.wx.util.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/wx_public_api")
@Api(tags = { "微信公众号api" }, description = "微信公众号api")
public class WxPublicApiController extends AbstractController{
@Autowired
private WxService wxService;
/**
* 微信公众平台服务器配置验证
* @param request
* @param response
*/
@GetMapping
@ApiOperation("微信公众平台服务器配置验证")
public void validate(HttpServletRequest request, HttpServletResponse response) {
// 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
PrintWriter out = null;
try {
out = response.getWriter();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
} finally {
out.close();
out = null;
}
}
/**
* 关注推送消息
* @param request
* @param response
*/
@PostMapping
@ApiOperation("关注推送消息")
public void about(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
logger.error(e.getMessage(),e);
}
response.setContentType("text/html;charset=UTF-8");
// 调用核心业务类接收消息、处理消息
String respMessage = wxService.newMessageRequest(request);
// 响应消息
PrintWriter out = null;
try {
out = response.getWriter();
out.print(respMessage);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage(),e);
} finally {
out.close();
out = null;
}
}
}
Java的基本数据类型分为:1、整数类型,用来表示整数的数据类型。2、浮点类型,用来表示小数的数据类型。3、字符类型,字符类型的关键字是“char”。4、布尔类型,是表示逻辑值的基本数据类型。
关于如何使用Java开发微信公众号就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。