Heim  >  Artikel  >  Backend-Entwicklung  >  PHP WeChat öffentliche Plattforminteraktion und Schnittstelle, detaillierte Erklärung_php-Beispiel

PHP WeChat öffentliche Plattforminteraktion und Schnittstelle, detaillierte Erklärung_php-Beispiel

WBOY
WBOYOriginal
2016-12-05 13:28:241066Durchsuche

Dieser Artikel ist in drei Teile gegliedert, damit jeder ihn vorstellen kann. Der spezifische Inhalt ist wie folgt

1. Interaktion zwischen WeChat-Benutzern, WeChat-Server und Backend-Server

Beispiel: Ein WeChat-Benutzer sendet eine Textnachricht an den WeChat-Server. Der WeChat-Server verarbeitet die Nachricht und leitet sie im XML-Datenformat weiter Wenn die Daten empfangen werden, werden die Daten verarbeitet, und dann werden die Antwortdaten im XML-Datenformat an den WeChat-Server übergeben, und der WeChat-Server antwortet dann auf die WeChat-Schnittstelle des Benutzers.
Der Interaktionsprozess zwischen WeChat-Benutzern und dem WeChat-Backend-Server ist der Datenübertragungsprozess, der jedoch nur über den WeChat-Server als Übertragungsstation erfolgen muss.

Wozu dient der WeChat-Server also als Übergabestation?
Die XML-Daten werden verarbeitet und verpackt und auf dem Bildschirm des Mobiltelefons angezeigt. Die von uns akzeptierten grafischen Nachrichten lauten wie folgt:

Einzelnes Bild und Text:

Mehrere Bilder und Text

Sie werden feststellen, dass fast alle Bilder und Texte auf WeChat in diesem Format vorliegen und dasselbe Format und dieselbe Größe haben. Dies ist das Ergebnis nach der Verpackung durch den WeChat-Server.

2. Interaktive Datentypen

Datentypen, die WeChat-Benutzer senden können
1. Texttyp (Text)

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

2. Stimme

<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>

3. Bild (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>

Jede an den WeChat-Server gesendete Nachricht wird mit einer MsgId markiert, und hochgeladene Bilder, Videos, Stimmen usw. werden ebenfalls mit einer MediaId markiert.

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>

5. Geolocation-Nachricht (Standort)

<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>

6. Linknachricht (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>

Nachrichtentyp, auf den der Hintergrundserver reagiert hat
1. Texttyp (Text)
2. Stimme

<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>

3. Bild (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>

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>

5. Musik

<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>

6. Bilder und Text (Neuigkeiten)

<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>

Der obige Code dient nur als Referenz beim Ausfüllen von Daten. Der obige Code kann bei Bedarf aufgerufen werden. Hier zeigen wir Ihnen nur das folgende Datenformat.
CDATA ist ein Tag und die dadurch markierten Textdaten werden vom XML-Parser nicht analysiert. Eine CDATA-Komponente beginnt mit „

ToUserName Receiver Account
FromUserName Absenderkonto
CreateTime-Sendeereignis
MsgType-Datentyp
Inhalt Textinhalt
ArticleCount Anzahl der Bilder und Texte
MsgId-Daten-ID
MediaId Medien-ID
Titel Titel
Beschreibung Beschreibung
MusicUrl Musikverbindungsadresse
HQMusicUrl Hochwertige Musikverbindungsadresse

2. Spezifische Interaktionsschritte sind Codes

In Abbildung 2 des vorherigen Kapitels haben wir die URL und das Token für das Testkonto definiert. Die URL ist die Back-End-Serveradresse für die Kommunikation mit dem WeChat-Server, und ein Token entspricht einem Token. Der WeChat-Server präsentiert dieses Token, wenn er mit dem Backend-Server kommuniziert. Wenn der Backend-Server feststellt, dass der WeChat-Server mit dem Token übereinstimmt, den er trägt, wird er die Kommunikation verweigern. Dieser Vorgang wird als Token-Verifizierung bezeichnet (dieser Token ist nicht der Wert des Tokens).
Das Obige ist anschaulicher, lassen Sie es mich durch den folgenden Code erklären
Beispiel: Die URL lautet http://weixinceshi111111.applinzi.com/index2.php
Token: weixin
index2.php-Code

<&#63;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/&#63;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/&#63;u=txw1958");
 $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/&#63;u=txw1958");
 $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/&#63;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 = "<Image>
 <MediaId><![CDATA[%s]]></MediaId>
</Image>";

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

 $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

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

 /*
 * 回复语音消息
 */
 private function transmitVoice($object, $voiceArray)
 {
 $itemTpl = "<Voice>
 <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

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

 $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

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

 /*
 * 回复视频消息
 */
 private function transmitVideo($object, $videoArray)
 {
 $itemTpl = "<Video>
 <MediaId><![CDATA[%s]]></MediaId>
 <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
 <Title><![CDATA[%s]]></Title>
 <Description><![CDATA[%s]]></Description>
</Video>";

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

 $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

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

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

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

 $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

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

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

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

 $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

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

3. Schnittstelle

3.1 Was ist die Schnittstelle

Die Schnittstelle entspricht einem Tool mit spezifischen Funktionen. Wenn Sie beispielsweise beim Hausbau Löcher in die Wand bohren müssen, verwenden Sie zum Bohren von Löchern ein Bohrwerkzeug. Vom Herausholen der Werkzeuge bis zum Abschluss des Bohrens müssen Sie eine Reihe von Schritten wie Einstecken, Kalibrieren und Bohren durchführen, um schließlich Ihr Ziel zu erreichen. Das Bohrgerät ist unsere Schnittstelle, und Anschließen, Kalibrieren und Bohren sind die Schritte, die wir als Werkzeuge bezeichnen, um den Zweck zu erfüllen.

Ein Beispiel für die WeChat-Erstellungsmenüoberfläche.

Schritte zum Aufrufen der Schnittstelle:
1. Ermitteln Sie die Verbindungsadresse der WeChat-Menüoberfläche und stellen Sie über die Curl-Funktion einen Dialog mit dieser Schnittstelle her.
2. Senden Sie die Erstellungsmenüdaten an diese Schnittstelle.
Nachdem der Schnittstellenaufruf abgeschlossen ist, verarbeitet diese Schnittstelle automatisch die Daten und generiert ein Menü auf der öffentlichen WeChat-Seite.

Informationen zum Aufrufen der WeChat-Schnittstelle finden Sie im nächsten Kapitel: Entwicklung der öffentlichen WeChat-Plattform (3): Aufrufen der erweiterten WeChat-Schnittstelle.

Das Obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, dass er für das Studium aller hilfreich sein wird. Ich hoffe auch, dass jeder Script House unterstützt.

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn