


WeChat 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 分别顺序替换模板里“%s”位置,也即是“$resultStr”这个变量最后实际为:
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...

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

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

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

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

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

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.
