Home WeChat Applet WeChat Development Introduction to how to use PHP to develop WeChat to receive messages, automatically judge and reply to corresponding messages

Introduction to how to use PHP to develop WeChat to receive messages, automatically judge and reply to corresponding messages

Mar 20, 2017 pm 02:37 PM
php WeChat development

This article mainly introduces the development of the PHP version of WeChatreceiving messages, the method of automatically judging and replying to the corresponding messages, and involves the related operation skills of calling based on the WeChat message processinginterface, Friends in need can refer to

This article describes the example of the PHP version of WeChat development on how to receive messages, automatically judge and reply to corresponding messages. I share it with you for your reference. The details are as follows:

WeChat’s api is now powerful enough that you can freely call the content of our website or designated database to automatically reply and push messages, here Let me introduce you to a WeChat development note.

Send 1, 2, 3, 7 test corresponding messages, the menu mode needs to be upgraded to a service account, or the number of subscribers exceeds 500.

1. The messages sent by users are received through the developer URL submitted by you. You can get it by subscribing here. The data sent is in the xml format and needs to be parsed. The code is as follows:

$data = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!emptyempty($data)) {//接收消息并处理
$xml = (array)simplexml_load_string($data, ‘SimpleXMLElement', LIBXML_NOCDATA);
return $xml;
}
Copy after login

The reply also needs to return XML data format.

2. Actively send messages to users, query user information, and create custom menu (subscription accounts can also be used now), As well as some advanced functions, you need to obtain the appid and AppSecret in order to obtain the access_token.

Access_token is used by every interface in addition to receiving information. The access_token expires in 7200 milliseconds and needs to be obtained again.

Currently, I have implemented it, receiving messages, automatically judging and replying to the corresponding news, creating a custom menu, and performing corresponding operations after clicking on the custom menu, such as user lists. I feel that there is no difference between the current development model and the subscription model.

Here is a test example of testing the reply, the code is as follows:

<?php
/**
 * wechat php test
 */
//define your token
define("TOKEN", "你的申请上的token");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
 public function valid()
  {
    $echoStr = $_GET["echostr"];
    //valid signature , option
    if($this->checkSignature()){
     $this->responseMsg();
     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, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
  $msgType = "text";
        $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 ))
        {
         $contentStr = $this->keyrep($keyword);
   if( emptyempty($contentStr) )
   {
   $contentStr ="你是故意的吧,没文化真可怕";//你是故意的吧,没文化真可怕;
   }
   //$contentStr = @iconv('UTF-8','gb2312',$keyword);
         $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
         echo $resultStr;
        }else{
         $contentStr = '没文化真可怕,居然不会打字!';//$this->keyrep($keyword);
         //$contentStr = @iconv('UTF-8','gb2312',$keyword);
   $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);
 $tmpStr = implode( $tmpArr );
 $tmpStr = sha1( $tmpStr );
 if( $tmpStr == $signature ){
  return true;
 }else{
  return false;
 }
 }
 function keyrep($key)
 {
 //return $key;
 if( $key=='嗨' || $key=='在吗' || $key=='你好' ){
  $mt = mt_rand(1,17);
  $array = array(1=>'自杀中,稍后再说...',2=>'有事找我请大叫!',3=>'我正在裸奔,已奔出服务区',4=>'我现在位置:WC; 姿势:下蹲; 脸部:抽搐; 状态:用力中。。。。',5=>'去吃饭了,如果你是帅哥,请一会联系我,如果你是美女...............就算你是美女,我也要先吃饱肚子啊',6=>'
洗澡中~谢绝旁观!!^_^0',7=>'有熊出?],我去诱捕,尽快回来。',8=>'你好,我是500,请问你是250吗?',9=>'喂!乱码啊,再发',10=>'
不是我不理你,只是时间难以抗拒!',11=>'你刚才说什么,我没看清楚,请再说一遍!',12=>'发多几次啊~~~发多几次我就回你。',13=>'此人已死,有事烧纸!',14=>'乖,不急哦…',15=>'你好.我去杀几个人,很快回来.',16=>'本人已成仙?有事请发烟?佛说有烟没火成不了正果?有火没烟成不了仙。',17=>'
你要和我说话?你真的要和我说话?你确定自己想说吗?你一定非说不可吗?那你说吧,这是自动回复,反正我看不见其实我在~就是不回你拿我怎么着?'
);
  return $array[$mt];
 }
 if( $key=='靠' || $key=='啊' || $key=='阿' )
 {
  $mt = mt_rand(1,19);
  $array = array(1=>'人之初?性本善?玩心眼?都滚蛋。',2=>'今后的路?我希望你能自己好好走下去?而我 坐车',3=>'笑话是什么?就是我现在对你说的话。',4=>'人人都说我丑?其实我只是美得不明显。',5=>'A;猪是怎么死的?B;你还没死我怎么知道',6=>'
奥巴马已经干掉和他同姓的两个人?奥特曼你要小心了。 ',7=>'有的人活着?他已经死了?有的人活着?他早该死了。',8=>'"妹妹你坐船头?哥哥我岸上走"据说很傻逼的人看到都是唱出来的。',9=>'我这辈子只有两件事不会?这也不会?那也不会。',10=>'
过了这个村?没了这个店?那是因为有分店。',11=>'我以为你只是个球?没想到?你真是个球。',12=>'你终于来啦,我找你N年了,去火星干什么了?我现在去冥王星,回头跟你说个事,别走开啊',13=>'你有权保持沉默,你所说的一切都将被作为存盘记录。你可以请代理服务器,如果请不起网络会为你分配一个。',14=>'本人正在被国际刑警组织全球范围内通缉,如果您有此人的消息,请拨打当地报警电话',15=>'洗澡中~谢绝旁观!!^_^0',16=>'嘀,这里是移动秘书, 美眉请再发一次,我就与你联系;姐姐请再发两次,我就与你联系;哥哥、弟弟就不要再发了,因为发了也不和你联系!',17=>'
其实我在~就是不回你拿我怎么着?',18=>'你刚才说什么,我没看清楚,请再说一遍!',19=>'乖,不急。。。');
  return $array[$mt];
 }
 if( $key =='请问' )
 {
  $mt = mt_rand(1,5);
  $array = array(1=>'"我脸油吗"反光??反正我不清楚',2=>'走,我请你吃饭',3=>'此人已死,有事烧纸!',4=>'喂!什么啊!乱码啊,再发',5=>'笑话是什么??就是我现在对你说的话。');
  return $array[$mt];
 }
 return "";
 }
 function keylist()
 {
 $array = array(1=>'嗨',2=>'你好',3=>'靠',4=>'在吗',5=>'请问');
 }
}
?>
Copy after login

The above is the detailed content of Introduction to how to use PHP to develop WeChat to receive messages, automatically judge and reply to corresponding messages. For more information, please follow other related articles on the PHP Chinese website!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles