XMLParse.php 1.3 KB

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