search
HomeBackend DevelopmentPHP TutorialPHP implementation example of remote control server function using WeChat

WeChat development has been very popular recently. This article mainly shares with you examples of PH implementation of remote control server functions using WeChat. The general functions are still there, but they are not complete. I have not dealt with many places. But for communication in plain text, there is no problem.

PHP implementation example of remote control server function using WeChat

PHP implementation example of remote control server function using WeChat

Environment Construction

Let’s briefly talk about the principles of WeChat public accounts. Maybe my understanding is not in place. If there is something wrong, I welcome criticism and advice.

The client sends a request to the WeChat platform, and the WeChat platform forwards the request to the private server. After being handed over to the program for processing, the processing results of the private server are obtained and then fed back to the client.

Of course, the “WeChat Public Platform” plays a core role in this. It is equivalent to providing a stage, a platform that allows talented people and strangers to show their own characteristics. In fact, this is not only true for WeChat, but also for Alibaba, so that major e-commerce companies can show their talents.

Open configuration

The first step is to apply for a WeChat developer account. For individuals, it is enough to choose a subscription account. There is a lot of relevant information on the Internet and it is very detailed, so I won’t go into details. Let’s get straight to the point.

After successfully logging in to the developer account, you can open the server-side settings, as shown below

PHP implementation example of remote control server function using WeChat

The activation is completed, and you can set it according to the situation of your own server. Can.

  • URL is the address used by your private server to process request data

  • TOKEN is a token, set it casually. But remember that you will use it in your own code later.

  • As for the key, it has no major use, so you can leave it alone for now.

PHP implementation example of remote control server function using WeChat

Setting on demand

After setting, you can enable it. This is like having all the wires in your home renovated and now you want to use them and press the switch. As shown below

PHP implementation example of remote control server function using WeChat

Enable server configuration

Server environment

Regarding the server, the official website explains it in detail.

https://mp.weixin.qq.com/wiki

We can also download the official demo to simulate.

PHP implementation example of remote control server function using WeChat

Official sample

The code is also very simple. Basically, anyone who has learned the basic syntax of PHP can understand it.

<?php /**
 * wechat php test
 */
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
 public function valid()
 {
 $echoStr = $_GET["echostr"];
 //valid signature , option
 if($this->checkSignature()){
 echo $echoStr;
 exit;
 }
 }
 public function responseMsg()
 {
 //get post data, May be due to the different environments
 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
 //extract post data
 if (!empty($postStr)){
 /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
  the best way is to check the validity of xml by yourself */
 libxml_disable_entity_loader(true);
 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
 $fromUsername = $postObj->FromUserName;
 $toUsername = $postObj->ToUserName;
 $keyword = trim($postObj->Content);
 $time = time();
 $textTpl = "<xml>
  <tousername></tousername>
  <fromusername></fromusername>
  <createtime>%s</createtime>
  <msgtype></msgtype>
  <content></content>
  <funcflag>0</funcflag>
  </xml>"; 
 if(!empty( $keyword ))
 {
  $msgType = "text";
  $contentStr = "Welcome to wechat world!";
  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  echo $resultStr;
 }else{
  echo "Input something...";
 }
 }else {
 echo "";
 exit;
 }
 }
 private function checkSignature()
 {
 // you must define TOKEN by yourself
 if (!defined("TOKEN")) {
 throw new Exception('TOKEN is not defined!');
 }
 $signature = $_GET["signature"];
 $timestamp = $_GET["timestamp"];
 $nonce = $_GET["nonce"];
 $token = TOKEN;
 $tmpArr = array($token, $timestamp, $nonce);
 // use SORT_STRING rule
 sort($tmpArr, SORT_STRING);
 $tmpStr = implode( $tmpArr );
 $tmpStr = sha1( $tmpStr );
 if( $tmpStr == $signature ){
 return true;
 }else{
 return false;
 }
 }
}
?>

The core idea is nothing more than checking the signature, processing the request, and feeding back the results.

What I have to say here is that I think Tencent can actually remove those templates and directly expose the black box mode. In this case, the security will be higher. In many cases, the more open the permissions are, the worse the effect may be.

Core Class

The next step is my own processing logic, please refer to the official documentation. WeChat public has 6 receiving interfaces and three replying interfaces. It can be determined based on MsgType.

Interface details

Verification

private function checkSignature() {
 // you must define TOKEN by yourself
 if (! defined ( "TOKEN" )) {
 throw new Exception ( 'TOKEN is not defined!' );
 }
 $signature = $_GET ["signature"];
 $timestamp = $_GET ["timestamp"];
 $nonce = $_GET ["nonce"];
 $token = TOKEN;
 $tmpArr = array (
 $token,
 $timestamp,
 $nonce 
 );
 // use SORT_STRING rule
 sort ( $tmpArr, SORT_STRING );
 $tmpStr = implode ( $tmpArr );
 $tmpStr = sha1 ( $tmpStr );
 if ($tmpStr == $signature) {
 return true;
 } else {
 return false;
 }
 }

The core of the verification method works based on the TOKEN we set on the previous web page, so it will be used in the code.

Reply

The reply code needs to be treated differently according to the type of data sent by the client. The WeChat platform will package the data and encapsulate it. We need to call the internal MsgType. Just process it.

Expansion

The expansion part was added on my own whim.

Add a robot

Call a robot interface to send replies on your behalf. This skill allows users to have a good user experience and can also please the public. Why not?

I tested two interfaces here, one is curl mode and the other is file_get_contents mode, both of them are very easy to use.

<?php /**
 * 图灵 机器人接口
 * 
 * 使用curl来进行浏览器模拟并抓取数据
 */
function turing($requestStr) {
 // 图灵机器人接口
 $url = "http://www.tuling123.com/openapi/api";
 // 用于POST请求的数据
 $data = array(
 &#39;key&#39;=>"哈哈,这个key还是得你自己去申请的啦",
 'info'=>$requestStr,
 );
 // 构造curl下载器
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 $responseStr = curl_exec($ch);
 curl_close($ch);
 return $responseStr;
}
/**
 * 调用另外的接口
 * @param unknown $req
 * @return mixed
 */
function test($req){
 $url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=".$req;
 $result = file_get_contents($url);
 $result = json_decode($result, true);
 return $result['content'];
}
$req = 'hello';
$res = test($req);
echo $res;

Command Mode

One of the great advantages of mobile phones over computers is their portability. Although we cannot carry computers anytime and anywhere, we can use mobile phones instead. Many times the commands required to manage the server are very simple, but it is inconvenient to log in remotely. It’s also a good idea to use WeChat to help spread the word at this time.

I usually like to use Python to write some scripts, such as getting local IP, chatting, checking memory, network speed, etc. It can be said that it has everything. This time it finally comes into play. By using WeChat's keyword matching, you can simply let the WeChat public account act as a small messenger.

Here is an idea, the specific implementation is relatively simple, just treat it as text.

Complete code

The complete code on my server is posted below. I have made some changes in some private parts. You can modify it according to your own situation.

