Wechat.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2020/6/11
  6. * Time: 下午5:03
  7. */
  8. namespace app\api\controller\v1;
  9. use app\common\library\WeChatObject;
  10. use app\main\constants\ErrorCodeConstants;
  11. use app\main\service\LogService;
  12. use app\main\service\OpenPlatformService;
  13. use EasyWeChat\Kernel\Exceptions\HttpException;
  14. use Psr\SimpleCache\InvalidArgumentException;
  15. use think\Request;
  16. class Wechat extends Init
  17. {
  18. /**
  19. * 获取渠道token
  20. */
  21. public function token()
  22. {
  23. $admin_id = Request::instance()->param('admin_id');
  24. LogService::info('getToken:admin_id:' . $admin_id);
  25. if (!$admin_id) {
  26. $this->setMsg('缺少参数')->setCode(ErrorCodeConstants::PARAMS_ERROR_EMPTY)->getReturn();
  27. }
  28. $adminConfig = model('AdminConfig')->getAdminInfoAll($admin_id);
  29. if (!$adminConfig) {
  30. $this->setMsg('参数无效')->setCode(ErrorCodeConstants::PARAMS_ERROR_INVALID)->getReturn();
  31. }
  32. $wechat = new WeChatObject($adminConfig);
  33. $officialAccount = $wechat->getOfficialAccount();
  34. if (!$officialAccount) {
  35. $this->setMsg('账号未授权')->setCode(ErrorCodeConstants::PERMISSION_DENY)->getReturn();
  36. }
  37. try {
  38. $token = $officialAccount->access_token->getToken();
  39. } catch (HttpException $e) {
  40. $this->setMsg('账号被封')->setCode(ErrorCodeConstants::PERMISSION_DENY)->getReturn();
  41. } catch (InvalidArgumentException $e) {
  42. $this->setMsg($e->getMessage())->setCode(ErrorCodeConstants::API_ERROR)->getReturn();
  43. } catch (\Exception $e) {
  44. $this->setMsg($e->getMessage())->setCode(ErrorCodeConstants::API_ERROR)->getReturn();
  45. }
  46. if (isset($token) && is_array($token) && array_key_exists('authorizer_access_token', $token)) {
  47. $proxy = OpenPlatformService::instance()->getProxyconfigByChannel($admin_id, null, 'job_proxy_config', true);
  48. $data = [
  49. 'appid' => $adminConfig['appid'],
  50. 'token' => $token['authorizer_access_token'],
  51. 'proxy_config' => $proxy ?: [],
  52. ];
  53. $this->setData($data)->getReturn();
  54. } else {
  55. $this->setMsg('获取token失败')->setCode(ErrorCodeConstants::API_ERROR)->getReturn();
  56. }
  57. }
  58. }