php版微信自定义回复功能示例

yipeiwu_com6年前PHP代码库

本文实例讲述了php版微信自定义回复功能。分享给大家供大家参考,具体如下:

配置好服务器之后,就可以用php实现自动回复了。

index.php中的代码

<?php
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
  $wechatObj->valid();
}else{
  $wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
  public function valid()
  {
    $echoStr = $_GET["echostr"];
    if($this->checkSignature()){
      header('content-type:text');
      echo $echoStr;
      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;
    }
  }
  public function responseMsg()
  {
    $postStr = $GLOBALS["HTTP_RAW_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();
      $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($keyword == "?" || $keyword == "?") //获取用户信息
      {
        $msgType = "text";
        $contentStr = date("Y-m-d H:i:s",time()); // 回复的内容
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
      }
    }else{
      echo "";
      exit;
    }
  }
}
?>

效果:

当用户输入?或者?就会获取当前时间

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP微信开发技巧汇总》、《PHP编码与转码操作技巧汇总》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php 获取页面中指定内容的实现类

功能: 1.获取内容中的url,email,image。 2.替换内容中的url,email,image。 url:<a href="url">xxx</a> e...

php实现三级级联下拉框

这是我在网上查找到的php实现三级级联下拉框的资料,共享个大家,大家一起进步,具体内容如下 index.php: <html> <head> <met...

PHP mb_convert_encoding 获取字符串编码类型实现代码

后来又在手册上找到了is_utf8函数,这样,再结合iconv函数,我的问题就解决了。下面帖出这个函数: 复制代码 代码如下:function is_utf8($string) { re...

php URL验证正则表达式

复制代码 代码如下: <?php $url = 'http://www.baidu.com/zongzi/oo.html'; $n = preg_match_all("/http:...

深入解析PHP的引用计数机制

PHP的变量声明并赋值后,变量名存在符号表中,而值和类信息存在zval中,zval中包含四个变量,is_ref,refcount,value,type,zval源码如下复制代码 代码如下...