微信公众号一、接入微信并实现机器人自动回复功能_glm 微信云托管 公众号 微信机器人-程序员宅基地

技术标签: # 微信公众号/小程序  

一、说明

微信公众平台

https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN

测试平台

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

本文demo

链接:https://pan.baidu.com/s/1syGGvdCJqcSPnZdJZpMkTA 提取码:y8y5

开发建议使用测试平台,测试平台拥有所有接口权限
微信公众平台个人只能申请订阅号,而且很多接口没有权限,如菜单,网页录授权

二、外网映射工具ngrok

微信接入必须能外网访问,其项目端口必须为80,需要进行路由映射
内网穿透工具 ngrok使用: https://blog.csdn.net/qq_41463655/article/details/92846613

代码写好后启动本地服务,输入内网穿透工具的地址进行接入
在这里插入图片描述
我这里使用内网穿透工具是花生壳
在这里插入图片描述
微信公众平台在 设置-基本资料 设置服务器配置,启动就ok了,花生壳的域名应该被微信认为是非法连接了,一直提示参数错误,使用 ngrok 工具连接是没有问题的
在这里插入图片描述

三、环境搭建

1、创建springboot 项目

在这里插入图片描述

2、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-weixin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-weixin</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
        <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.11.1</version>
        </dependency>

        <!-- httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!-- json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3、XmlUtils

package com.example.springbootweixin.utils;

import com.example.springbootweixin.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class XmlUtils {
    
	/**
	 * 解析微信发来的请求(XML)
	 * 
	 * @param request
	 * @return Map<String, String>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
    
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();

		// 从request中取得输入流
		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();

		// 遍历所有子节点
		for (Element e : elementList)
			map.put(e.getName(), e.getText());

		// 释放资源
		inputStream.close();
		inputStream = null;

		return map;
	}

	/**
	 * 文本消息对象转换成xml
	 * 
	 * @param textMessage
	 *            文本消息对象
	 * @return xml
	 */
	public static String messageToXml(TextMessage textMessage) {
    
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}

	/**
	 * 扩展xstream使其支持CDATA
	 */
	private static XStream xstream = new XStream();
}

4、HttpClientUtil

package com.example.springbootweixin.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    

    public static String doGet(String url, Map<String, String> param) {
    
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
    
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
    
                for (String key : param.keySet()) {
    
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
    
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                if (response != null) {
    
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
    
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
    
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
    
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
    
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
    
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
    
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                response.close();
            } catch (IOException e) {
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPost(String url) {
    
        return doPost(url, null);
    }
    
    public static String doPostJson(String url, String json) {
    
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
    
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            try {
    
                response.close();
            } catch (IOException e) {
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

5、CheckUtil 验签

package com.example.springbootweixin.utils;

import java.security.MessageDigest;

import java.util.Arrays;

public class CheckUtil {
    

	public static final String tooken = "123456789"; // 开发者自行定义Tooken

	public static boolean checkSignature(String signature, String timestamp, String nonce) {
    
		// 1.定义数组存放tooken,timestamp,nonce
		String[] arr = {
     tooken, timestamp, nonce };
		// 2.对数组进行排序
		Arrays.sort(arr);
		// 3.生成字符串
		StringBuffer sb = new StringBuffer();
		for (String s : arr) {
    
			sb.append(s);
		}
		// 4.sha1加密,网上均有现成代码
		String temp = getSha1(sb.toString());
		// 5.将加密后的字符串,与微信传来的加密签名比较,返回结果
		return temp.equals(signature);

	}

	public static String getSha1(String str) {
    
		if (str == null || str.length() == 0) {
    
			return null;
		}
		char hexDigits[] = {
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
    

			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));
			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
    
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
    
			return null;
		}

	}

}

6、BaseMessage

package com.example.springbootweixin.entity;

import lombok.Data;

@Data
public class BaseMessage {
    

	/**
	 * 开发者微信
	 */
	private String ToUserName;
	/**
	 * 发送方openid
	 */
	private String FromUserName;
	/**
	 * 创建时间
	 */
	private long CreateTime;
	/**
	 * 内容类型
	 */
	private String MsgType;
//	/**
//	 * 消息id
//	 */
//	private long MsgId ;
}

7、TextMessage

package com.example.springbootweixin.entity;

import lombok.Data;

@Data
public class TextMessage  extends BaseMessage {
    

	 private String Content;
}

8、微信接入主类 DispatCherServlet

青云客智能聊天机器人API:http://api.qingyunke.com/

package com.example.springbootweixin.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootweixin.entity.TextMessage;
import com.example.springbootweixin.utils.CheckUtil;
import com.example.springbootweixin.utils.HttpClientUtil;
import com.example.springbootweixin.utils.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信事件通知
 */

@RestController
@Slf4j
public class DispatCherServlet {
    

    /**
     * 微信验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping(value = "/dispatCherServlet", method = RequestMethod.GET)
    public String getDispatCherServlet(String signature, String timestamp, String nonce, String echostr) {
    
        boolean checkSignature = CheckUtil.checkSignature(signature, timestamp, nonce);
        if (!checkSignature) {
    
            return null;
        }
        return echostr;
    }


    /**
     * 功能说明:微信事件通知(用户所有消息都会通过改接口接收)
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dispatCherServlet", method = RequestMethod.POST)
    public void postdispatCherServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map<String, String> mapResult = XmlUtils.parseXml(request);
        if (mapResult == null) {
    
            return;
        }
        String msgType = mapResult.get("MsgType");
        PrintWriter out = response.getWriter();
        if(msgType ==  "text") {
    
            //获取用户信息
            String content = mapResult.get("Content");
            String toUserName = mapResult.get("ToUserName");
            String fromUserName = mapResult.get("FromUserName");
            String textMessage = null;
            //判断回复
            if (content.equals("微信公众号")) {
    
                textMessage = setTextMessage("我是后台接口自动回复的哦", toUserName, fromUserName);
            } else {
    
                // 调用第三方智能接口(青云客智能聊天机器人API)
                String resultStr = HttpClientUtil.doGet("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + content);
                JSONObject jsonObject = new JSONObject().parseObject(resultStr);
                Integer integer = jsonObject.getInteger("result");
                if (integer == null || integer != 0) {
    
                    textMessage = setTextMessage("亲,系统出错啦!", toUserName, fromUserName);
                } else {
    
                    String result = jsonObject.getString("content");
                    textMessage = setTextMessage(result, toUserName, fromUserName);
                }
            }
            log.info("postdispatCherServlet() info:{}", textMessage);
            out.print(textMessage);
        }
        out.close();
    }




    // 回复消息封装
    public String setTextMessage(String content, String toUserName, String fromUserName) {
    
        TextMessage textMessage = new TextMessage();
        textMessage.setCreateTime(System.currentTimeMillis());
        textMessage.setFromUserName(toUserName);
        textMessage.setToUserName(fromUserName);
        textMessage.setContent(content);
        textMessage.setMsgType("text");
        String messageToXml = XmlUtils.messageToXml(textMessage);
        return messageToXml;
    }
}

9、启动配置好后测试效果如下

别忘了看第二步微信公众号接入当前本地项目
在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41463655/article/details/103777474

智能推荐

hive使用适用场景_大数据入门:Hive应用场景-程序员宅基地

文章浏览阅读5.8k次。在大数据的发展当中,大数据技术生态的组件,也在不断地拓展开来,而其中的Hive组件,作为Hadoop的数据仓库工具,可以实现对Hadoop集群当中的大规模数据进行相应的数据处理。今天我们的大数据入门分享,就主要来讲讲,Hive应用场景。关于Hive,首先需要明确的一点就是,Hive并非数据库,Hive所提供的数据存储、查询和分析功能,本质上来说,并非传统数据库所提供的存储、查询、分析功能。Hive..._hive应用场景

zblog采集-织梦全自动采集插件-织梦免费采集插件_zblog 网页采集插件-程序员宅基地

文章浏览阅读496次。Zblog是由Zblog开发团队开发的一款小巧而强大的基于Asp和PHP平台的开源程序,但是插件市场上的Zblog采集插件,没有一款能打的,要么就是没有SEO文章内容处理,要么就是功能单一。很少有适合SEO站长的Zblog采集。人们都知道Zblog采集接口都是对Zblog采集不熟悉的人做的,很多人采取模拟登陆的方法进行发布文章,也有很多人直接操作数据库发布文章,然而这些都或多或少的产生各种问题,发布速度慢、文章内容未经严格过滤,导致安全性问题、不能发Tag、不能自动创建分类等。但是使用Zblog采._zblog 网页采集插件

Flink学习四:提交Flink运行job_flink定时运行job-程序员宅基地

文章浏览阅读2.4k次,点赞2次,收藏2次。restUI页面提交1.1 添加上传jar包1.2 提交任务job1.3 查看提交的任务2. 命令行提交./flink-1.9.3/bin/flink run -c com.qu.wc.StreamWordCount -p 2 FlinkTutorial-1.0-SNAPSHOT.jar3. 命令行查看正在运行的job./flink-1.9.3/bin/flink list4. 命令行查看所有job./flink-1.9.3/bin/flink list --all._flink定时运行job

STM32-LED闪烁项目总结_嵌入式stm32闪烁led实验总结-程序员宅基地

文章浏览阅读1k次,点赞2次,收藏6次。这个项目是基于STM32的LED闪烁项目,主要目的是让学习者熟悉STM32的基本操作和编程方法。在这个项目中,我们将使用STM32作为控制器,通过对GPIO口的控制实现LED灯的闪烁。这个STM32 LED闪烁的项目是一个非常简单的入门项目,但它可以帮助学习者熟悉STM32的编程方法和GPIO口的使用。在这个项目中,我们通过对GPIO口的控制实现了LED灯的闪烁。LED闪烁是STM32入门课程的基础操作之一,它旨在教学生如何使用STM32开发板控制LED灯的闪烁。_嵌入式stm32闪烁led实验总结

Debezium安装部署和将服务托管到systemctl-程序员宅基地

文章浏览阅读63次。本文介绍了安装和部署Debezium的详细步骤,并演示了如何将Debezium服务托管到systemctl以进行方便的管理。本文将详细介绍如何安装和部署Debezium,并将其服务托管到systemctl。解压缩后,将得到一个名为"debezium"的目录,其中包含Debezium的二进制文件和其他必要的资源。注意替换"ExecStart"中的"/path/to/debezium"为实际的Debezium目录路径。接下来,需要下载Debezium的压缩包,并将其解压到所需的目录。

Android 控制屏幕唤醒常亮或熄灭_android实现拿起手机亮屏-程序员宅基地

文章浏览阅读4.4k次。需求:在诗词曲文项目中,诗词整篇朗读的时候,文章没有读完会因为屏幕熄灭停止朗读。要求:在文章没有朗读完毕之前屏幕常亮,读完以后屏幕常亮关闭;1.权限配置:设置电源管理的权限。

随便推点

目标检测简介-程序员宅基地

文章浏览阅读2.3k次。目标检测简介、评估标准、经典算法_目标检测

记SQL server安装后无法连接127.0.0.1解决方法_sqlserver 127 0 01 无法连接-程序员宅基地

文章浏览阅读6.3k次,点赞4次,收藏9次。实训时需要安装SQL server2008 R所以我上网上找了一个.exe 的安装包链接:https://pan.baidu.com/s/1_FkhB8XJy3Js_rFADhdtmA提取码:ztki注:解压后1.04G安装时Microsoft需下载.NET,更新安装后会自动安装如下:点击第一个傻瓜式安装,唯一注意的是在修改路径的时候如下不可修改:到安装实例的时候就可以修改啦数据..._sqlserver 127 0 01 无法连接

js 获取对象的所有key值,用来遍历_js 遍历对象的key-程序员宅基地

文章浏览阅读7.4k次。1. Object.keys(item); 获取到了key之后就可以遍历的时候直接使用这个进行遍历所有的key跟valuevar infoItem={ name:'xiaowu', age:'18',}//的出来的keys就是[name,age]var keys=Object.keys(infoItem);2. 通常用于以下实力中 <div *ngFor="let item of keys"> <div>{{item}}.._js 遍历对象的key

粒子群算法(PSO)求解路径规划_粒子群算法路径规划-程序员宅基地

文章浏览阅读2.2w次,点赞51次,收藏310次。粒子群算法求解路径规划路径规划问题描述    给定环境信息,如果该环境内有障碍物,寻求起始点到目标点的最短路径, 并且路径不能与障碍物相交,如图 1.1.1 所示。1.2 粒子群算法求解1.2.1 求解思路    粒子群优化算法(PSO),粒子群中的每一个粒子都代表一个问题的可能解, 通过粒子个体的简单行为,群体内的信息交互实现问题求解的智能性。    在路径规划中,我们将每一条路径规划为一个粒子,每个粒子群群有 n 个粒 子,即有 n 条路径,同时,每个粒子又有 m 个染色体,即中间过渡点的_粒子群算法路径规划

量化评价:稳健的业绩评价指标_rar 海龟-程序员宅基地

文章浏览阅读353次。所谓稳健的评估指标,是指在评估的过程中数据的轻微变化并不会显著的影响一个统计指标。而不稳健的评估指标则相反,在对交易系统进行回测时,参数值的轻微变化会带来不稳健指标的大幅变化。对于不稳健的评估指标,任何对数据有影响的因素都会对测试结果产生过大的影响,这很容易导致数据过拟合。_rar 海龟

IAP在ARM Cortex-M3微控制器实现原理_value line devices connectivity line devices-程序员宅基地

文章浏览阅读607次,点赞2次,收藏7次。–基于STM32F103ZET6的UART通讯实现一、什么是IAP,为什么要IAPIAP即为In Application Programming(在应用中编程),一般情况下,以STM32F10x系列芯片为主控制器的设备在出厂时就已经使用J-Link仿真器将应用代码烧录了,如果在设备使用过程中需要进行应用代码的更换、升级等操作的话,则可能需要将设备返回原厂并拆解出来再使用J-Link重新烧录代码,这就增加了很多不必要的麻烦。站在用户的角度来说,就是能让用户自己来更换设备里边的代码程序而厂家这边只需要提供给_value line devices connectivity line devices