>  기사  >  백엔드 개발  >  WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

小云云
小云云원래의
2018-01-27 09:28:081156검색

WeChat 개발은 최근 매우 인기가 높습니다. 이 기사에서는 PH가 WeChat을 사용하여 원격 제어 서버 기능을 구현하는 방법에 대한 예를 주로 공유하지만 아직 많은 부분을 다루지는 않았습니다. 하지만 일반 텍스트로 통신하는 경우에는 문제가 없습니다.

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

환경 설정

WeChat 공개 계정의 원칙에 대해 간략하게 이야기하겠습니다. 어쩌면 내 이해가 제대로 이루어지지 않았을 수도 있습니다. 잘못된 점이 있으면 비판과 조언을 환영합니다.

클라이언트가 WeChat 플랫폼에 요청을 보내고, WeChat 플랫폼은 해당 요청을 처리를 위해 프로그램에 넘겨준 후, 프라이빗 서버의 처리 결과를 얻어 클라이언트에 다시 피드백합니다. .

물론 “WeChat 공개 플랫폼”이 여기에 핵심적인 역할을 합니다. 재능 있는 사람과 낯선 사람이 각자의 개성을 보여줄 수 있는 무대, 플랫폼을 제공하는 것과 같다. 실제로 이는 위챗뿐만 아니라 알리바바에서도 마찬가지여서 주요 전자상거래 기업들이 자신들의 능력을 발휘할 수 있게 됐다.

구성 열기

첫 번째 단계는 WeChat 개발자 계정을 신청하는 것입니다. 개인의 경우 구독 계정을 선택하면 됩니다. 온라인에는 관련 정보가 많고 매우 상세하므로 자세한 내용은 다루지 않겠습니다. 바로 요점을 살펴보겠습니다.

먼저 개발자 계정 로그인에 성공하신 후 아래와 같이 서버사이드 설정을 열 수 있습니다

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

활성화 완료 후, 본인의 서버 조건에 맞게 설정을 하시면 됩니다.

  • URL은 요청 데이터를 처리하기 위해 개인 서버에서 사용하는 주소입니다.

  • TOKEN은 토큰이므로 원하는 대로 설정하세요. 그러나 나중에 자신의 코드에서 이를 사용할 것이라는 점을 기억하십시오.

  • 열쇠는 크게 사용하지 않으니 일단은 놔두셔도 됩니다.

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

필요에 따라 설정

설정 후 활성화하시면 됩니다. 이는 집에 있는 모든 전선을 장식하고 이제 이를 사용하고 스위치를 누르는 것과 같습니다. 아래와 같이

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

서버 구성 활성화

서버 환경

서버에 대해서는 공식 홈페이지에서 자세히 설명하고 있습니다.

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

공식 데모를 다운로드하여 시뮬레이션할 수도 있습니다.

WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예

공식 샘플

코드도 매우 간단합니다. 기본적으로 PHP의 기본 구문을 배운 사람이라면 누구나 이해할 수 있습니다.

<?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;
 }
 }
}
?>

핵심 아이디어는 서명을 확인하고, 요청을 처리하고, 결과를 피드백하는 것입니다.

여기서 말씀드리고 싶은 것은 Tencent가 실제로 해당 템플릿을 제거하고 블랙박스 모드를 직접 노출할 수 있다고 생각합니다. 이 경우 보안이 더 높아질 것입니다. 대부분의 경우 권한이 공개될수록 효과는 더 나빠질 수 있습니다.

Core Class

다음 단계는 나만의 처리 로직입니다. 공식 문서를 참고해주세요. WeChat 공개에는 6개의 수신 인터페이스와 3개의 응답 인터페이스가 있습니다. MsgType을 기준으로 확인할 수 있습니다.

인터페이스 세부정보

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;
 }
 }

검증 방법의 핵심은 이전 웹 페이지에서 설정한 TOKEN을 기반으로 작동하므로 코드에 사용됩니다.

Reply

응답 코드는 클라이언트가 보낸 데이터 유형에 따라 다르게 처리되어야 합니다. WeChat 플랫폼은 데이터를 패키지화하고 처리하기 위해 내부 MsgType을 호출하기만 하면 됩니다.

Expansion

확장 부분은 제 기분에 따라 추가했습니다.

로봇 추가

로봇 인터페이스를 호출하여 대신 응답을 보낼 수 있습니다. 이 기술을 사용하면 사용자가 좋은 사용자 경험을 얻을 수 있고 대중도 기쁘게 할 수 있습니다.

여기서 두 개의 인터페이스를 테스트했습니다. 하나는 컬 모드이고 다른 하나는 file_get_contents 모드입니다. 둘 다 사용하기 매우 쉽습니다.

<?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;

명령 모드

컴퓨터에 비해 휴대전화의 가장 큰 장점은 휴대성이 있다는 것입니다. 비록 컴퓨터를 언제 어디서나 가지고 다닐 수는 없지만 대신 휴대전화를 사용할 수 있다는 것입니다. 서버 관리에 필요한 명령어는 매우 간단한데 원격 로그인이 불편한 경우가 많습니다. 이때, 위챗을 활용해 소문을 퍼뜨리는 것도 좋습니다.

저는 보통 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=='WeChat을 이용한 원격제어 서버 기능의 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 == 'WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예模式'){
  $msgType = 'text';
  $contentStr = "进入WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예模式,开始对服务器进行管理!\n接下来将依据您输入的WeChat을 이용한 원격제어 서버 기능의 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 = "
  
  
  %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'];
}
?>

요약

마지막으로 이번 실험에 어떤 지식 포인트가 사용되었는지 복습해 보겠습니다.

  • PHP의 객체 지향 프로그래밍은 구현이 간단합니다.

  • 두 가지 인터페이스 처리 방법

  • WeChat 공개 계정의 백엔드 비공개 서버에 대한 액세스, 처리 및 피드백.

  • 프론트엔드와 백엔드의 상호작용, 그리고 챗봇의 적용.

사실 이 코드는 원래 생각과 많이 다릅니다. 원래는 밤에 잠자리에 들기 전에 위챗을 사용하여 "전기 담요를 켜세요"라는 명령을 보내려고 했습니다. .30분 후에 TV를 보고 잠자리에 들었을 때 침대가 매우 따뜻하다는 것을 알았습니다. 네, 하드웨어만 추가하면 쉽게 완성할 수 있습니다. 그리고 TV. 그렇다면 그것은 "스마트 홈"인 것 같아요.

관련 권장 사항:

영구 저장 예제 공유로 임시 변환을 기록하는 WeChat의 PHP 구현

WeChat 애플릿 개발에서 발생한 문제 요약

js in WeChat, Weibo, QQ, Huo 앱 예제 공유

위 내용은 WeChat을 이용한 원격제어 서버 기능의 PHP 구현 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.