微信開發(2)-被動回覆用戶消息

配置好上一篇的服務器之後,用戶發送消息,就會自動post提交到我們配置的地址,我們可以通過file_get_contents(“php://input”)獲取微信提交過來的數據,使用simplexml_load_string()把xml數據轉成SimpleXMLElement 對象,代碼如下

$postStr = file_get_contents("php://input");
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

測試的時候發現微信會回調兩次,解出來的數據是這樣的

SimpleXMLElement::__set_state(array(
   'ToUserName' => 'fsfsdfsdfsd',
   'FromUserName' => 'dfwfsfsdfsdfsd',
   'CreateTime' => '1590742768',
   'MsgType' => 'event',
   'Event' => 'location_select',
   'EventKey' => 'rselfmenu_2_0',
   'SendLocationInfo' => 
  SimpleXMLElement::__set_state(array(
     'Location_X' => 'xxxx',
     'Location_Y' => 'xxxx',
     'Scale' => '15',
     'Label' => 'xxxxx',
     'Poiname' => 'xxxxxx',
  )),
SimpleXMLElement::__set_state(array(
   'ToUserName' => 'fsfsdfsdfsd',
   'FromUserName' => 'dfwfsfsdfsdfsd',
   'CreateTime' => '1590742768',
   'MsgType' => 'location',
   'Location_X' => 'xxxx',
   'Location_Y' => 'xxxx',
   'Scale' => '15',
   'Label' => 'xxxx',
   'MsgId' => 'xxxx',
))

第二次的是我們需要的,我這個是給公衆號發送的定位,MsgType類型是location,除了這種還有text,image,voice等等
然後就是根據傳過來的數據處理邏輯,把想要返回給用戶的數據備好

$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, $fromUserName, $toUserName, time(), $content);

ToUserName是要發送的用戶的openid,fromUserName是微信號,直接把微信提交過來的數據拿來用就可以了,不過記得要把兩者的位置調換一下,因爲微信接收信息的時候是作爲接收者,用戶作爲發送者,回覆用戶的時候微信是作爲發送者,用戶是作爲接收者。
sprintf會把數據轉成xml數據,然後直接echo用戶就可以收到了
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章