Home Backend Development PHP Tutorial Detailed explanation of php WeChat public platform interaction and interface

Detailed explanation of php WeChat public platform interaction and interface

May 30, 2018 am 11:49 AM
php interface Detailed explanation

This article mainly introduces the development, interaction and interface of PHP WeChat public platform in detail. It has certain reference value. Interested friends can refer to it.

This article is divided into three parts: Everyone will introduce it. The specific content is as follows

1. Interaction between WeChat users, WeChat servers and backend servers

Example: WeChat users send a text message to the public account. This A message will first be sent to the WeChat server. The WeChat server processes the information and passes it to the backend server in XML data format. After receiving the data, the backend server will process the data, and then the response data will be passed to the WeChat server in XML data format. , the WeChat server then responds to the user WeChat interface.
The interaction process between WeChat users and the WeChat backend server is the data transfer process, but it only needs to go through the WeChat server as a transfer station.

So what is the use of the WeChat server as a transfer station?
The xml data is processed and packaged and displayed on the mobile phone screen. The graphic messages we accept are as follows:

Single graphic message:

Multiple graphic messages

You will find that almost all pictures and texts on WeChat are in this format, with the same format and size. This is the result after being packaged by the WeChat server.

2. Interactive data types

Data types that WeChat users can send
1. Text type (text)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
Copy after login

2. Voice (voice)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<Format><![CDATA[amr]]></Format>
<MsgId>5836982871638042400</MsgId>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
<Recognition><![CDATA[]]></Recognition>//recognition表示语音识别的结果
</xml>
Copy after login

3. Picture (img)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<PicUrl><![CDATA[http://mmbiz.qpic.cn/mmbiz/L4qjYtOibummHn90t1mnaibYiaR8ljyicF3MW7XX3BLp1qZgUb7CtZ0D]]></PicUrl>
<MsgId>5836982871638042400</MsgId>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
</xml>
Copy after login

Every message sent to the WeChat server will be marked with a MsgId, and uploaded pictures, videos, voices, etc. will also be marked with a mediaId .

4. Video

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[vedio]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
<ThumbMediaId><![CDATA[mxUJ5gcCeesJwx2T9qsk62YzI
clCP_HnRdfTQcojlPeT2G9Q3d22UkSLyBFLZ01J]]></ThumbMediald>;//视频静止时显示那张图片地址
</xml>
Copy after login

5. Location message (location)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[location]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Location_X>22.539968</Location_X>
<Location_Y>113.954980</Location_Y>
<Scale>16</Scale>
<Label><![CDATA[中国广东省深圳市南山区深南大道9001号 
邮政编码: 518053]]></Label>
</xml>
Copy after login

6. Link message (link)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[link]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Title><![CDATA[微信公众平台开发者的江湖]]></Title>
<Description><![CDATA[陈坤的微信公众号这段时间大火,大家...]]></Description>
<Url><![CDATA[http://www.cnblogs.com/txw1958/]]></Url>
<MsgId>5839907284805129867</MsgId>
</xml>
Copy after login

Backend server response Message type
1, text type (text)
2, voice (voice)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Voice>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
</Voice>
</xml>
Copy after login

3, picture (img)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Image>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
</Image>
</xml>
Copy after login

4. Video

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[vedio]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<video>
<MediaId><![CDATA[PGKsO3LAgbVTsFYO7FGu51KUYa07D0C_Nozz2fn1z6VYtHOsF59PTFl0vagGxkVH]]></MediaId>
<ThumbMediaId><![CDATA[mxUJ5gcCeesJwx2T9qsk62YzI
clCP_HnRdfTQcojlPeT2G9Q3d22UkSLyBFLZ01J]]></ThumbMediald>;//视频静止时显示那张图片地址
</video>
</xml>
Copy after login

5 , music (music)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Music>
<Title><![CDATA[最炫民族风]]></Title>
<Description><![CDATA[凤凰传奇]]></Description>
<MusicUrl><![CDATA[http://zj189.cn/zj/download/music/zxmzf.mp3]]></MusicUrl>
<HQMusicUrl><![CDATA[http://zj189.cn/zj/dodownload/music/zxmzf.mp3]]></HQMusicUrl>
</Music>
</xml>
Copy after login

6, graphics (news)

<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<MsgId>5836982871638042400</MsgId>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
<item>
<Title><![CDATA[ 【深圳】实况 温度:6℃ 湿度:62﹪ 风速:东北风2级]]></Title>
<Description><![CDATA[]]></Description>
<PicUrl><![CDATA[http://www.doucube.com/weixin/weather/icon/banner.jpg]]></PicUrl>
<Url><![CDATA[]]></Url>
</item>
<item>
<Title><![CDATA[ 【深圳】实况 温度:6℃ 湿度:62﹪ 风速:东北风2级]]></Title>
<Description><![CDATA[]]></Description>
<PicUrl><![CDATA[http://www.doucube.com/weixin/weather/icon/banner.jpg]]></PicUrl>
<Url><![CDATA[]]></Url>
</item>
</Articles>
</xml>
Copy after login

The above code is only for reference in data filling. The above code can be called when needed. Here we just show you the following data format.
CDATA is a tag, and the text data marked by it will not be parsed by the xml parser. A CDATA component starts with "

ToUserName Receiver Account
FromUserName Sender Account
CreateTime Send Event
MsgType Data Type
Content Text Content
ArticleCount Number of Images and Texts
MsgId Data id
MediaId Media id
Title Title
Description Description
MusicUrl Music connection address
HQMusicUrl High-quality music connection address

2. Specific interaction steps That is, the code

In Figure 2 of the previous chapter, we defined the url and token for the test account. The url is the backend server address for communicating with the WeChat server, and a token is equivalent to a token. The token will be presented when the WeChat server communicates with the backend server. If the backend server finds that the WeChat server is the same as the token it carries, it will communicate. If it is not the same, it will refuse the communication. This process is called token verification (this token is not a token) value).
The above is more vivid, I will explain it through the code below
For example: the url is http://weixinceshi111111.applinzi.com/index2.php
token: weixin
index2.php code

responseMsg();//响应数据
}else{
 $wechatObj->valid();//响应
}

class wechatCallbackapiTest
{
 public function valid()
 {
 $echoStr = $_GET["echostr"];
 if($this->checkSignature()){
 echo $echoStr;
 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;
 }
 }

 public function responseMsg()
 {
 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//获取发送过来的数据。
 if (!empty($postStr)){
 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', );//把xml字符串载入到一个SimpleXMLelement对象中。simplexml_load_string()是一种xml解析器。
 $RX_TYPE = trim($postObj->MsgType);//trim去掉字符串两端kongge。

 //用户发送的消息类型判断
 switch ($RX_TYPE)
 {
 case "text":
  $result = $this->receiveText($postObj);
  break;
 case "image":
  $result = $this->receiveImage($postObj);
  break;
 case "voice":
  $result = $this->receiveVoice($postObj);
  break;
 case "video":
  $result = $this->receiveVideo($postObj);
  break;
 default:
  $result = "unknow msg type: ".$RX_TYPE;
  break;
 }
 echo $result;
 }else {
 echo "";
 exit;
 }
 }

 private function receiveText($object)
 {
 $keyword = trim($object->Content);

 if($keyword == "文本"){
 //回复文本消息
 $content = "这是个文本消息";
 $result = $this->transmitText($object, $content);
 }
 else if($keyword == "图文" || $keyword == "单图文"){
 //回复单图文消息
 $content = array();
 $content[] = array("Title"=>"单图文标题", 
  "Description"=>"单图文内容", 
  "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", 
  "Url" =>"http://m.cnblogs.com/?u=txw1958");
 $result = $this->transmitNews($object, $content);
 }
 else if($keyword == "多图文"){
 //回复多图文消息
 $content = array();
 $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
 $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
 $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
 $result = $this->transmitNews($object, $content);

 }
 else if($keyword == "音乐"){
 //回复音乐消息
 $content = array("Title"=>"最炫民族风", 
 "Description"=>"歌手:凤凰传奇", 
 "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3",
 "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
 $result = $this->transmitMusic($object, $content);
 }

 return $result;
 }

 private function receiveImage($object)
 {
 //回复图片消息 
 $content = array("MediaId"=>$object->MediaId);
 $result = $this->transmitImage($object, $content);;
 return $result;
 }

 private function receiveVoice($object)
 {
 //回复语音消息 
 $content = array("MediaId"=>$object->MediaId);
 $result = $this->transmitVoice($object, $content);;
 return $result;
 }

 private function receiveVideo($object)
 {
 //回复视频消息 
 $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
 $result = $this->transmitVideo($object, $content);;
 return $result;
 } 

 /*
 * 回复文本消息,将要回复的xml消息进行包装。
 */
 private function transmitText($object, $content)
 {
 $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);//sprintf()这个函数的作用还是比较有意思的,可以搜索看看。
 return $result;
 }

 /*
 * 回复图片消息
 */
 private function transmitImage($object, $imageArray)
 {
 $itemTpl = "
 
";

 $item_str = sprintf($itemTpl, $imageArray['MediaId']);

 $textTpl = "


%s

$item_str
";

 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
 return $result;
 }

 /*
 * 回复语音消息
 */
 private function transmitVoice($object, $voiceArray)
 {
 $itemTpl = "
 
";

 $item_str = sprintf($itemTpl, $voiceArray['MediaId']);

 $textTpl = "


%s

$item_str
";

 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
 return $result;
 }

 /*
 * 回复视频消息
 */
 private function transmitVideo($object, $videoArray)
 {
 $itemTpl = "";

 $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

 $textTpl = "


%s

$item_str
";

 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
 return $result;
 }

 /*
 * 回复图文消息
 */
 private function transmitNews($object, $arr_item)
 {
 if(!is_array($arr_item))
 return;

 $itemTpl = " 
 <![CDATA[%s]]>
 
 
 
 
";
 $item_str = "";
 foreach ($arr_item as $item)
 $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

 $newsTpl = "


%s


%s

$item_str
";

 $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
 return $result;
 }

 /*
 * 回复音乐消息
 */
 private function transmitMusic($object, $musicArray)
 {
 $itemTpl = "
 <![CDATA[%s]]>
 
 
 
";

 $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

 $textTpl = "


%s

$item_str
";

 $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
 return $result;
 }
}
?>
Copy after login

3. Interface

3.1 What is the interface

The interface is equivalent to a tool with specific functions. For example, when you need to drill holes in the wall when building a house, you will use a drill tool to drill. From the time you bring the tool to the completion of the drilling, you You need to complete a series of steps such as plugging in, calibrating, drilling, etc., and finally achieve your goal. The drill is our interface, and plugging in, calibrating, and drilling are the steps we use to call the tools to complete the purpose.

An example of WeChat's creation menu interface.

Steps to call the interface:
1. Obtain the connection address of the WeChat menu interface and establish a dialogue with this interface through the curl function.
2. Create Menu data is sent to this interface.
After the interface call is completed, this interface will automatically process the data and generate a menu on the WeChat public good page.

Please see the next chapter for how to call the WeChat interface: WeChat public platform development (3): Calling the WeChat advanced interface.

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations: The difference between constants, static properties, and non-static properties in

php

#phpClasses and objects: Detailed graphic explanation of static properties and static methods

phpThe difference between static properties and static methods

The above is the detailed content of Detailed explanation of php WeChat public platform interaction and interface. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles