微信公众号接入java

微信公众号接入与消息处理

内网穿透工具

https://www.ngrok.cc/user.html 收费。。

1.微信公众号接入服务器

1.1申请微信公众号测试号
公众号首页—设置与开发—基本配置

@GetMapping("/wx")
	public void tokenVerify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		
		boolean isVerify = SignUtil.checkSignature(signature, timestamp, nonce);

		if (!isVerify) {
			log.error("消息不是来自微信服务器!");
		} else {
			response.getOutputStream().println(echostr);
		}

	}

SignUtil接口

public class SignUtil {
	
	 private static String token = "weixin";

	    public static boolean checkSignature(String signature, String timestamp, String nonce) {
	        boolean result = false;

	        // 对token、timestamp和nonce按字典序排序
	        String[] array = new String[]{token, timestamp, nonce};
	        Arrays.sort(array);

	        // 将三个参数字符拼接成一个字符串
	        String str = array[0].concat(array[1]).concat(array[2]);

	        String sha1Str = null;
	        try {
	            // 对拼接后的字符串进行sha1加密
	            MessageDigest md = MessageDigest.getInstance("SHA-1");
	            byte[] digest = md.digest(str.getBytes());
	            sha1Str = byte2str(digest);
	        }
	        catch(Exception e) {
	        }

	        System.out.println(sha1Str);
	        if(sha1Str != null &&  sha1Str.equals(signature)) {
	            result = true;
	        }

	        return result;
	    }

	    /*
	     * 将字节数组转换成字符串
	     */
	    public static String byte2str(byte[] array) {
	        StringBuffer hexstr = new StringBuffer();
	        String shaHex="";
	        for(int i = 0; i < array.length; i++) {
	            shaHex = Integer.toHexString(array[i] & 0xFF);
	            if(shaHex.length() < 2) {
	                hexstr.append(0);
	            }
	            hexstr.append(shaHex);
	        }
	        return hexstr.toString();
	    }

}

Token必须跟代码里面一致,可加入配置文件
提交发送请求,请求成功

在这里插入图片描述

2.接收消息_返回消息

接受消息也需要封装,改为安全模式

/**
	 * 微信消息处理
	 * 
	 * @throws IOException
	 */
	@PostMapping("/tokenVerify")
	public void getMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {

		request.setCharacterEncoding("utf8");
		response.setCharacterEncoding("utf8");

		Map<String, String> map = XmlUtils.xmlAnalysis(request.getInputStream());

		String openId = map.get("FromUserName");
		String msgType = map.get("MsgType");

		String Conten = topicService.topicList();
		if ("event".equals(msgType)) {

			String Event = map.get("Event");
			if ("subscribe".equals(Event)) {

			} else if ("unsubscribe".equals(Event)) {
				
			}

		} else if ("text".equals(msgType)) {

			String Content = map.get("Content");

			if ("订阅".equals(Content)) {
				// Conten = topicService.topicList();
			} else if (CommonUtils.isNumeric(Content)) {
				
			}

		} else {

		}

		String xml = "<xml><ToUserName><![CDATA[" + map.get("FromUserName") + "]]></ToUserName><FromUserName><![CDATA["
				+ map.get("ToUserName") + "]]></FromUserName><CreateTime>" + System.currentTimeMillis() / 1000
				+ "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + Conten + "]]></Content><MsgId>"
				+ map.get("MsgId") + "</MsgId></xml>";

		PrintWriter out = response.getWriter();
		out.print(xml);
		out.flush();
		out.close();
	}

XmlUtils.xmlAnalysis方法

public static  Map<String,String> xmlAnalysis(InputStream is){
		
		//用户发过来的是什么消息
		SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        Map<String,String> map = new HashMap<>();
        for(Element e:elements){
            map.put(e.getName(), e.getStringValue());
        }
        
        return map;
		
	}

3.获取access_token

需要后期加入缓存

public static String REQURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
	// 微信公众号
	private static final String APPID = "";
	private static final String APPSECRET = "";

	public static String getToken() throws IOException {

		String url = REQURL.replace("APPID", APPID);
		url = url.replace("SECRET", APPSECRET);

		String respJson = OkHttpUtils.runGet(url);

		JSONObject respJsonObj = JSONObject.parseObject(respJson);
		System.out.println(respJsonObj.getString("access_token"));
		return respJsonObj.getString("access_token");
	}
### DeepSeek Java SDK 接入微信公众号指南 #### 一、环境准备 为了成功集成DeepSeek到微信公众号,需确保开发环境中已安装并配置Java运行环境以及Maven构建工具。此外,还需获取来自微信公众平台的应用凭证(AppID 和 AppSecret),这些参数用于后续接口调用的身份验证[^1]。 #### 二、引入依赖项 通过Maven项目管理器,在`pom.xml`文件内添加如下所示的依赖声明来导入所需的库: ```xml <dependency> <groupId>com.deepseek</groupId> <artifactId>deepseek-java-sdk</artifactId> <version>x.x.x</version><!-- 版本号请参照官方最新发布 --> </dependency> <!-- 微信公众平台SDK --> <dependency> <groupId>me.chanjar</groupId> <artifactId>wx-java-mp-spring-boot-starter</artifactId> <version>y.y.y</version><!-- 版本号同样需要依据实际情况调整 --> </dependency> ``` 上述代码片段展示了如何利用Maven仓库中的资源快速搭建起支持DeepSeek功能的基础架构,并集成了处理微信消息收发的能力[^2]。 #### 三、初始化客户端实例 创建一个新的类作为入口点,负责建立与两个服务端口之间的连接。在此过程中要特别注意设置正确的API地址和其他必要的选项参数。 ```java import com.deepseek.client.DeepSeekClient; import me.chanjar.weixin.mp.api.WxMpService; public class WeChatIntegration { private final WxMpService wxMpService; // 微信公众号服务对象 public static void main(String[] args){ // 初始化DeepSeek Client DeepSeekClient deepSeekClient = new DeepSeekClient.Builder() .setApiKey("your_api_key_here")// 设置API密钥 .build(); // 配置Wx Mp Service... this.wxMpService = ... } } ``` 这段程序示范了怎样分别构造出能够访问各自系统的客户代理实体,从而为进一步实现自动化交互打下基础[^3]。 #### 四、事件监听机制设计 针对不同类型的消息推送(如文本、图片等),可以定义相应的处理器方法来进行针对性响应;而对于订阅/取消关注这类特定场景,则可通过覆盖默认行为的方式自定义逻辑流程。 ```java @EventHandler public void onTextMessage(WxMpXmlMessage message, WxMpMessageHandlerChain chain) throws Exception{ String content = message.getContent(); // 调用DeepSeek API分析收到的内容... } @Override protected void onSubscribeEvent(WxMpUserSubscribeEvent event){ super.onSubscribeEvent(event); // 用户首次关注时触发的操作... } ``` 以上示例体现了基于Spring框架下的AOP特性所实现的一种灵活的消息路由方案,使得开发者可以根据实际需求轻松扩展业务规则[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值