Nav apraksta

TemplateController.php 2.9KB

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