Home > Backend Development > PHP Tutorial > Introductory example of WeChat public platform development based on PHP, PHP public platform example_PHP tutorial

Introductory example of WeChat public platform development based on PHP, PHP public platform example_PHP tutorial

WBOY
Release: 2016-07-13 09:57:06
Original
936 people have browsed it

Introduction examples of WeChat public platform development based on php, php public platform examples

This article describes the development method of WeChat public platform based on php. Share it with everyone for your reference. The details are as follows:

I have been working on WeChat public platform development recently, and I wrote more than 20 functions in one breath, which is quite interesting~

Let me share my development experience today~
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, the user uses WeChat to send messages -> WeChat sends the data 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 is interacted with XML done, 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 with one ID card. The account name is related to V authentication, so please register carefully.

2. Apply for server/virtual host

Children’s shoes without a server/virtual host can use BAE and SAE, no more introduction.

3. Turn on developer mode

The 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, and two parameters need to be configured:
URL: Developer application access address, currently only supports port 80, take "http://www.YoonPer.com/weixin/index.php" as an example.
TOKEN: Fill it in at will and use it to generate a signature, taking "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.

<&#63;php
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;
    }
  }
}
&#63;>
Copy after login

This thing is to verify whether the URL is correctly accessed by the WeChat public platform. There is no substantive meaning in studying the code. The file can be deleted after verification. I will not explain it in detail. Interested children can check the official documentation.
WeChat public platform API documentation:
http://mp.weixin.qq.com/wiki/index.php

5. Develop WeChat public platform functions

OK, as mentioned above, 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 provided by the official interface document Specification, take text message 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><![CDATA[toUser]]></ToUserName>
<!--发送方帐号(OpenID)-->
<FromUserName><![CDATA[fromUser]]></FromUserName>
<!--消息创建时间 (整型)-->
<CreateTime>12345678</CreateTime>
<!--消息类别 (text文本消息)-->
<MsgType><![CDATA1]></MsgType>
<!--消息内容-->
<Content><![CDATA[content]]></Content>
<!--消息ID (64位整型)-->
<MsgId>1234567890123456</MsgId>
</xml>
Copy after login

After processing the message, the developer needs to return the data to the WeChat server:

<xml>
<!--接收方帐号(OpenID)-->
<ToUserName><![CDATA[toUser]]></ToUserName>
<!--开发者微信号-->
<FromUserName><![CDATA[fromUser]]></FromUserName>
<!--消息创建时间 (整型)-->
<CreateTime>12345678</CreateTime>
<!--消息类别 (text文本消息)-->
<MsgType><![CDATA1]></MsgType>
<!--回复消息内容-->
<Content><![CDATA[content]]></Content>
<!--星标操作(位0x0001被标志时 星标刚收到的消息)-->
<FuncFlag>0</FuncFlag>
</xml>
Copy after login

In addition to text messages, the WeChat public platform also supports users to send picture messages, geographical location messages, link messages, and event push. Developers can also reply to music messages and graphic messages to the WeChat public platform. Various message XML specifications See also the official documentation.

Let’s take a look at an official PHP example. I’ve simplified it a bit:

<&#63;php
/*-------------------------------------------------
|   index.php [ 微信公众平台接口 ]
+--------------------------------------------------
|   Author: LimYoonPer
+------------------------------------------------*/
$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat {
 public function responseMsg() {
  //---------- 接 收 数 据 ---------- //
  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据
  //用SimpleXML解析POST过来的XML数据
  $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
  $fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)
  $toUsername = $postObj->ToUserName; //获取接收方账号
  $keyword = trim($postObj->Content); //获取消息内容
  $time = time(); //获取当前时间戳
  //---------- 返 回 数 据 ---------- //
  //返回消息模板
  $textTpl = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>0</FuncFlag>
  </xml>";
  $msgType = "text"; //消息类型
  include('simsimi.php');
  $contentStr = simsimi($keyword); //返回消息内容
  //格式化消息模板
  $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
  echo $resultStr; //输出结果
 }
}
&#63;>
Copy after login

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

Now when users send any message through the WeChat public platform, 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) interface using CURL. Incoming keywords will return a text reply. This part is not the focus of this article, so I will not elaborate further. Directly upload the code (updated on 2014.07.28):

<&#63;php
/*-------------------------------------------------
|   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(';', $matches[1]).";simsimi_uid=1;";
  curl_close($ch);
  //----------- 抓 取 回 复 ----------//
  $url = "http://www.simsimi.com/func/reqN&#63;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['result'] == '200' ) {
    return $content['sentence_resp'];
  } else {
    return '我还不会回答这个问题...';
  }
}
&#63;>
Copy after login

Integrate the above two pieces of code and you are done. It needs to be explained that the WeChat server will disconnect if it does not receive a response within 5 seconds. There may be a timeout through this interface, and SimSimi has blocked BAE and SAE. For crawling requests, it is recommended to use SimSimi’s official paid API, which is faster~

I hope this article will be helpful to everyone in developing WeChat public platform based on PHP.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/984616.htmlTechArticleIntroduction examples of php-based WeChat public platform development, php public platform examples This article describes the php-based WeChat public platform development methods. Share it with everyone for your reference. The details are as follows...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template