| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- <?php
- namespace addons\StarChain\common\services;
- use addons\StarChain\common\api\BaseApi;
- use addons\StarChain\common\models\Setting;
- use Exception;
- use yii\base\BaseObject;
- /**
- * BaseService
- */
- class BaseService extends BaseObject
- {
- /**
- * MallId
- *
- * @var integer
- */
- public $mall_id;
- /**
- * Api
- *
- * @var BaseApi
- */
- protected $api;
- /**
- * Error
- *
- * @var string
- */
- public $error;
- /**
- * 初始化
- *
- * @param array $config
- */
- public function __construct($config)
- {
- parent::__construct($config);
- $this->getApi();
- }
- /**
- * 获取API
- *
- * @return boolean|void
- */
- public function getApi()
- {
- if ($this->mall_id) {
- $setting = Setting::getSetting($this->mall_id);
- // if (empty($setting)) return $this->error('还未配置设置');
- $setting && $this->api = BaseApi::getInstance([
- 'app_key' => $setting['app_key'],
- 'app_secret' => $setting['app_secret'],
- ]);
- }
- }
- /**
- * 执行Api
- *
- * @param string $fun
- * @param string $params
- * @return array
- */
- public function exApi($fun, $params)
- {
- try {
- if (empty($this->api)) {
- throw new Exception('未设置APPKEY');
- }
- if (method_exists($this->api, $params)) {
- throw new Exception('API方法不存在');
- }
- return $this->api->$fun($params);
- } catch (Exception $e) {
- return $this->error($e->getMessage());
- }
- }
-
- public function callApi(callable $fun)
- {
- try {
- if (empty($this->api)) {
- throw new Exception('未设置APPKEY');
- }
- return call_user_func($fun, $this->api);
- } catch (Exception $e) {
- return $this->error($e->getMessage());
- }
- }
- /**
- * 错误返回
- *
- * @param string $msg
- * @return boolean
- */
- public function error($msg = '')
- {
- $this->error = $msg;
- return false;
- }
- /**
- * 获取错误信息
- *
- * @return string
- */
- public function getErrorMsg()
- {
- return $this->error;
- }
- /**
- * @param array $params
- * @return int
- */
- public function getLimit(array $params = [])
- {
- return $params['limit'] ?? 20;
- }
- }
|