XMLParse.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace weworkapi\receive;
  3. use weworkapi\receive\ErrorCode;
  4. use \DOMDocument;
  5. /**
  6. * XMLParse class
  7. *
  8. * 提供提取消息格式中的密文及生成回复消息格式的接口.
  9. */
  10. class XMLParse
  11. {
  12. /**
  13. * 提取出xml数据包中的加密消息
  14. * @param string $xmltext 待提取的xml字符串
  15. * @return string 提取出的加密消息字符串
  16. */
  17. public function extract($xmltext)
  18. {
  19. try {
  20. $xml = new DOMDocument();
  21. $xml->loadXML($xmltext);
  22. $array_e = $xml->getElementsByTagName('Encrypt');
  23. $encrypt = $array_e->item(0)->nodeValue;
  24. return array(0, $encrypt);
  25. } catch (Exception $e) {
  26. print $e . "\n";
  27. return array(ErrorCode::$ParseXmlError, null);
  28. }
  29. }
  30. /**
  31. * 生成xml消息
  32. * @param string $encrypt 加密后的消息密文
  33. * @param string $signature 安全签名
  34. * @param string $timestamp 时间戳
  35. * @param string $nonce 随机字符串
  36. */
  37. public function generate($encrypt, $signature, $timestamp, $nonce)
  38. {
  39. $format = "<xml>
  40. <Encrypt><![CDATA[%s]]></Encrypt>
  41. <MsgSignature><![CDATA[%s]]></MsgSignature>
  42. <TimeStamp>%s</TimeStamp>
  43. <Nonce><![CDATA[%s]]></Nonce>
  44. </xml>";
  45. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  46. }
  47. }
  48. //
  49. // Test
  50. /*
  51. $sPostData = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><AgentID><![CDATA[toAgentID]]></AgentID><Encrypt><![CDATA[msg_encrypt]]></Encrypt></xml>";
  52. $xmlparse = new XMLParse;
  53. $array = $xmlparse->extract($sPostData);
  54. var_dump($array);
  55. */
  56. ?>