企微短剧业务系统

TemplateController.php 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if(empty($component)) {
  20. return self::returnValue([], 1001);
  21. }
  22. $this->aesKey = $component['aes_key'];
  23. $this->authToken = $component['auth_token'];
  24. }
  25. /**
  26. * 消息与事件接收
  27. * */
  28. public function receive(Request $request)
  29. {
  30. $msgSign = trim($request->input('msg_signature'));
  31. $timestamp = trim($request->input('timestamp'));
  32. $nonce = trim($request->input('nonce'));
  33. if($request->isMethod('get')) { // 初步校验回调链接合法性
  34. $echoStr = trim($request->input('echostr'));
  35. $encryptMsg = ""; // 解析之后的明文
  36. $crypt = new \WXBizMsgCrypt($this->authToken, $this->aesKey, $this->corpid);
  37. $errCode = $crypt->VerifyURL($msgSign, $timestamp, $nonce, $echoStr, $encryptMsg);
  38. if($errCode == 0) {
  39. echo $encryptMsg;
  40. } else {
  41. # 解密失败,写入日志
  42. Log::logError($echoStr, [
  43. 'msgSign' => $msgSign,
  44. 'timestamp' => $timestamp,
  45. 'nonce' => $nonce,
  46. 'err_code' => $errCode
  47. ], 'MsgReceiveDecrypt-Get');
  48. }
  49. exit;
  50. } else { // 数据回调通知
  51. $str = file_get_contents('php://input');
  52. $encryptMsg = ""; // 解析之后的明文
  53. try {
  54. $crypt = new \WXBizMsgCrypt($this->authToken, $this->aesKey, $this->appTemplateId);
  55. $encrypt = getInfoFromXMl($str, 'Encrypt');
  56. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  57. $from_xml = sprintf($format, $encrypt);
  58. $errCode = $crypt->decryptMsg($msgSign, $timestamp, $nonce, $from_xml, $encryptMsg);
  59. Log::logInfo($encryptMsg, []);
  60. if($errCode == 0) {
  61. TemplateCallbackService::responseCommand($encryptMsg);
  62. echo 'success';
  63. exit;
  64. } else {
  65. Log::logError('verifyTicket获取失败', ['errCode' => $errCode], 'TemplateVerifyTicketGetFail');
  66. }
  67. } catch (\Exception $e) {
  68. Log::logError('事件信息捕获异常', [
  69. 'msg' => $e->getMessage(),
  70. 'line' => $e->getLine(),
  71. ],'TemplateEventGet');
  72. }
  73. echo "success";
  74. }
  75. }
  76. }