


Detailed explanation of steps to develop WeChat remote control server with PHP
This time I will bring you a detailed explanation of the steps to develop a WeChat remote control server with PHP. What are the precautions for PHP to develop a WeChat remote control server? The following is a practical case, let's take a look.
Summary
WeChat public good development is very popular, and mini programs are even more popular. So I joined in the fun and gave it a try.
The general functions are still there, but they are incomplete and I have not dealt with many places. But for communication in plain text, there is no problem.
##Environment setup
Let’s talk about WeChat in general The principle of the public account. 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 central 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- 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.
Server environment
About the server , the official website also explains it in detail. https://mp.weixin.qq.com/wikiWe can also download the official demo to simulate.PHP basic syntax 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; } } } ?>
Core Class
The next step is my own processing logic, refer to the official documentation. WeChat public has 6 receiving interfaces and three replying interfaces. It can be determined based on MsgType. Interface detailsVerification
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; } }
验证方法核心就是依据咱们之前网页上设置的TOKEN来工作的,所以代码上会用得到。
回复
回复的代码需要依据客户端发送的数据的类型来区分对待,类型这块微信平台会将数据打包好封装起来,我们住需要调用内部的MsgType进行处理即可。
拓展
拓展部分,是我自己异想天开往上加的。
添加机器人
调用一个机器人接口,来代替自己发送回复,技能让用户得到一个良好的用户体验,还能愉悦大众,何乐而不为?
我这边测试了两个接口,一个是curl模式,一个是file_get_contents模式,都挺好用的啦。
<?php /** * 图灵 机器人接口 * * 使用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); $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;
Detailed explanation of steps to develop WeChat remote control server with PHP模式
手机相对于电脑一个很大的优点就是便携,我们虽然不能随时随地携带电脑,但是却能使用手机来代替。很多时候对服务器的管理需要的Detailed explanation of steps to develop WeChat remote control server with PHP很简单,但是远程登录的时候也不方便。这个时候就用微信来帮忙传话也是不错的啦。
我平时喜欢使用Python写一些脚本,什么获取本地IP,聊天,查看内存,网速啥的,可谓是应有尽有。这下也终于能有用武之地了。利用微信的关键字匹配,就可以简单的让微信公众号当一个小小传话员啦。
这里给个思路,具体实现起来也比较简单,当做是文本来处理即可。
完整代码
下面贴出我服务器上的完整代码,有些私密的地方我做了些更改,届时按照自己的情况进行修改即可。
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=='Detailed explanation of steps to develop WeChat remote control server with PHP' || $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 == 'Detailed explanation of steps to develop WeChat remote control server with PHP模式'){ $msgType = 'text'; $contentStr = "进入Detailed explanation of steps to develop WeChat remote control server with PHP模式,开始对服务器进行管理!\n接下来将依据您输入的Detailed explanation of steps to develop WeChat remote control server with PHP对服务器进行管理!"; 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 = ""; $resultStr = sprintf ( $textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr ); echo $resultStr; } function imageMessageHandle($fromUsername, $toUsername, $time, $msgType, $contentStr) { $imageTpl = " %s 0 "; $resultStr = sprintf ( $textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr ); echo $resultStr; } function musicMessageHandle($fromUsername, $toUsername, $time, $msgType, $musictitle, $musicDescription, $musicurl, $hqmusicurl) { $musicTpl = " %s 1234567890123456 "; $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']; } ?> %s
总结
最后来回顾一下,本次试验用到了哪些知识点。
PHP的面向对象方法编程简单实现。
接口处理的两种方式
微信公众号后台私服的接入,处理,反馈。
前后端的交互,以及聊天机器人的应用。
其实,这些代码跟我一开始的设想还是差别挺大的,原本是想实现一个“遥控器”,晚上想睡觉之前,用微信发一条Detailed explanation of steps to develop WeChat remote control server with PHP“打开电热毯”,半个小时后,电视看完了,去睡觉的时候发现被窝很暖和,是的,只要加上点硬件,这很容易实现啦再者冰箱了,电视了统统可以完成,那样估计就诊的是“智能家居”了吧。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of steps to develop WeChat remote control server with PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
