企微短剧业务系统

EventController.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Log;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. include '../app/Libs/qyWeChatSDK/WXBizMsgCrypt.php';
  7. class EventController extends Controller
  8. {
  9. private $aesKey;
  10. private $authToken;
  11. /*
  12. * 初始化
  13. * */
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. $component = config('qyWechat.suite_info');
  18. if(empty($component)) {
  19. return self::returnValue([], 1001);
  20. }
  21. $this->aesKey = $component['aes_key'];
  22. $this->authToken = $component['auth_token'];
  23. }
  24. /**
  25. * 消息与事件接收
  26. * */
  27. public function receive(Request $request)
  28. {
  29. $msgSign = trim($request->input('msg_signature'));
  30. $timestamp = trim($request->input('timestamp'));
  31. $nonce = trim($request->input('nonce'));
  32. if($request->isMethod('get')) { // 初步校验回调链接合法性
  33. $echoStr = trim($request->input('echostr'));
  34. $encryptMsg = ""; // 解析之后的明文
  35. $crypt = new \WXBizMsgCrypt($this->authToken, $this->aesKey, $this->corpid);
  36. $errCode = $crypt->VerifyURL($msgSign, $timestamp, $nonce, $echoStr, $encryptMsg);
  37. if($errCode == 0) {
  38. echo $encryptMsg;
  39. } else {
  40. # 解密失败,写入日志
  41. Log::logError($echoStr, [
  42. 'msgSign' => $msgSign,
  43. 'timestamp' => $timestamp,
  44. 'nonce' => $nonce,
  45. 'err_code' => $errCode
  46. ], 'MsgReceiveDecrypt-Get');
  47. }
  48. exit;
  49. } else { // 数据回调通知
  50. $str = file_get_contents('php://input');
  51. // Log::logInfo($str, []);
  52. $encryptMsg = ""; // 解析之后的明文
  53. try {
  54. $crypt = new \WXBizMsgCrypt($this->authToken, $this->aesKey, $this->corpid);
  55. $encrypt = getInfoFromXMl($str, 'Encrypt');
  56. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  57. $from_xml = sprintf($format, $encrypt);
  58. $result = $crypt->decryptMsg($msgSign, $timestamp, $nonce, $from_xml, $encryptMsg);
  59. // Log::logInfo($encryptMsg, []);
  60. } catch (\Exception $e) {
  61. Log::logError('事件信息捕获异常', [
  62. 'msg' => $e->getMessage(),
  63. 'line' => $e->getLine(),
  64. ],'EventGet');
  65. }
  66. echo "";
  67. }
  68. }
  69. }