BaseService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. <?php
  2. namespace addons\StarChain\common\services;
  3. use addons\StarChain\common\api\BaseApi;
  4. use addons\StarChain\common\models\Setting;
  5. use Exception;
  6. use yii\base\BaseObject;
  7. /**
  8. * BaseService
  9. */
  10. class BaseService extends BaseObject
  11. {
  12. /**
  13. * MallId
  14. *
  15. * @var integer
  16. */
  17. public $mall_id;
  18. /**
  19. * Api
  20. *
  21. * @var BaseApi
  22. */
  23. protected $api;
  24. /**
  25. * Error
  26. *
  27. * @var string
  28. */
  29. public $error;
  30. /**
  31. * 初始化
  32. *
  33. * @param array $config
  34. */
  35. public function __construct($config)
  36. {
  37. parent::__construct($config);
  38. $this->getApi();
  39. }
  40. /**
  41. * 获取API
  42. *
  43. * @return boolean|void
  44. */
  45. public function getApi()
  46. {
  47. if ($this->mall_id) {
  48. $setting = Setting::getSetting($this->mall_id);
  49. // if (empty($setting)) return $this->error('还未配置设置');
  50. $setting && $this->api = BaseApi::getInstance([
  51. 'app_key' => $setting['app_key'],
  52. 'app_secret' => $setting['app_secret'],
  53. ]);
  54. }
  55. }
  56. /**
  57. * 执行Api
  58. *
  59. * @param string $fun
  60. * @param string $params
  61. * @return array
  62. */
  63. public function exApi($fun, $params)
  64. {
  65. try {
  66. if (empty($this->api)) {
  67. throw new Exception('未设置APPKEY');
  68. }
  69. if (method_exists($this->api, $params)) {
  70. throw new Exception('API方法不存在');
  71. }
  72. return $this->api->$fun($params);
  73. } catch (Exception $e) {
  74. return $this->error($e->getMessage());
  75. }
  76. }
  77. public function callApi(callable $fun)
  78. {
  79. try {
  80. if (empty($this->api)) {
  81. throw new Exception('未设置APPKEY');
  82. }
  83. return call_user_func($fun, $this->api);
  84. } catch (Exception $e) {
  85. return $this->error($e->getMessage());
  86. }
  87. }
  88. /**
  89. * 错误返回
  90. *
  91. * @param string $msg
  92. * @return boolean
  93. */
  94. public function error($msg = '')
  95. {
  96. $this->error = $msg;
  97. return false;
  98. }
  99. /**
  100. * 获取错误信息
  101. *
  102. * @return string
  103. */
  104. public function getErrorMsg()
  105. {
  106. return $this->error;
  107. }
  108. /**
  109. * @param array $params
  110. * @return int
  111. */
  112. public function getLimit(array $params = [])
  113. {
  114. return $params['limit'] ?? 20;
  115. }
  116. }