search
HomeWeChat AppletWeChat DevelopmentPHP WeChat public platform development reply function example code

This article mainly introduces the fourth article of PHP WeChat public platform development, WeChat reply function development, which has certain reference value. Interested friends can refer to it

1. Introduction

The WeChat public platform can make judgments based on the information sent by users, and then give corresponding replies, which has good interactivity. The following will simulate a simple reply function. Based on this case, developers can also basically understand the principles of WeChat interaction and conduct deeper development.

2. Idea analysis

We can extract keywords from the text messages sent by users, and use simple if...elseif...else... accomplish.

The key code is as follows:


if($keyword=="你好"){
  $contentStr = "hello";
}elseif($keyword=="苏州"){
  $contentStr = "上有天堂,下有苏杭";
}else{
  $contentStr = "感谢您关注【卓锦苏州】 微信号:zhuojinsz";
}

If the user sends "Hello", then reply "hello", if the user sends "Suzhou", then reply " There is heaven above, Suzhou and Hangzhou below." For other information, I will reply with your welcome message.

3. Complete code


<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "zhuojin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
//$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)){
        
         $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
        $RX_TYPE = trim($postObj->MsgType);

        switch($RX_TYPE)
        {
          case "text":
            $resultStr = $this->handleText($postObj);
            break;
          case "event":
            $resultStr = $this->handleEvent($postObj);
            break;
          default:
            $resultStr = "Unknow msg type: ".$RX_TYPE;
            break;
        }
        echo $resultStr;
    }else {
      echo "";
      exit;
    }
  }

  public function handleText($postObj)
  {
    $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(!empty( $keyword ))
    {
      $msgType = "text";

      if($keyword=="你好"){
        $contentStr = "hello";
      }elseif($keyword=="苏州"){
        $contentStr = "上有天堂,下有苏杭";
      }else{
        $contentStr = "感谢您关注【卓锦苏州】 微信号:zhuojinsz";
      }
      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
      echo $resultStr;
    }else{
      echo "Input something...";
    }
  }

  public function handleEvent($object)
  {
    $contentStr = "";
    switch ($object->Event)
    {
      case "subscribe":
        $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待...";
        break;
      default :
        $contentStr = "Unknow Event: ".$object->Event;
        break;
    }
    $resultStr = $this->responseText($object, $contentStr);
    return $resultStr;
  }
  
  public function responseText($object, $content, $flag=0)
  {
    $textTpl = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[text]]></MsgType>
          <Content><![CDATA[%s]]></Content>
          <FuncFlag>%d</FuncFlag>
          </xml>";
    $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
    return $resultStr;
  }


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

?>

4. Test

PHP WeChat public platform development reply function example code##

The above is the detailed content of PHP WeChat public platform development reply function example code. 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor