search
HomeBackend DevelopmentPHP TutorialWeChat public platform development (2) WeChat public platform sample code analysis_PHP tutorial

The WeChat public platform provides a simple PHP sample code. Before further development, it is necessary for us to understand it in detail.

WeChat official website: http://mp.weixin.qq.com/mpres/htmledition/res/wx_sample.zip

The complete code is as follows:

<?<span php
</span><span /*</span><span *
  * wechat php test
  </span><span */</span>

<span //</span><span define your token</span>
<span define</span>("TOKEN", "weixin"<span );
</span><span $wechatObj</span> = <span new</span><span  wechatCallbackapiTest();
</span><span $wechatObj</span>-><span valid();

</span><span class</span><span  wechatCallbackapiTest
{
    </span><span public</span> <span function</span><span  valid()
    {
        </span><span $echoStr</span> = <span $_GET</span>["echostr"<span ];

        </span><span //</span><span valid signature , option</span>
        <span if</span>(<span $this</span>-><span checkSignature()){
            </span><span echo</span> <span $echoStr</span><span ;
            </span><span exit</span><span ;
        }
    }

    </span><span public</span> <span function</span><span  responseMsg()
    {
        </span><span //</span><span get post data, May be due to the different environments</span>
        <span $postStr</span> = <span $GLOBALS</span>["HTTP_RAW_POST_DATA"<span ];

        </span><span //</span><span extract post data</span>
        <span if</span> (!<span empty</span>(<span $postStr</span><span )){
                
                </span><span $postObj</span> = <span simplexml_load_string</span>(<span $postStr</span>, 'SimpleXMLElement',<span  LIBXML_NOCDATA);
                </span><span $fromUsername</span> = <span $postObj</span>-><span FromUserName;
                </span><span $toUsername</span> = <span $postObj</span>-><span ToUserName;
                </span><span $keyword</span> = <span trim</span>(<span $postObj</span>-><span Content);
                </span><span $time</span> = <span time</span><span ();
                </span><span $textTpl</span> = "<span <xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml></span>"<span ;             
                </span><span if</span>(!<span empty</span>( <span $keyword</span><span  ))
                {
                    </span><span $msgType</span> = "text"<span ;
                    </span><span $contentStr</span> = "Welcome to wechat world!"<span ;
                    </span><span $resultStr</span> = <span sprintf</span>(<span $textTpl</span>, <span $fromUsername</span>, <span $toUsername</span>, <span $time</span>, <span $msgType</span>, <span $contentStr</span><span );
                    </span><span echo</span> <span $resultStr</span><span ;
                }</span><span else</span><span {
                    </span><span echo</span> "Input something..."<span ;
                }

        }</span><span else</span><span  {
            </span><span echo</span> ""<span ;
            </span><span exit</span><span ;
        }
    }
        
    </span><span private</span> <span function</span><span  checkSignature()
    {
        </span><span $signature</span> = <span $_GET</span>["signature"<span ];
        </span><span $timestamp</span> = <span $_GET</span>["timestamp"<span ];
        </span><span $nonce</span> = <span $_GET</span>["nonce"<span ];    
                
        </span><span $token</span> =<span  TOKEN;
        </span><span $tmpArr</span> = <span array</span>(<span $token</span>, <span $timestamp</span>, <span $nonce</span><span );
        </span><span sort</span>(<span $tmpArr</span><span );
        </span><span $tmpStr</span> = <span implode</span>( <span $tmpArr</span><span  );
        </span><span $tmpStr</span> = <span sha1</span>( <span $tmpStr</span><span  );
        
        </span><span if</span>( <span $tmpStr</span> == <span $signature</span><span  ){
            </span><span return</span> <span true</span><span ;
        }</span><span else</span><span {
            </span><span return</span> <span false</span><span ;
        }
    }
}

</span>?>

3.1 Overall analysis

