微信公众号一、接入微信并实现机器人自动回复功能_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

智能推荐

PHP-生成缩略图和添加水印图-学习笔记-程序员宅基地

文章浏览阅读82次。1.开始 在网站上传图片过程,经常用到缩略图功能。这里我自己写了一个图片处理的Image类,能生成缩略图,并且可以添加水印图。2.如何生成缩略图 生成缩略图,关键的是如何计算缩放比率。 这里,我根据图片等比缩放,宽高的几种常见变化,得出一个算缩放比率算法是,使用新图(即缩略图)的宽高,分别除以原图的宽高,看哪个值大,就取它作为缩放比率:...

dyld: Library not loaded: @rpath/libswiftCore.dylib ... Reason: image not found 解决-程序员宅基地

文章浏览阅读2.7k次。在室友Xcode继承一些framework时,爆出了如下错误:dyld: Library not loaded: @rpath/libswiftCore.dylib Referenced from: /private/var/containers/Bundle/Application/1761A6FE-9D6B-45F7-9F9F-922C94BF54A3/demo.app/Framewor..._library not loaded: @rpath/libswiftcore.dylib

linux gvim 快捷键tab,Linux中Vim的常用命令及快捷键-程序员宅基地

文章浏览阅读356次。光标控制命令h或^h向左移一个字符j或^j或^n向下移一行k或^p向上移一行l或空格向右移一个字符G移到文件的最后一行nG移到文件的第n行w..._gvim itab

umi4 项目使用umi-plugin-keep-alive缓存页面(react-activation)-程序员宅基地

文章浏览阅读1k次,点赞12次,收藏10次。按 name 卸载缓存状态下的 节点,name 可选类型为 String 或 RegExp,注意,仅卸载命中 的第一层内容,不会卸载 中嵌套的、未命中的。按 name 刷新缓存状态下的 节点,name 可选类型为 String 或 RegExp,注意,仅刷新命中 的第一层内容,不会刷新 中嵌套的、未命中的。按 name 卸载缓存状态下的 节点,name 可选类型为 String 或 RegExp,将卸载命中 的所有内容,包括 中嵌套的所有。true: 卸载时缓存。获取所有缓存中的节点。_umi-plugin-keep-alive

memory compiler使用流程-程序员宅基地

文章浏览阅读3k次,点赞2次,收藏25次。用了几天的memory compiler,搞清楚了它的使用流程。因为这个软件是不开源的,而且手册又很长,没有快速阅读指南,所以就花了挺多时间学习手册细节,想把其中比较主要的流程记录下来,供大家学习参考。它是一个用来综合一些IP核的软件,它里面各种各样的memory compiler,可以根据自己的选择选中一个,设置好参数之后就能生成想要的参数的memory。 因为每个memory compiler可能工艺不一样,端口数不一样,所以里面有手册告诉你这些细节的。(手册很多,每个手册几百页上下)1、首先就是要安装_memory compiler

Android 读取csv格式数据文件-程序员宅基地

文章浏览阅读5.6k次,点赞5次,收藏16次。前言什么是csv文件呢?百度百科上说 CSV是逗号分隔值文件格式,也有说是电子表格的,既然是电子表格,那么就可以用Excel打开,那为什么要在Android中来读取这个.csv格式的文件呢?因为现在主流数据格式是采用的JSON,但是另一种就是.csv格式的数据,这种数据通常由数据库直接提供,进行读取。下面来看看简单的使用吧正文首先还是先来创建一个项目,名为ReadCSV准备.csv格式的文件,点击和风APILocationList下载ZIP,保存到本地,然后解压,这个时候在你的项目文件中新建_android 读取csv

随便推点

【故障诊断】BP神经网络电机数据特征提取与故障诊断【含Matlab源码 2569期】_故障特征量为无编码比值的bp神经网络-程序员宅基地

文章浏览阅读402次。BP神经网络电机数据特征提取与故障诊断完整的代码,方可运行;可提供运行操作视频!适合小白!_故障特征量为无编码比值的bp神经网络

BIOS、Legacy BIOS和UEFI BIOS:你需要知道的一切-程序员宅基地

文章浏览阅读1.1k次。BIOS 是计算机历史上的一个重要组成部分。这个术语最早是在 20 世纪 70 年代作为 Gary Kildall 开发的 CP/M(微型计算机控制程序)操作系统的一部分使用的。但 BIOS 至今仍在使用。然而,成功的技术现在越来越多地用于现代计算机。Legacy BIOS 和 UEFI BIOSBIOS 的含义是什么?该术语是 Basic Input/Output System(基本输入/输出系统)的首字母缩写,它描述的是作为非易失性存储器储存在计算机主板上的固件。_legacy bios

GitLab集成gitlab-runner_gitlab-runner 16.1.2-程序员宅基地

文章浏览阅读2k次。​GitLab Runner是一个开源项目,用于运行您的作业并将结果发送回GitLab。它与GitLab CI结合使用,GitLab CI是GitLab随附的用于协调作业的开源持续集成服务。​。_gitlab-runner 16.1.2

缓存数据库的意义、作用与种类详解-程序员宅基地

文章浏览阅读449次,点赞7次,收藏7次。Redis、Memcached等常见的缓存数据库,以及它们各自的特点和优势,使得开发人员可以根据应用场景选择最适合的解决方案。通过合理地配置和使用缓存数据库,可以有效地改善应用程序的性能,降低数据库负载,为用户提供更流畅的体验。缓存数据库允许应用程序在需要数据时,首先从缓存中查询数据,如果数据存在,则可以避免直接访问主数据库,从而显著提高数据访问速度。主数据库通常面临大量读写请求,而缓存数据库可以分担部分读请求,减轻主数据库的负载,提高其稳定性和可靠性。缓存数据库可以作为主数据库的备份,以防止数据丢失。

手把手教你安装VSCode(附带图解步骤)_vscode安装包-程序员宅基地

文章浏览阅读3.3w次,点赞38次,收藏158次。前端开发是创建Web页面或app等前端界面呈现给用户的过程,通过HTML,CSS及JavaScript以及衍生出来的各种技术、框架、解决方案,来实现互联网产品的用户界面交互[1]。它从网页制作演变而来,名称上有很明显的时代特征。在互联网的演化进程中,网页制作是Web1.0时代的产物,,用户使用网站的行为也以浏览为主。随着互联网技术的发展和HTML5、CSS3的应用,现代网页更加美观,交互效果显著,功能更加强大。[2]..._vscode安装包

Linux下jar包的运行、查看、终止_linux查看jar包是否运行-程序员宅基地

Linux下使用java -jar命令运行jar包,可通过ctrl + c或关闭窗口停止程序。可以使用pid文件记录jar包的运行进程,方便终止。通过编写启停脚本,可以方便地终止jar包的运行。