YZTokenClient.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. require_once __DIR__ . '/YZApiProtocol.php';
  3. require_once __DIR__ . '/YZHttpClient.php';
  4. class YZTokenClient {
  5. private static $tokenUrl = 'https://open.youzan.com/api/oauthentry/';
  6. public function __construct($accesstoken) {
  7. if ('' == $accesstoken) throw new Exception('accesstoken不能为空');
  8. $this->accesstoken = $accesstoken;
  9. }
  10. public function get($method, $methodVersion, $params = array()) {
  11. return $this->parseResponse(
  12. YZHttpClient::get($this->url($method,$methodVersion), $this->buildRequestParams($method, $params))
  13. );
  14. }
  15. public function post($method, $methodVersion, $params = array(), $files = array()) {
  16. return $this->parseResponse(
  17. YZHttpClient::post($this->url($method,$methodVersion), $this->buildRequestParams($method, $params), $files)
  18. );
  19. }
  20. public function url($method, $methodVersion){
  21. $method_array=explode(".", $method);
  22. $method='/'.$methodVersion.'/'.$method_array[count($method_array)-1];
  23. array_pop($method_array);
  24. $method=implode(".", $method_array).$method;
  25. $url=self::$tokenUrl.$method;
  26. return $url;
  27. }
  28. private function parseResponse($responseData) {
  29. $data = json_decode($responseData, true);
  30. if (null === $data) throw new Exception('response invalid, data: ' . $responseData);
  31. return $data;
  32. }
  33. private function buildRequestParams($method, $apiParams) {
  34. if (!is_array($apiParams)) $apiParams = array();
  35. $pairs = $this->getCommonParams($this->accesstoken, $method);
  36. foreach ($apiParams as $k => $v) {
  37. if (isset($pairs[$k])) throw new Exception('参数名冲突');
  38. $pairs[$k] = $v;
  39. }
  40. return $pairs;
  41. }
  42. private function getCommonParams($accessToken, $method) {
  43. $params = array();
  44. $params[YZApiProtocol::TOKEN_KEY] = $accessToken;
  45. $params[YZApiProtocol::METHOD_KEY] = $method;
  46. return $params;
  47. }
  48. }