The original sample code is roughly divided into four parts:

  • Define TOKEN
  • Declare a class wechatCallbackapiTest
  • Create an instance object of class wechatCallbackapiTest $wechatObj
  • Call the valid() method of the class.

3.2 Detailed analysis

3.2.1 Define TOKEN

3.2.2 Declare a class

<span <span><span><span <strong>responseMsg 函数详解:</strong></span><br /><br /></span></span><span>$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];</span><br />接收微信公众平台发送过来的用户消息,该消息数据结构为XML,不是php默认的识别数据类型,因此这里用了$GLOBALS['HTTP_RAW_POST_DATA']来接收,同时赋值给了$postStr<br /><br />if (!empty($postStr))<br />判断$postStr是否为空,如果不为空(接收到了数据),就继续执行下面的语句;如果为空,则跳转到与之相对应的else语句。<br /><br />$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);<br />使用simplexml_load_string() 函数将接收到的XML消息数据载入对象$postObj中。这个严谨的写法后面还得加个判断是否载入成功的条件语句,不过不写也没事。<br /><br />$fromUsername = $postObj->FromUserName;<br />将对象$postObj中的发送消息用户的OPENID赋值给$fromUsername变量<br /><br />$toUsername = $postObj->ToUserName;<br />将对象$postObj中的公众账号的ID赋值给$toUsername变量<br /><br />$keyword = trim($postObj->Content);<br />trim() 函数从字符串的两端删除空白字符和其他预定义字符,这里就可以得到用户输入的关键词<br /><br />$time = time();<br />time() 函数返回当前时间的 Unix 时间戳,即自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。<br /><br />$textTpl = "<xml><br /></span>       <ToUserName><![CDATA[%s]]></ToUserName><br />       <FromUserName><![CDATA[%s]]></FromUserName><br />        <CreateTime>%s</CreateTime><br />       <MsgType><![CDATA[%s]]></MsgType><br />       <Content><![CDATA[%s]]></Content><br />       <FuncFlag>0</FuncFlag><br />       </xml>";<br />存放微信输出内容的模板<br /><br />if(!empty( $keyword ))<br />判断$keyword是否为空,不为空则继续执行下面的语句;如果为空,则跳转到与之相对应的else语句,即 echo "Input something...";<br /><br />$msgType = "text";<br />消息类型是文本类型<br /><br />$contentStr = "Welcome to wechat world!";<br />回复的消息内容<br /><br />$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br />使用sprintf() 函数将格式化的数据写入到变量中去;<br />$fromUsername, $toUsername, $time, $msgType, $contentStr 分别顺序替换模板里&ldquo;%s&rdquo;位置,也即是&ldquo;$resultStr&rdquo;这个变量最后实际为:




$time


0 //When bit 0x0001 is flagged, the star just received the message.

echo $resultStr; //Output the reply message

<span 加密/校验流程:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信</span>

3.2.4 Calling class method verification

$wechatObj->valid();

The above is an analysis of WeChat’s official sample code. If there are any incorrect explanations, please ask experts to point them out. In addition, this code is only a simple example code provided by the official. If complex development is required, developers are still required to rewrite this code according to a rigorous development model, which will be explained in subsequent tutorials.

WeChat official public platform API document: http://mp.weixin.qq.com/wiki/index.php

Please follow Zhuojin Suzhou WeChat public account, Zhuojin Suzhou is developed based on the SAE platform and is developed and tested for mainstream WeChat functions.

You can follow the Zhuojin Suzhou public account to conduct functional testing and obtain new application development.

1. Log in to the WeChat client, friends -> Add friends -> Search number -> zhuojinsz, find and follow.

2. Scan the QR code:

Zhuojin Suzhou Function list.


We Believe, Great People Share Knowledge...

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440310.htmlTechArticleWeChat public platform provides a simple PHP sample code. Before further development, we need to make it detailed Find out. WeChat official website: http://mp.weixin.qq.com/mpres/ht...
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment