WechatOpenPlatformController.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. <?php
  2. namespace Modules\Channel\Http\Controllers;
  3. use Catch\Base\CatchController;
  4. use EasyWeChat\OpenPlatform\Application;
  5. use Illuminate\Foundation\Validation\ValidatesRequests;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Redis;
  10. use Modules\Channel\Models\WechatAuthorizationInfo;
  11. use Modules\Channel\Services\WechatOpenPlatform\WechatOpenPlatformService;
  12. use Modules\Common\Errors\Errors;
  13. use Modules\Common\Exceptions\CommonBusinessException;
  14. use Modules\User\Http\Controllers\UserTrait;
  15. use Symfony\Component\Cache\Adapter\RedisAdapter;
  16. class WechatOpenPlatformController extends CatchController
  17. {
  18. use UserTrait;
  19. use ValidatesRequests;
  20. /**
  21. * 三方授权跳转页
  22. * @param Request $request
  23. * @return string
  24. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  25. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  26. * @throws \Illuminate\Validation\ValidationException
  27. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  28. * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
  29. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  30. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  31. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  32. */
  33. public function preauth(Request $request) {
  34. $this->validate($request, [
  35. 'user_id' => 'required'
  36. ]);
  37. $currentUser = $this->getCurrentUser();
  38. $componentInfo = WechatOpenPlatformService::getComponentInfoByCompanyUid($currentUser->id);
  39. $app = WechatOpenPlatformService::buildApplication($componentInfo);
  40. $user_id = $request->input('user_id');
  41. $url = $app->createPreAuthorizationUrl(sprintf('%s/api/channel/openPlatform/auth/%s/%s',config('app.url'), $componentInfo->app_id, $user_id), []);
  42. return $url;
  43. }
  44. /**
  45. * 三方授权回调
  46. * @param Request $request
  47. * @param $component_appid
  48. * @param $user_id
  49. * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
  50. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  51. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  52. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  53. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  54. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  55. */
  56. public function auth(Request $request, $component_appid, $user_id) {
  57. $auth_code = $request->input('auth_code');
  58. $auth_user = DB::table('users')
  59. ->where([
  60. 'id' => $user_id, 'deleted_at' => 0, 'status' => 1
  61. ])
  62. ->where('pid', '<>', 0)
  63. ->select('pid', 'id')->first();
  64. if(!$auth_user) {
  65. CommonBusinessException::throwError(Errors::OPENPLATFORM_OPTIMIZER_INFO_ERROR);
  66. }
  67. $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
  68. $app = WechatOpenPlatformService::buildApplication($componentInfo);
  69. $client = $app->getClient();
  70. $response = $client->postJson('/cgi-bin/component/api_query_auth', [
  71. 'component_appid' => $component_appid,
  72. 'authorization_code' => $auth_code
  73. ]);
  74. $parsedContent = \json_decode($response->getContent(), true);
  75. $authorizer_appid = $parsedContent['authorization_info']['authorizer_appid'];
  76. $authorizer_refresh_token = $parsedContent['authorization_info']['authorizer_refresh_token'];
  77. $response = $client->postJson('/cgi-bin/component/api_get_authorizer_info', [
  78. 'component_appid' => $component_appid,
  79. 'authorizer_appid' => $authorizer_appid
  80. ]);
  81. $parsedContent = \json_decode($response->getContent(), true);
  82. WechatAuthorizationInfo::updateOrCreate([
  83. 'authorizer_appid' => $authorizer_appid,
  84. 'component_appid' => $component_appid,
  85. 'user_id' => $user_id,
  86. 'puser_id' => $auth_user->pid,
  87. ], [
  88. 'authorizer_refresh_token' => $authorizer_refresh_token,
  89. 'nick_name' => $parsedContent['authorizer_info']['nick_name'],
  90. ]);
  91. return view('wechat.openPlatform.authSuccess')->with('url', sprintf('%s/#/user/advertiser',config('app.url')));
  92. }
  93. /**
  94. * 处理授权事件
  95. * @param Request $request
  96. * @param $component_appid
  97. */
  98. public function authorCommand(Request $request, $component_appid) {
  99. $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
  100. $app = WechatOpenPlatformService::buildApplication($componentInfo);
  101. $server = $app->getServer();
  102. $server->handleAuthorized(function($message, \Closure $next) {
  103. myLog('authorCommand')->info('handleAuthorized', ['message' => $message]);
  104. return $next($message);
  105. });
  106. $server->handleUnauthorized(function($message, \Closure $next) {
  107. WechatOpenPlatformService::handleUnauthorized($message);
  108. return $next($message);
  109. });
  110. return $server->serve();
  111. }
  112. public function infoCommand(Request $request, $authorizer_appid, $component_appid) {
  113. $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
  114. $app = WechatOpenPlatformService::buildApplication($componentInfo);
  115. myLog("wx-xiaoxi")->info('-------开始处理---'.get_date());
  116. $server = $app->getServer();
  117. $message = $server->getDecryptedMessage();
  118. myLog("wx-xiaoxi")->info([
  119. 'authorizer_appid' => $authorizer_appid,
  120. 'component_appid' => $component_appid,
  121. 'param' => $request->all(),
  122. 'msg' => $message,
  123. ]);
  124. $refreshToken = WechatOpenPlatformService::getRefreshToken($authorizer_appid,$component_appid);
  125. $server = $app->getOfficialAccountWithRefreshToken($authorizer_appid, $refreshToken)->getServer();
  126. $server->addMessageListener('text', function($message) {
  127. myLog("wx-xiaoxi")->info('----文本消息---');
  128. if ($message->Content == "pk"){
  129. return $message->FromUserName;
  130. }
  131. });
  132. $server->addEventListener('subscribe', function() { });
  133. myLog("wx-xiaoxi")->info('-------结束处理---'.get_date());
  134. return $server->serve();
  135. }
  136. }