valid();
// 调用回复信息方法
$wechatObj->responseMsg ();
// 微信消息处理核心类
class wechatCallbackapiTest {
 public function valid() {
 $echoStr = $_GET ["echostr"];
 // valid signature , option
 if ($this->checkSignature ()) {
 echo $echoStr;
 exit ();
 } else {
 echo "验证失败!";
 }
 }
 public function responseMsg() {
 // get post data, May be due to the different environments
 // 类似$_POST但是可以接受XML数据,属于增强型
 $postStr = $GLOBALS ["HTTP_RAW_POST_DATA"];
 // extract post data
 if (! empty ( $postStr )) {
 /*
 * libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
 * the best way is to check the validity of xml by yourself
 */
 // 不解析外部数据,防止xxml漏洞
 libxml_disable_entity_loader ( true );
 $postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
 $fromUsername = $postObj->FromUserName;
 $toUsername = $postObj->ToUserName;
 $keyword = trim ( $postObj->Content );
 $time = time ();
 /*
 * 微信客户端发送信息的时候会附带一些参数,详见官方文档。所以要根据不同的类型,来分别做相关的处理。
 * 于是MsgType 就充当这样的一个区分的标记
 */
 $msgType = $postObj->MsgType;
 /*
 * 当有用户关注后者退订的时候,会触发相应的事件。所以再来个event事件的监听更为友好。
 * $event = $postObj->Event.
 * 具体的参数信息,官网上很详细。
 */
 $event = $postObj->Event;
 switch ($msgType) {
 // 文本消息 处理部分
 case "text" :
  if (! empty ( $keyword )) {
  // 在此处进行对关键字的匹配就可以实现:针对不同关键字组装的相应数据
  if($keyword=='PHP implementation example of remote control server function using WeChat' || $keyword == "music") {
  $msgType = 'music';
  $musictitle = "The Mountain";
  $musicdescription = "夏日舒心清凉歌曲";
  $musicurl = "http://101.200.58.242/wx/themaintain.mp3";
  $hqmusicurl = "http://101.200.58.242/wx/themaintain.mp3";
  musicMessageHandle($fromUsername, $toUsername, $time, $msgType, $musictitle, $musicdescription, $musicurl, $hqmusicurl);
  }elseif($keyword == '1'){
  $msgType = 'text';
  $contentStr = "人生得意须尽欢,莫使金樽空对月!";
  textMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr);
  }elseif($keyword == 'PHP implementation example of remote control server function using WeChat模式'){
  $msgType = 'text';
  $contentStr = "进入PHP implementation example of remote control server function using WeChat模式,开始对服务器进行管理!\n接下来将依据您输入的PHP implementation example of remote control server function using WeChat对服务器进行管理!";
  textMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr);
  }else {
  // 直接调用 机器人接口,与用户进行交流
  $msgType = "text";
  $contentStr = turing($keyword)!=""?turing($keyword):"这里是微信 纯文本测试数据!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  }
  } else {
  echo "您得输入点数据,我才能回复不是!";
  }
  break;
 // 接收图片信息
 case "image" :
  if (! empty ( $keyword )) {
//  $msgType = "image";
  $contentStr = "您发送的图片看起来还真不错!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的图片!";
  }
  break;
 // 接收语音信息
 case "voice" :
  if (! empty ( $keyword )) {
//  $msgType = "voice";
  $contentStr = "您发送的语音听起来还真不错!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的语音!";
  }
  break;
 // 接收视频信息
 case "video" :
  if (! empty ( $keyword )) {
//  $msgType = "video";
  $contentStr = "您发送的视频看起来还真不错!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的视频!";
  }
  break;
 // 接收视频信息
 case "shortvideo" :
  if (! empty ( $keyword )) {
//  $msgType = "shortvideo";
  $contentStr = "您发送的小视频看起来还真不错!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的小视频!";
  }
  break;
 // 接收位置信息
 case "location" :
  if (! empty ( $keyword )) {
//  $msgType = "location";
  $contentStr = "您发送的位置已被接收!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的位置!";
  }
  break;
 // 接收视频信息
 case "link" :
  if (! empty ( $keyword )) {
//  $msgType = "link";
  $contentStr = "您发送的链接看起来还真不错!";
  textMessageHandle ( $fromUsername, $toUsername, $time, $msgType, $contentStr );
  } else {
  echo "服务器没能收到您发送的链接!";
  }
  break;
 // 对事件进行侦听
 case "event":
  switch ($event) {
  case "subscribe":
  // 发送一些消息!
  $msgType = 'text';
  $contentStr = "终于等到你!";
  textMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr);
  break;
  }
  break;
 default :
  break;
 }
 } else {
 echo "";
 exit ();
 }
 }
 private function checkSignature() {
 // you must define TOKEN by yourself
 if (! defined ( "TOKEN" )) {
 throw new Exception ( 'TOKEN is not defined!' );
 }
 $signature = $_GET ["signature"];
 $timestamp = $_GET ["timestamp"];
 $nonce = $_GET ["nonce"];
 $token = TOKEN;
 $tmpArr = array (
 $token,
 $timestamp,
 $nonce 
 );
 // use SORT_STRING rule
 sort ( $tmpArr, SORT_STRING );
 $tmpStr = implode ( $tmpArr );
 $tmpStr = sha1 ( $tmpStr );
 if ($tmpStr == $signature) {
 return true;
 } else {
 return false;
 }
 }
}
/**
 * 定义为心中想难关的六个接口的数据发送格式模板
 */
function textMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr) {
 $textTpl = "
  
  
  %s
  
  
  0
 ";
 $resultStr = sprintf ( $textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr );
 echo $resultStr;
}
function imageMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr) {
 $imageTpl = "
  
  
  %s
  
  
  
  
  1234567890123456
  ";
 $resultStr = sprintf ( $textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr );
 echo $resultStr;
}
function musicMessageHandle($fromUsername, $toUsername, $time, $msgType, $musictitle, $musicDescription, $musicurl, $hqmusicurl) {
 $musicTpl = "
  
  
  %s
  
  
  
  
  
  
  
 ";
 $resultStr = sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType, $musictitle, $musicDescription, $musicurl, $hqmusicurl);
 echo $resultStr;
}
/**
 * 图灵 机器人接口
 * 
 * 使用curl来进行浏览器模拟并抓取数据
 */
function turing($requestStr) {
 /* // 图灵机器人接口
 $url = "http://www.tuling123.com/openapi/api";
 // 用于POST请求的数据
 $data = array(
 "key"=>"您在图灵机器人官网上申请的key",
 "info"=>$requestStr
 );
 // 构造curl下载器
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 $requestStr = curl_exec($ch);
 curl_close($ch);
 return responseStr; */
 $url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=".$requestStr;
 $result = file_get_contents($url);
 $result = json_decode($result, true);
 return $result['content'];
}
?>

Summary

Finally, let’s review what knowledge points were used in this experiment.

  • PHP’s object-oriented programming is simple to implement.

  • Two ways of interface processing

  • Access, processing, and feedback to the backend private server of the WeChat public account.

  • Interaction between front and back ends, and application of chat robots.

Actually, these codes are quite different from what I originally imagined. Originally, I wanted to implement a "remote control". Before going to bed at night, I would use WeChat to send a command "Open "Electric blanket". After half an hour, I finished watching TV. When I went to bed, I found that the bed was very warm. Yes, as long as some hardware is added, this is easy to achieve. Moreover, it can be completed with a refrigerator and TV. In that case, it is estimated that you will need to see a doctor. It's called "smart home".

Related recommendations:

PHP implementation of temporary conversion of WeChat recordings to permanent storage example sharing

Summary of problems encountered in the development of WeChat mini programs

js sharing examples on WeChat, Weibo, QQ, and Huo App

The above is the detailed content of PHP implementation example of remote control server function using WeChat. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在 RHEL 9 上配置 DHCP 服务器如何在 RHEL 9 上配置 DHCP 服务器Jun 08, 2023 pm 07:02 PM

DHCP是“动态主机配置协议DynamicHostConfigurationProtocol”的首字母缩写词,它是一种网络协议,可自动为计算机网络中的客户端系统分配IP地址。它从DHCP池或在其配置中指定的IP地址范围分配客户端。虽然你可以手动为客户端系统分配静态IP,但DHCP服务器简化了这一过程,并为网络上的客户端系统动态分配IP地址。在本文中,我们将演示如何在RHEL9/RockyLinux9上安装和配置DHCP服务器。先决条件预装RHEL9或RockyLinux9具有sudo管理权限的普

在容器中怎么使用nginx搭建上传下载的文件服务器在容器中怎么使用nginx搭建上传下载的文件服务器May 15, 2023 pm 11:49 PM

一、安装nginx容器为了让nginx支持文件上传,需要下载并运行带有nginx-upload-module模块的容器:sudopodmanpulldocker.io/dimka2014/nginx-upload-with-progress-modules:latestsudopodman-d--namenginx-p83:80docker.io/dimka2014/nginx-upload-with-progress-modules该容器同时带有nginx-upload-module模块和ng

