TaobaoService.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace app\services\ThirdParty\Taobao;
  3. use think\facade\Config;
  4. use think\facade\Log;
  5. class TaobaoService
  6. {
  7. protected $client;
  8. protected $config;
  9. protected $adzoneId;
  10. public function __construct()
  11. {
  12. // 从配置文件读取淘宝联盟配置
  13. $this->config = Config::get('third_party');
  14. // 引入淘宝SDK
  15. require_once app()->getRootPath() . 'extend/TaobaoSdk/TopSdk.php';
  16. $this->client = new \TopClient();
  17. $this->client->appkey = $this->config['taobao']['appKey'];
  18. $this->client->secretKey = $this->config['taobao']['appSecret'];
  19. // 推广位ID
  20. $this->adzoneId = $this->config['taobao']['adzoneId'];
  21. }
  22. /**
  23. * 执行API请求
  24. * @param $request
  25. * @return false|mixed
  26. */
  27. protected function execute($request)
  28. {
  29. try {
  30. $response = $this->client->execute($request);
  31. // var_dump($response);
  32. return $this->formatResponse($response);
  33. } catch (\Exception $e) {
  34. // 记录错误日志
  35. Log::error('淘宝API请求失败: ' . $e->getMessage());
  36. return false;
  37. }
  38. }
  39. /**
  40. * 格式化响应
  41. * @param $response
  42. * @return false|mixed
  43. */
  44. protected function formatResponse($response)
  45. {
  46. if (isset($response->code) && $response->code) {
  47. // API返回错误
  48. Log::error("淘宝API错误: {$response->msg} [{$response->code}]");
  49. return false;
  50. }
  51. return $response;
  52. }
  53. /**
  54. * 批量设置对象属性
  55. * @param object $object 目标对象
  56. * @param array $params 参数数组
  57. */
  58. protected function batchSetProperties($object, array $params)
  59. {
  60. foreach ($params as $key => $value) {
  61. $setter = 'set' . ucfirst($key);
  62. if (method_exists($object, $setter)) {
  63. $object->$setter($value);
  64. }
  65. }
  66. }
  67. }