WXBizMsgCryptTest.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Tests\Common\Support\Wechat\Crypt;
  3. use Modules\Common\Support\Wechat\Crypt\WXBizMsgCrypt;
  4. use PHPUnit\Framework\TestCase;
  5. use Tests\UsedTestCase;
  6. class WXBizMsgCryptTest extends UsedTestCase
  7. {
  8. public function testDemo() {
  9. // 第三方发送消息给公众平台
  10. $encodingAesKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
  11. $token = "pamtest";
  12. $timeStamp = "1409304348";
  13. $nonce = "xxxxxx";
  14. $appId = "wxb11529c136998cb6";
  15. $text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";
  16. $pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
  17. $encryptMsg = '';
  18. $errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
  19. if ($errCode == 0) {
  20. print("加密后: " . $encryptMsg . "\n");
  21. } else {
  22. print($errCode . "\n");
  23. }
  24. $xml_tree = new \DOMDocument();
  25. $xml_tree->loadXML($encryptMsg);
  26. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  27. $array_s = $xml_tree->getElementsByTagName('MsgSignature');
  28. $encrypt = $array_e->item(0)->nodeValue;
  29. $msg_sign = $array_s->item(0)->nodeValue;
  30. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  31. $from_xml = sprintf($format, $encrypt);
  32. // 第三方收到公众号平台发送的消息
  33. $msg = '';
  34. $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
  35. if ($errCode == 0) {
  36. print("解密后: " . $msg . "\n");
  37. $xml = simplexml_load_string($msg, "SimpleXMLElement", LIBXML_NOCDATA);
  38. $json = json_encode($xml);
  39. $array = json_decode($json,TRUE);
  40. dump($array);
  41. } else {
  42. print($errCode . "\n");
  43. }
  44. }
  45. }