vue3项目打包发布到服务器后访问页面显示空白怎么解决vue3项目打包发布到服务器后访问页面显示空白怎么解决May 17, 2023 am 08:19 AM

vue3项目打包发布到服务器后访问页面显示空白1、处理vue.config.js文件中的publicPath处理如下:const{defineConfig}=require(&#39;@vue/cli-service&#39;)module.exports=defineConfig({publicPath:process.env.NODE_ENV===&#39;production&#39;?&#39;./&#39;:&#39;/&

服务器怎么使用Nginx部署Springboot项目服务器怎么使用Nginx部署Springboot项目May 14, 2023 pm 01:55 PM

1,将java项目打成jar包这里我用到的是maven工具这里有两个项目,打包完成后一个为demo.jar,另一个为jst.jar2.准备工具1.服务器2.域名(注:经过备案)3.xshell用于连接服务器4.winscp(注:视图工具,用于传输jar)3.将jar包传入服务器直接拖动即可3.使用xshell运行jar包注:(服务器的java环境以及maven环境,各位请自行配置,这里不做描述。)cd到jar包路径下执行:nohupjava-jardemo.jar>temp.txt&

python中怎么使用TCP实现对话客户端和服务器python中怎么使用TCP实现对话客户端和服务器May 17, 2023 pm 03:40 PM

TCP客户端一个使用TCP协议实现可连续对话的客户端示例代码:importsocket#客户端配置HOST=&#39;localhost&#39;PORT=12345#创建TCP套接字并连接服务器client_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)client_socket.connect((HOST,PORT))whileTrue:#获取用户输入message=input("请输入要发送的消息:&

Linux怎么在两个服务器直接传文件Linux怎么在两个服务器直接传文件May 14, 2023 am 09:46 AM

scp是securecopy的简写,是linux系统下基于ssh登陆进行安全的远程文件拷贝命令。scp是加密的,rcp是不加密的,scp是rcp的加强版。因为scp传输是加密的,可能会稍微影响一下速度。另外,scp还非常不占资源,不会提高多少系统负荷,在这一点上,rsync就远远不及它了。虽然rsync比scp会快一点,但当小文件众多的情况下,rsync会导致硬盘I/O非常高,而scp基本不影响系统正常使用。场景:假设我现在有两台服务器(这里的公网ip和内网ip相互传都可以,当然用内网ip相互传

如何使用psutil模块获取服务器的CPU、内存和磁盘使用率?如何使用psutil模块获取服务器的CPU、内存和磁盘使用率?May 07, 2023 pm 10:28 PM

psutil是一个跨平台的Python库,它允许你获取有关系统进程和系统资源使用情况的信息。它支持Windows、Linux、OSX、FreeBSD、OpenBSD和NetBSD等操作系统,并提供了一些非常有用的功能,如:获取系统CPU使用率、内存使用率、磁盘使用率等信息。获取进程列表、进程状态、进程CPU使用率、进程内存使用率、进程IO信息等。杀死进程、发送信号给进程、挂起进程、恢复进程等操作。使用psutil,可以很方便地监控系统的运行状况,诊断问题和优化性能。以下是一个简单的示例,演示如何

怎么在同一台服务器上安装多个MySQL怎么在同一台服务器上安装多个MySQLMay 29, 2023 pm 12:10 PM

一、安装前的准备工作在进行MySQL多实例的安装前,需要进行以下准备工作:准备多个MySQL的安装包,可以从MySQL官网下载适合自己环境的版本进行下载:https://dev.mysql.com/downloads/准备多个MySQL数据目录,可以通过创建不同的目录来支持不同的MySQL实例,例如:/data/mysql1、/data/mysql2等。针对每个MySQL实例,配置一个独立的MySQL用户,该用户拥有对应的MySQL安装路径和数据目录的权限。二、基于二进制包安装多个MySQL实例

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!