Home > WeChat Applet > WeChat Development > php development WeChat public platform interface smart reply example code

php development WeChat public platform interface smart reply example code

高洛峰
Release: 2017-03-20 14:10:30
Original
2331 people have browsed it

This article mainly introduces the intelligent reply development of the PHP version of the WeChat public platform interface . It analyzes in detail the principle of the reply-only function and the specific implementation techniques through the WeChat interface call in the form of examples. Friends in need can refer to

This article describes the implementation method of the smart reply function in the PHP version of WeChat public platform interface development. Share it with everyone for your reference, the details are as follows:

Smart reply is to feedback the results to the user based on the conditions entered by the user. This editor has written before and compiled some examples for your reference. It is relatively complete. It is introduced on the development side.

WeChat has become really popular since its launch, and the launch of the payment function has pushed WeChat to an unparalleled height, and people who applied for WeChat subscription accounts or service accounts began to flock one after another. Now I will give you a brief explanation of the WeChat public platform development interface.

First go to the WeChat public platform to apply for an account, and then follow the prompts step by step. When choosing a subscription account and a service account, individuals can only apply for a subscription account, and it is limited to basic functions; while enterprises can apply for both. The difference between a subscription account and a service account is that a subscription account can send one message per day, while a service account can only send one message per month; a subscription account requires WeChat certification Custom menu (can only be certified by an enterprise, and certification costs 300 yuan per time ), while the service account has a customized menu from the beginning, but it can also be authenticated. After authentication, the service account can directly upgrade to advanced functions. For more differences, please refer to Baidu...

I applied for a subscription account because I am an individual. Just send a photo of your face holding your ID card, although it’s a bit silly. Then wait for the information registration review (about a day). After passing, directly enter the WeChat public platform, click on the function to enter the advanced function, turn off edit mode, turn on the development mode, then download the demo provided by WeChat, unzip it, and there will be only one file: wx_sample.php, the code is as follows:

<?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 (!emptyempty($postStr)){
        $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $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>";
  if(!emptyempty( $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()
 {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
 $token = TOKEN;
 $tmpArr = array($token, $timestamp, $nonce);
 sort($tmpArr, SORT_STRING);
 $tmpStr = implode( $tmpArr );
 $tmpStr = sha1( $tmpStr );
 if( $tmpStr == $signature ){
  return true;
 }else{
  return false;
 }
 }
}
?>
Copy after login

In fact, it is authentication, and thensends the message. Transfer the file to your server, I put it in the root directory, and then modify the url and token values ​​in development mode. Assume that the URL used here is http://www.jb51.net/wx_sample.php, and the token is the token defined above. This can be changed, as long as both sides are consistent, the default is weixin. Then click Submit, and you will be prompted that it is successful. Then scan the number you applied for and send a message. You will find that there is no response. At this time, we need to make a small adjustment. Turn off the method of calling authentication in the interface document and enable the method of calling the reply information:

//$wechatObj->valid();
$wechatObj->responseMsg();
Copy after login

If you send a message at this time, you will receive: Welcome to wechat world!

After following some subscription accounts or service accounts, you will receive a message immediately. What to reply 1, how and so on; reply 2, how and so on and so on.

How to achieve this? Go directly to the code:

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)){
      $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
      $fromUsername = $postObj->FromUserName;
      $toUsername = $postObj->ToUserName;
      $keyword = trim($postObj->Content);
      $time = time();
      $MsgType = $postObj->MsgType; //add
      $textTpl = "
        
        
        %s
        
        
        0
        ";
      if($MsgType != 'event') {
        if(!empty( $keyword ))
        {
          $msgType = "text";
          $contentStr = "Welcome to wechat world!";
        }else{
          echo "Input something...";
        }
      } else {
        $msgType = "text";
        $contentStr = "感谢您关注AndyYang个人博客微信小助手。\r\n".
          "回复【1】返回两篇最新文章\r\n".
          "回复【2】返回两篇人气文章\r\n".
          "回复【3】返回两篇热评文章\r\n".
          "回复【4】返回两篇最新技术文章\r\n".
          "回复【5】返回两篇最新写作文章\r\n".
          "回复其他返回搜索关键字的两篇文章\r\n".
          "更多精彩内容,尽在:www.jb51.net。亲们,请多多支持哦,谢谢~";
        ;
      }
      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
      echo $resultStr;
    }else {
      echo "";
      exit;
    }
  }
  private function checkSignature()
  {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    $token = TOKEN;
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING); //这个在新的sdk中添加了第二个参数(compare items as strings)
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
    if( $tmpStr == $signature ){
      return true;
    }else{
      return false;
    }
  }
}
Copy after login

