Home  >  Article  >  Backend Development  >  PHP WeChat public platform interaction and interface detailed explanation_php example

PHP WeChat public platform interaction and interface detailed explanation_php example

WBOY
WBOYOriginal
2016-12-05 13:28:24999browse

This article is divided into three parts for everyone to introduce. The specific content is as follows

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

Example: A WeChat user sends a text message to the official account. This message will first be sent to the WeChat server. The WeChat server processes the message and passes it to the backend server in xml data format. The backend server will process the data after receiving the data. After processing, the response data is passed to the WeChat server in xml data format, and the WeChat server then responds to the user's 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 picture and text:

Multiple pictures and text

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

2. Interactive data types

Types of data that WeChat users can send
1. Text




%s


";

2. Voice




%s


5836982871638042400

//recognition表示语音识别的结果

3. Picture (img)




%s


5836982871638042400


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

4. Video




%s

5836982871638042400

;//视频静止时显示那张图片地址

5. Geolocation message (location)




%s

5836982871638042400
22.539968
113.954980
16


6. Link message (link)




%s

5836982871638042400
<![CDATA[微信公众平台开发者的江湖]]>


5839907284805129867

Message type responded by the background server
1. Text
2. Voice




%s

5836982871638042400




3. Picture (img)




%s

5836982871638042400




4. Video




%s

5836982871638042400


5. Music




%s

5836982871638042400

<![CDATA[最炫民族风]]>





6. Pictures and text (news)




%s

5836982871638042400

%s


<![CDATA[ 【深圳】实况 温度:6℃ 湿度:62﹪ 风速:东北风2级]]>





<![CDATA[ 【深圳】实况 温度:6℃ 湿度:62﹪ 风速:东北风2级]]>






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 pictures 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 are codes

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 WeChat server will present this token when communicating 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 the value of the token).
The above is more vivid, let me explain it through code below
For example: the url is http://weixinceshi111111.applinzi.com/index2.php
token:weixin
index2.php code

<?php
//
// 响应用户消息
// 微信公众账号响应给用户的不同消息类型
//微信服务器要和后台服务器进行通信首先要进行token验证,微信会通过get方式发送signature(微信加密签名)、nonce(随机数)、timestamp(时间戳)、echostr(随机字符串)。后台服务器获取之后会将timestamp、nonce与自身定义的TOKEN按照一定的顺序拼接成字符串,通过shal加密后获得的结果与signature进行对比,如果相同则把echostr返回给微信服务器。 表示验证成功。
header("content-type:text;charset=utf8");
define("TOKEN", "weixin");
//token验证是通过get传输数据,微信用户发送的数据通过post方式发送。先进行get请求,再进行post请求。
$wechatObj = new wechatCallbackapiTest();
//判断是get请求还是post请求。$_GET['echostr']如果存在,表示是进行token验证的get请求。反之是传输数据的post请求。
if (!isset($_GET['echostr'])) {
 $wechatObj->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 = "


%s


";
 $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;
 }
}
?>

3.Interface

3.1 What is the interface

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

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. Send the creation menu data 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.

For the calling method of WeChat interface, please see the next chapter: WeChat public platform development (3): Calling of WeChat advanced interface.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

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