1
0

XMLParse.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace wx\offiaccount\event;
  3. use DOMDocument;
  4. use Exception;
  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. $array_a = $xml->getElementsByTagName('ToUserName');
  24. $encrypt = $array_e->item(0)->nodeValue;
  25. $tousername = $array_a->item(0)->nodeValue;
  26. return array(0, $encrypt, $tousername);
  27. } catch (Exception $e) {
  28. //print $e . "\n";
  29. return array(ErrorCode::$ParseXmlError, null, null);
  30. }
  31. }
  32. /**
  33. * 生成xml消息
  34. * @param string $encrypt 加密后的消息密文
  35. * @param string $signature 安全签名
  36. * @param string $timestamp 时间戳
  37. * @param string $nonce 随机字符串
  38. */
  39. public function generate($encrypt, $signature, $timestamp, $nonce)
  40. {
  41. $format = "<xml>
  42. <Encrypt><![CDATA[%s]]></Encrypt>
  43. <MsgSignature><![CDATA[%s]]></MsgSignature>
  44. <TimeStamp>%s</TimeStamp>
  45. <Nonce><![CDATA[%s]]></Nonce>
  46. </xml>";
  47. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  48. }
  49. }