Home  >  Article  >  Backend Development  >  PHP basic tutorial WeChat public platform development

PHP basic tutorial WeChat public platform development

巴扎黑
巴扎黑Original
2017-08-17 09:06:591342browse


Abstract: The interface provided by WeChat public platform is very simple. Let’s take a look at the message interaction process first: To put it more simply, users use WeChat to send messages - WeChat transfers data Send to the developer - The developer processes the message and returns the data to WeChat - WeChat sends the returned data to the user, during which the data interaction is completed through XML, that's it...

WeChat Public Platform The interface provided is very simple. Let’s take a look at the message interaction process first:

PHP basic tutorial WeChat public platform development

To put it more simply, users use WeChat to send messages -> WeChat sends data to developers Author-> The developer processes the message and returns the data to WeChat-> WeChat sends the returned data to the user, and the data interaction is completed through XML. It's that simple.

Write an example below to develop a WeChat intelligent chatbot:

  1. Register a WeChat public platform account
    WeChat public platform:
    https://mp.weixin.qq.com/
    Note: Currently, only two accounts can be registered for one ID card. The account name is related to V certification, so please register carefully.

  2. Apply for server/virtual host
    Children's shoes without server/virtual host can use BAE and SAE, no more introduction.

  3. Enable developer mode
    WeChat public platform has two modes, one is the editing mode (fool mode), which is simple but has a single function. The other is the developer mode, which can implement complex functions through development. The two modes are mutually exclusive. Obviously, log in to the WeChat public platform and turn on the developer mode through the "Advanced Functions" menu.

  4. Fill in the interface configuration information
    It is also configured in the "Advanced Functions" menu. Two parameters need to be configured:
    URL: Developer application access address, currently only supported Port 80, take "http://www.YoonPer.com/weixin/index.php" as an example.
    TOKEN: Fill in whatever you want to generate a signature, take "YoonPer" as an example.
    After filling in, save the following code as index.php and upload it to the http://www.YoonPer.com/weixin/ directory, and finally click "Submit" to complete the verification.

define("TOKEN", "YoonPer"); //TOKEN值
$wechatObj = new wechat();
$wechatObj->valid();
class wechat {
  public function valid() {
    $echoStr = $_GET["echostr"];
    if($this->checkSignature()){
      echo $echoStr;
      exit;
    }
  }
  private function checkSignature() {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    $token = TOKEN;
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
    if( $tmpStr == $signature ) {
      return true;
    } else {
      return false;
    }
  }
}
?>

In fact, it is the WeChat public platform to verify whether the URL is correctly accessed. There is no substantive meaning in studying the code. The file can be deleted after verification. I will not explain it in detail. For those who are interested, You can view the official documentation.
WeChat public platform API document: http://mp.weixin.qq.com/wiki/index.php

  1. Developing WeChat public platform functions
    OK, as mentioned above Here, the data interaction between the WeChat public platform and developers is completed through XML. Since XML is used, of course it must follow the specifications, so before starting development, take a look at the XML specifications provided by the official interface document, taking text messages as an example. :

When a user sends a message to a WeChat public account, the WeChat server will POST some data to the developer:

<xml><ToUserName>ToUserName><FromUserName>FromUserName><CreateTime>12345678CreateTime><MsgType><![CDATA1]>MsgType><Content>Content><MsgId>1234567890123456MsgId>xml>

The developer needs to return the data after processing the message To the WeChat server:

<xml><ToUserName>ToUserName><FromUserName>FromUserName><CreateTime>12345678CreateTime><MsgType><![CDATA1]>MsgType><Content>Content><FuncFlag>0FuncFlag>xml>

In addition to text messages, the WeChat public platform also supports users to send picture messages, location messages, link messages, and event push, and developers can also reply to the WeChat public platform with music messages and pictures. Text messages, various message XML specifications can also be found in official documents.

Let’s take a look at an official PHP example. I made some simplifications:

responseMsg();
class wechat {
 public function responseMsg() {
  //---------- 接 收 数 据 ---------- //
  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
  //用SimpleXML解析POST过来的XML数据
  $postObj = simplexml_load_string($postStr,&#39;SimpleXMLElement&#39;,LIBXML_NOCDATA);
  $fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
  $toUsername = $postObj->ToUserName; //获取接收方账号
  $keyword = trim($postObj->Content); //获取消息内容
  $time = time(); //获取当前时间戳
  //---------- 返 回 数 据 ---------- //
  //返回消息模板
  $textTpl = "%s0";
  $msgType = "text"; //消息类型
  include(&#39;simsimi.php&#39;);
  $contentStr = simsimi($keyword); //返回消息内容
  //格式化消息模板
  $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
  echo $resultStr; //输出结果
 }
}
?>

Save the code as index.php and upload it to http://www.YoonPer.com/weixin / directory, if the file was not deleted just now, it will be overwritten directly.

Now users send any message through the WeChat public platform and the public account will return a message with the content "http://www.YoonPer.com".
The next thing you need to do is to dynamically return results based on user messages~

SimSimi (Little Yellow Chicken) is currently a popular chat robot. I developed a free SimSimi (Little Yellow Chicken) using CURL. interface, passing in keywords will return a text reply. This part is not the focus of this article, so I won’t explain it further. Just go to the code:

/*-------------------------------------------------
|   simsimi.php [ 智能聊天(simsimi) ]
+--------------------------------------------------
|   Author: LimYoonPer
+------------------------------------------------*/

function simsimi ($keyword)
{
  $keyword = urlencode($keyword);
  //----------- 获取COOKIE ----------//
  $url = "http://www.simsimi.com/";
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $content = curl_exec($ch);
  list($header, $body) = explode("\r\n\r\n", $content);
  preg_match_all("/set\-cookie:([^\r\n]*);/iU", $header, $matches);
  $cookie = implode(&#39;;&#39;, $matches[1]).";simsimi_uid=1;";
  curl_close($ch);
  //----------- 抓 取 回 复 ----------//
  $url = "http://www.simsimi.com/func/reqN?lc=ch&ft=0.0&req=$keyword&fl=http%3A%2F%2Fwww.simsimi.com%2Ftalk.htm";
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  $content = json_decode(curl_exec($ch), 1);
  curl_close($ch);
  if ( $content[&#39;result&#39;] == &#39;200&#39; ) {
    return $content[&#39;sentence_resp&#39;];
  } else {
    return &#39;我还不会回答这个问题...&#39;;
  }
}
?>

Integrate the above two pieces of code and you are done. One thing needs to be explained, WeChat If the server does not receive a response within 5 seconds, the connection will be disconnected. There may be a timeout through this interface, and SimSimi has blocked crawl requests on BAE and SAE. It is recommended to use SimSimi's official paid API, which is faster~

The above is the detailed content of PHP basic tutorial WeChat public platform development. 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