Of course, this is just a simple implementation. Simple modifications are made on the SDK provided by the WeChat public platform. In fact, there are many msgtype types. Even if the message type is event, it also includes subscribe, LOCATION, etc., and if you want to refine it, use Event as subscribe to handle the first event of concern. The code is as follows:

<?php
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->weixin_run();
class wechatCallbackapiTest {
  private $fromUsername;
  private $toUsername;
  private $times;
  private $keyword;
  private $MsgType;
  public function responseMsg() {
 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
 if (!emptyempty($postStr)) {
      $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
      $this->fromUsername = $postObj->FromUserName;
      $this->toUsername  = $postObj->ToUserName;
      $this->keyword   = trim($postObj->Content);
      $this->time     = time();
      $this->MsgType   = $postObj->MsgType;
    } else {
     echo "Pay attention to <a href=&#39;http://{$_SERVER[&#39;HTTP_HOST&#39;]}&#39;>http://{$_SERVER[&#39;HTTP_HOST&#39;]}</a>,thanks!";
     exit;
    }
  }
  public function weixin_run() {
    $this->responseMsg();
    if($this->MsgType != &#39;event&#39;) { //attention
      $data = $this->getData();
     $this->fun_xml("news", $data, count($data));
    } else {
      $data = $this->getWelData();
     $this->fun_xml("text", $data, 1);
    }
  }
 //type: text 文本类型, news 图文类型
 //text,array(内容),array(ID)
 //news,array(array(标题,介绍,图片,超链接),...小于10条),条数
 private function fun_xml($type, $value_arr, $count) {
   $con="<xml>
   <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
   <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
   <CreateTime>{$this->times}</CreateTime>
   <MsgType><![CDATA[{$type}]]></MsgType>";
    switch($type) {
     case "text" :
   $con.="<Content><![CDATA[$value_arr]]></Content>";
     break;
   case "news" :
   $con.="<ArticleCount>{$count}</ArticleCount>
    <Articles>";
   foreach($value_arr as $key => $v) {
      $con.="<item>
       <Title><![CDATA[{$v[0]}]]></Title>
       <Description><![CDATA[{$v[1]}]]></Description>
       <PicUrl><![CDATA[{$v[2]}]]></PicUrl>
       <Url><![CDATA[{$v[3]}]]></Url>
       </item>";
   }
   $con.="</Articles>";
     break;
   }
   echo $con."</xml>";
 }
  private function getData() {
    //数据库通过关键字查询文章
    //。。。。。。。。。。。。
    //。。。。。。。。。。。。
    //返回文章结果的数组
    return $data;
  }
  private function getWelData() {
    $data = "感谢您关注AndyYang个人博客微信小助手。\r\n".
          "回复【1】返回两篇最新文章\r\n".
          "回复【2】返回两篇人气文章\r\n".
          "回复【3】返回两篇热评文章\r\n".
          "回复【4】返回两篇最新技术文章\r\n".
          "回复【5】返回两篇最新写作文章\r\n".
          "回复其他返回搜索关键字的两篇文章\r\n".
          "更多精彩内容,尽在:<a href=&#39;http://www.jb51.net/&#39;>www.jb51.net</a>。亲们,请多多支持哦,谢谢~";
        ;
    return $data;
  }
}
Copy after login

Honestly, I really want to get a service account to play with. There is no technical content in customizing the menu. , but the following services such as WeChat payment and service accounts are still worth trying.

The above is the detailed content of php development WeChat public platform interface smart reply example code. For more information, please follow other related articles on the PHP Chinese website!

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